diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index fc6941ea..c6801d59 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -51,8 +51,8 @@ use crate::fundamentals::FiscalPeriod; use crate::ilp::IlpWriterOptions; use crate::ilp_send::SendIlpArgs; use crate::mongo_stream::{ - MongoCliOptions, MongoUriSource, DEFAULT_MONGO_BATCH_SIZE, DEFAULT_MONGO_URI_ENV, - MAX_MONGO_BATCH_SIZE, + redact_embedded_mongo_uris, MongoCliOptions, MongoUriSource, DEFAULT_MONGO_BATCH_SIZE, + DEFAULT_MONGO_URI_ENV, MAX_MONGO_BATCH_SIZE, }; use crate::run_curate_adj::CurateAdjFactorsArgs; use crate::run_curate_bars::{ @@ -66,13 +66,17 @@ use crate::run_curate_fundamentals::{ }; use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL}; use crate::run_curate_fx_1m::CurateFx1mArgs; +use crate::run_curate_macro::CurateMacroArgs; use crate::run_curate_posts::{ CuratePostsArgs, DEFAULT_MAPPING_SOURCE as DEFAULT_POSTS_MAPPING_SOURCE, }; +use crate::run_curate_qm_bars_1m::{CurateQmBars1mArgs, DEFAULT_QM_BARS_1M_MAPPING_SOURCE}; use crate::run_curate_shorts::{CurateShortsArgs, DEFAULT_MAPPING_SOURCE}; use crate::run_mongo::{ - CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs, - CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, + CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateBars1mMongoArgs, + CurateCorporateActionsMongoArgs, CurateEventsMongoArgs, CurateFundamentalsMongoArgs, + CurateFx1dMongoArgs, CurateFx1mMongoArgs, CurateMacroMongoArgs, CuratePostsMongoArgs, + CurateQmBars1mMongoArgs, CurateShortsMongoArgs, }; /// Parsed CLI command to execute. @@ -94,9 +98,17 @@ pub enum CliAction { CurateEvents(CurateEventsArgs), CurateEventsMongo(CurateEventsMongoArgs), CurateBars1m(CurateBars1mArgs), + CurateBars1mMongo(CurateBars1mMongoArgs), + CurateQmBars1m(CurateQmBars1mArgs), + CurateQmBars1mMongo(CurateQmBars1mMongoArgs), CurateFx1m(CurateFx1mArgs), + CurateFx1mMongo(CurateFx1mMongoArgs), CuratePosts(CuratePostsArgs), + CuratePostsMongo(CuratePostsMongoArgs), CurateFundamentals(CurateFundamentalsArgs), + CurateFundamentalsMongo(CurateFundamentalsMongoArgs), + CurateMacro(CurateMacroArgs), + CurateMacroMongo(CurateMacroMongoArgs), SendIlp(SendIlpArgs), BenchSplit(usize), BenchAdj(usize), @@ -159,14 +171,24 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ {name} curate-events --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ Curate events from qmFilings + qmEarnings BSON or read-only MongoDB + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\ - {name} curate-bars-1m --eod-intraday --qm-splits --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ - Curate split-unadjusted 1-minute bars from eodIntraday1M + qmSplits BSON + provider_mapping TSV into bars_1m.shard-.ilp (default --mapping-source: {DEFAULT_BARS_1M_MAPPING_SOURCE})\n\ + {name} curate-bars-1m --eod-intraday --qm-splits (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ + {name} curate-bars-1m --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ + Curate split-unadjusted 1-minute bars from eodIntraday1M + qmSplits BSON or read-only MongoDB + provider_mapping TSV into bars_1m.shard-.ilp (default --mapping-source: {DEFAULT_BARS_1M_MAPPING_SOURCE})\n\ + {name} curate-qm-bars-1m --qm-intraday (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ + {name} curate-qm-bars-1m --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ + Curate raw 1-minute QuoteMedia bars from qmIntraday BSON or read-only MongoDB + provider_mapping TSV into bars_1m_qm.shard-.ilp (default --mapping-source: {DEFAULT_QM_BARS_1M_MAPPING_SOURCE})\n\ {name} curate-fx-1m --eod-intraday --out --shards \n\ - Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-.ilp\n\ - {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ - Curate ceoPosts from BSON + provider_mapping TSV into /events/year=YYYY/part.parquet using a dedicated --out directory (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\ - {name} curate-fundamentals --qm-financials --qm-filings --provider-mapping --listing-venues --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ - Curate point-in-time fundamentals from qmFinancials + qmFilings BSON + provider_mapping/listing_venues TSVs into fundamentals_pit/year=YYYY/part.parquet (file mode only; defaults: --financials-key-field {DEFAULT_QM_FINANCIALS_KEY_FIELD}, --period-end-field {DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD}, --report-date-field {DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD}, --report-period-field {DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD}, --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --mapping-source {DEFAULT_FUNDAMENTALS_MAPPING_SOURCE})\n\ + {name} curate-fx-1m --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] [--date-gte ] [--date-lt ] --out --shards \n\ + Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON or read-only MongoDB into fx_1m.shard-.ilp\n\ + {name} curate-posts --ceo-posts (--curate-inputs | --provider-mapping ) --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ + {name} curate-posts --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] (--curate-inputs | --provider-mapping ) --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ + Curate ceoPosts from BSON or read-only MongoDB + provider_mapping TSV into /events/year=YYYY/part-posts.parquet (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\ + {name} curate-fundamentals --qm-financials [--qm-financials-old ] --qm-filings (--curate-inputs | --provider-mapping --listing-venues ) --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ + {name} curate-fundamentals --from-mongo [--mongo-uri-env | --mongo-uri ] [--with-qm-financials-old] [--batch-size ] [--limit ] (--curate-inputs | --provider-mapping --listing-venues ) --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ + Curate point-in-time fundamentals from qmFinancials (+ optional qmFinancials-old) + qmFilings BSON or read-only MongoDB + provider_mapping/listing_venues TSVs into fundamentals_pit/year=YYYY/part.parquet (defaults: --financials-key-field {DEFAULT_QM_FINANCIALS_KEY_FIELD}, --period-end-field {DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD}, --report-date-field {DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD}, --report-period-field {DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD}, --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --mapping-source {DEFAULT_FUNDAMENTALS_MAPPING_SOURCE})\n\ + {name} curate-macro --te-data --series-map --out \n\ + {name} curate-macro --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] --series-map --out \n\ + Curate macroeconomic series from teData BSON or read-only MongoDB + caller-owned series_map TSV into macro/part.parquet\n\ {name} send-ilp --dir --prefix --addr \n\ Stream published ILP v2 shard files to an explicit QuestDB TCP endpoint (no default address; success means bytes were accepted by local sockets, not rows committed — verify row counts via PGWire; ILP v2 binary doubles over TCP on QuestDB 10.2.0 are unverified until the manual quant load check)\n\ {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ @@ -217,10 +239,12 @@ pub fn format_usage_stderr(name: &str) -> String { {name} curate-fx-1d --eod-prices --te-market-data [--te-symbol ] --out \n\ {name} curate-shorts --ceo-shorts --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ - {name} curate-bars-1m --eod-intraday --qm-splits --provider-mapping --out --shards --known-at-micros [--mapping-source ]\n\ + {name} curate-bars-1m --eod-intraday --qm-splits (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ + {name} curate-qm-bars-1m --qm-intraday (--curate-inputs | --provider-mapping ) --out --shards --known-at-micros [--mapping-source ]\n\ {name} curate-fx-1m --eod-intraday --out --shards \n\ - {name} curate-posts --ceo-posts --provider-mapping --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ - {name} curate-fundamentals --qm-financials --qm-filings --provider-mapping --listing-venues --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ + {name} curate-posts --ceo-posts (--curate-inputs | --provider-mapping ) --out --timestamp-unit [--key-field ] [--spiel-id-field ] [--timestamp-field ] [--edited-field ] [--bot-field ] [--user-id-field ] [--text-field ] [--mapping-source ]\n\ + {name} curate-fundamentals --qm-financials [--qm-financials-old ] --qm-filings (--curate-inputs | --provider-mapping --listing-venues ) --out --currency-field --filings-form-type-field --k (--fiscal-period | [--quarterly-tokens ] [--annual-tokens ]) [--financials-key-field ] [--period-end-field ] [--report-date-field ] [--report-period-field ] [--revenue-field ] [--net-income-field ] [--operating-cash-flow-field ] [--total-assets-field ] [--total-equity-field ] [--shares-outstanding-field ] [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--mapping-source ]\n\ + {name} curate-macro --te-data --series-map --out \n\ {name} send-ilp --dir --prefix --addr \n\ {name} bench-split [rows]\n\ {name} bench-adj [events]\n\ @@ -1194,8 +1218,51 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result { Ok(CliAction::CurateShorts(parsed)) } +fn resolve_provider_mapping_input( + curate_inputs: Option, + provider_mapping: Option, +) -> Result { + if let Some(inputs_dir) = curate_inputs { + if provider_mapping.is_some() { + return Err("cannot combine '--curate-inputs' with '--provider-mapping'".to_string()); + } + let pinned = pin_curate_inputs_dir(&inputs_dir)?; + Ok(pinned.join("provider_mapping.tsv")) + } else { + provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string()) + } +} + +fn resolve_fundamentals_tsv_inputs( + curate_inputs: Option, + provider_mapping: Option, + listing_venues: Option, +) -> Result<(PathBuf, PathBuf), String> { + if let Some(inputs_dir) = curate_inputs { + if provider_mapping.is_some() { + return Err("cannot combine '--curate-inputs' with '--provider-mapping'".to_string()); + } + if listing_venues.is_some() { + return Err("cannot combine '--curate-inputs' with '--listing-venues'".to_string()); + } + let pinned = pin_curate_inputs_dir(&inputs_dir)?; + Ok(( + pinned.join("provider_mapping.tsv"), + pinned.join("listing_venues.tsv"), + )) + } else { + let pm = provider_mapping + .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; + let lv = listing_venues + .ok_or_else(|| "missing required flag '--listing-venues'".to_string())?; + Ok((pm, lv)) + } +} + fn parse_curate_posts_args(args: &[&str]) -> Result { + let mut mongo = MongoFlagState::default(); let mut ceo_posts: Option = None; + let mut curate_inputs: Option = None; let mut provider_mapping: Option = None; let mut out_dir: Option = None; let mut timestamp_unit: Option = None; @@ -1217,23 +1284,13 @@ fn parse_curate_posts_args(args: &[&str]) -> Result { )); } - let flag_name = token.split_once('=').map_or(token, |(k, _)| k); - if !matches!( - flag_name, - "--ceo-posts" - | "--provider-mapping" - | "--out" - | "--timestamp-unit" - | "--key-field" - | "--spiel-id-field" - | "--timestamp-field" - | "--edited-field" - | "--bot-field" - | "--user-id-field" - | "--text-field" - | "--mapping-source" - ) { - return Err(format!("unknown flag '{flag_name}' for curate-posts")); + if token == "--from-mongo" { + if mongo.from_mongo { + return Err("duplicate flag '--from-mongo'".to_string()); + } + mongo.from_mongo = true; + i += 1; + continue; } let (flag, value) = if let Some((k, v)) = token.split_once('=') { @@ -1250,8 +1307,13 @@ fn parse_curate_posts_args(args: &[&str]) -> Result { (token, v) }; + if mongo.try_parse_value_flag(flag, value, false)? { + continue; + } + match flag { "--ceo-posts" => set_path(&mut ceo_posts, "--ceo-posts", value)?, + "--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?, "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, "--out" => set_path(&mut out_dir, "--out", value)?, "--timestamp-unit" => { @@ -1280,9 +1342,66 @@ fn parse_curate_posts_args(args: &[&str]) -> Result { } } + if mongo.from_mongo { + if ceo_posts.is_some() { + return Err("cannot combine '--from-mongo' with '--ceo-posts'".to_string()); + } + let mongo_opts = mongo.build_options()?; + let provider_mapping = resolve_provider_mapping_input(curate_inputs, provider_mapping)?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let timestamp_unit = + timestamp_unit.ok_or_else(|| "missing required flag '--timestamp-unit'".to_string())?; + let key_field = key_field.unwrap_or_else(|| DEFAULT_POSTS_KEY_FIELD.to_string()); + let spiel_id_field = + spiel_id_field.unwrap_or_else(|| DEFAULT_POSTS_SPIEL_ID_FIELD.to_string()); + let timestamp_field = + timestamp_field.unwrap_or_else(|| DEFAULT_POSTS_TIMESTAMP_FIELD.to_string()); + let edited_field = edited_field.unwrap_or_else(|| DEFAULT_POSTS_EDITED_FIELD.to_string()); + let bot_field = bot_field.unwrap_or_else(|| DEFAULT_POSTS_BOT_FIELD.to_string()); + let user_id_field = + user_id_field.unwrap_or_else(|| DEFAULT_POSTS_USER_ID_FIELD.to_string()); + let text_field = text_field.unwrap_or_else(|| DEFAULT_POSTS_TEXT_FIELD.to_string()); + let mapping_source = + mapping_source.unwrap_or_else(|| DEFAULT_POSTS_MAPPING_SOURCE.to_string()); + + let check = CuratePostsArgs { + ceo_posts: PathBuf::from("mongodb://ceoPosts"), + provider_mapping: provider_mapping.clone(), + out_dir: out_dir.clone(), + timestamp_unit, + key_field: key_field.clone(), + spiel_id_field: spiel_id_field.clone(), + timestamp_field: timestamp_field.clone(), + edited_field: edited_field.clone(), + bot_field: bot_field.clone(), + user_id_field: user_id_field.clone(), + text_field: text_field.clone(), + mapping_source: mapping_source.clone(), + }; + check.field_names().validate().map_err(|e| e.to_string())?; + + return Ok(CliAction::CuratePostsMongo(CuratePostsMongoArgs { + mongo: mongo_opts, + provider_mapping, + out_dir, + timestamp_unit, + key_field, + spiel_id_field, + timestamp_field, + edited_field, + bot_field, + user_id_field, + text_field, + mapping_source, + })); + } + + if mongo.has_any_mongo_option() { + return Err("MongoDB streaming flags require '--from-mongo'".to_string()); + } + let ceo_posts = ceo_posts.ok_or_else(|| "missing required flag '--ceo-posts'".to_string())?; - let provider_mapping = - provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; + let provider_mapping = resolve_provider_mapping_input(curate_inputs, provider_mapping)?; let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; let timestamp_unit = timestamp_unit.ok_or_else(|| "missing required flag '--timestamp-unit'".to_string())?; @@ -1331,8 +1450,12 @@ fn parse_curate_fundamentals_args(args: &[&str]) -> Result { } fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result { + let mut mongo = MongoFlagState::default(); + let mut with_qm_financials_old = false; let mut qm_financials: Option = None; + let mut qm_financials_old: Option = None; let mut qm_filings: Option = None; + let mut curate_inputs: Option = None; let mut provider_mapping: Option = None; let mut listing_venues: Option = None; let mut out_dir: Option = None; @@ -1367,11 +1490,34 @@ fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result Result set_path(&mut qm_financials, "--qm-financials", value)?, + "--qm-financials-old" => { + set_path(&mut qm_financials_old, "--qm-financials-old", value)?; + } "--qm-filings" => set_path(&mut qm_filings, "--qm-filings", value)?, + "--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?, "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, "--listing-venues" => set_path(&mut listing_venues, "--listing-venues", value)?, "--out" => set_path(&mut out_dir, "--out", value)?, @@ -1523,14 +1677,110 @@ fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result { + return Err( + "cannot combine '--fiscal-period' with '--quarterly-tokens' or '--annual-tokens'" + .to_string(), + ); + } + (Some(fixed), None, None) => CurateFundamentalsFiscalPeriod::Fixed(fixed), + (None, Some(quarterly), Some(annual)) => { + CurateFundamentalsFiscalPeriod::ByTokens { quarterly, annual } + } + (None, Some(quarterly), None) => CurateFundamentalsFiscalPeriod::ByTokens { + quarterly, + annual: Vec::new(), + }, + (None, None, Some(annual)) => CurateFundamentalsFiscalPeriod::ByTokens { + quarterly: Vec::new(), + annual, + }, + (None, None, None) => { + return Err( + "missing required fiscal-period mode: pass either '--fiscal-period ' or '--quarterly-tokens' / '--annual-tokens'" + .to_string(), + ); + } + }; + + let parsed = CurateFundamentalsMongoArgs { + mongo: mongo_opts, + with_qm_financials_old, + provider_mapping, + listing_venues, + out_dir, + financials_key_field: financials_key_field + .unwrap_or_else(|| DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string()), + financials_period_end_field: period_end_field + .unwrap_or_else(|| DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string()), + financials_report_date_field: report_date_field + .unwrap_or_else(|| DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string()), + financials_report_period_field: report_period_field + .unwrap_or_else(|| DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string()), + financials_currency_field: currency_field, + financials_revenue_field: revenue_field, + financials_net_income_field: net_income_field, + financials_operating_cash_flow_field: operating_cash_flow_field, + financials_total_assets_field: total_assets_field, + financials_total_equity_field: total_equity_field, + financials_shares_outstanding_field: shares_outstanding_field, + fiscal_period, + filings_key_field: filings_key_field + .unwrap_or_else(|| DEFAULT_FILINGS_KEY_FIELD.to_string()), + filings_timefiled_field: filings_timefiled_field + .unwrap_or_else(|| DEFAULT_FILINGS_TIMEFILED_FIELD.to_string()), + filings_form_type_field, + filings_filing_id_field, + filings_url_field, + mapping_source: mapping_source + .unwrap_or_else(|| DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string()), + k, + }; + let check = parsed.to_file_args(); + check + .financials_field_names() + .validate() + .map_err(|e| e.to_string())?; + check + .filings_field_names() + .validate() + .map_err(|e| e.to_string())?; + check + .fiscal_period + .with_borrowed(|period| period.validate()) + .map_err(|e| e.to_string())?; + + return Ok(CliAction::CurateFundamentalsMongo(parsed)); + } + + if mongo.has_any_mongo_option() || with_qm_financials_old { + return Err("MongoDB streaming flags require '--from-mongo'".to_string()); + } + let qm_financials = qm_financials.ok_or_else(|| "missing required flag '--qm-financials'".to_string())?; let qm_filings = qm_filings.ok_or_else(|| "missing required flag '--qm-filings'".to_string())?; - let provider_mapping = - provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; - let listing_venues = - listing_venues.ok_or_else(|| "missing required flag '--listing-venues'".to_string())?; + let (provider_mapping, listing_venues) = + resolve_fundamentals_tsv_inputs(curate_inputs, provider_mapping, listing_venues)?; let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; let currency_field = currency_field.ok_or_else(|| "missing required flag '--currency-field'".to_string())?; @@ -1582,6 +1832,7 @@ fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result Result { } fn parse_curate_bars_1m_args(args: &[&str]) -> Result { + let mut mongo = MongoFlagState::default(); let mut intraday_path: Option = None; let mut splits_path: Option = None; + let mut curate_inputs: Option = None; let mut provider_mapping_path: Option = None; let mut out_dir: Option = None; let mut shard_count: Option = None; @@ -1917,21 +2170,13 @@ fn parse_curate_bars_1m_args(args: &[&str]) -> Result { )); } - let flag_name = token.split_once('=').map_or(token, |(k, _)| k); - if matches!( - flag_name, - "--from-mongo" - | "--mongo-uri" - | "--mongo-uri-env" - | "--batch-size" - | "--limit" - | "--date-gte" - | "--date-lt" - | "--with-qm-prices" - ) { - return Err(format!( - "MongoDB streaming flag '{flag_name}' is not supported by curate-bars-1m (file mode only)" - )); + if token == "--from-mongo" { + if mongo.from_mongo { + return Err("duplicate flag '--from-mongo'".to_string()); + } + mongo.from_mongo = true; + i += 1; + continue; } let (flag, value) = if let Some((k, v)) = token.split_once('=') { @@ -1948,31 +2193,14 @@ fn parse_curate_bars_1m_args(args: &[&str]) -> Result { (token, v) }; - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(PathBuf::from(raw)); - Ok(()) - }; - - let set_name = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); - } - if raw.trim().is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); - } - *slot = Some(raw.to_string()); - Ok(()) - }; + if mongo.try_parse_value_flag(flag, value, true)? { + continue; + } match flag { "--eod-intraday" => set_path(&mut intraday_path, "--eod-intraday", value)?, "--qm-splits" => set_path(&mut splits_path, "--qm-splits", value)?, + "--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?, "--provider-mapping" => { set_path(&mut provider_mapping_path, "--provider-mapping", value)?; } @@ -2028,12 +2256,43 @@ fn parse_curate_bars_1m_args(args: &[&str]) -> Result { } } + if mongo.from_mongo { + if intraday_path.is_some() || splits_path.is_some() { + return Err( + "cannot combine '--from-mongo' with '--eod-intraday' or '--qm-splits'".to_string(), + ); + } + let mongo_opts = mongo.build_options()?; + let provider_mapping_path = + resolve_provider_mapping_input(curate_inputs, provider_mapping_path)?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let shard_count = + shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; + let known_at_micros = known_at_micros + .ok_or_else(|| "missing required flag '--known-at-micros'".to_string())?; + return Ok(CliAction::CurateBars1mMongo(CurateBars1mMongoArgs { + mongo: mongo_opts, + provider_mapping_path, + out_dir, + mapping_source: mapping_source + .unwrap_or_else(|| DEFAULT_BARS_1M_MAPPING_SOURCE.to_string()), + shard_count, + known_at_micros, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + })); + } + + if mongo.has_any_mongo_option() { + return Err("MongoDB streaming flags require '--from-mongo'".to_string()); + } + let intraday_path = intraday_path.ok_or_else(|| "missing required flag '--eod-intraday'".to_string())?; let splits_path = splits_path.ok_or_else(|| "missing required flag '--qm-splits'".to_string())?; - let provider_mapping_path = provider_mapping_path - .ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; + let provider_mapping_path = + resolve_provider_mapping_input(curate_inputs, provider_mapping_path)?; let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; let shard_count = shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; @@ -2054,35 +2313,32 @@ fn parse_curate_bars_1m_args(args: &[&str]) -> Result { })) } -fn parse_curate_fx_1m_args(args: &[&str]) -> Result { +fn parse_curate_qm_bars_1m_args(args: &[&str]) -> Result { + let mut mongo = MongoFlagState::default(); let mut intraday_path: Option = None; + let mut curate_inputs: Option = None; + let mut provider_mapping_path: Option = None; let mut out_dir: Option = None; let mut shard_count: Option = None; + let mut known_at_micros: Option = None; + let mut mapping_source: Option = None; let mut i = 0usize; while i < args.len() { let token = args[i]; if !token.starts_with("--") { return Err(format!( - "unexpected positional argument '{token}' for curate-fx-1m" + "unexpected positional argument '{token}' for curate-qm-bars-1m" )); } - let flag_name = token.split_once('=').map_or(token, |(k, _)| k); - if matches!( - flag_name, - "--from-mongo" - | "--mongo-uri" - | "--mongo-uri-env" - | "--batch-size" - | "--limit" - | "--date-gte" - | "--date-lt" - | "--with-qm-prices" - ) { - return Err(format!( - "MongoDB streaming flag '{flag_name}' is not supported by curate-fx-1m (file mode only)" - )); + if token == "--from-mongo" { + if mongo.from_mongo { + return Err("duplicate flag '--from-mongo'".to_string()); + } + mongo.from_mongo = true; + i += 1; + continue; } let (flag, value) = if let Some((k, v)) = token.split_once('=') { @@ -2099,17 +2355,162 @@ fn parse_curate_fx_1m_args(args: &[&str]) -> Result { (token, v) }; - let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { - if slot.is_some() { - return Err(format!("duplicate flag '{flag_name}'")); + if mongo.try_parse_value_flag(flag, value, true)? { + continue; + } + + match flag { + "--qm-intraday" => set_path(&mut intraday_path, "--qm-intraday", value)?, + "--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?, + "--provider-mapping" => { + set_path(&mut provider_mapping_path, "--provider-mapping", value)?; } - if raw.is_empty() { - return Err(format!("empty value for flag '{flag_name}'")); + "--out" => set_path(&mut out_dir, "--out", value)?, + "--shards" => { + if shard_count.is_some() { + return Err("duplicate flag '--shards'".to_string()); + } + if value.is_empty() { + return Err("empty value for flag '--shards'".to_string()); + } + if !value.bytes().all(|b| b.is_ascii_digit()) { + return Err(format!( + "invalid --shards '{value}' (expected a positive integer >= 1)" + )); + } + let parsed = value.parse::().map_err(|_| { + format!("invalid --shards '{value}' (expected a positive integer >= 1)") + })?; + if parsed == 0 { + return Err(format!( + "invalid --shards '{value}' (expected a positive integer >= 1)" + )); + } + shard_count = Some(parsed); } - *slot = Some(PathBuf::from(raw)); - Ok(()) + "--known-at-micros" => { + if known_at_micros.is_some() { + return Err("duplicate flag '--known-at-micros'".to_string()); + } + if value.is_empty() { + return Err("empty value for flag '--known-at-micros'".to_string()); + } + if !value.bytes().all(|b| b.is_ascii_digit()) { + return Err(format!( + "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" + )); + } + let parsed = value.parse::().map_err(|_| { + format!( + "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" + ) + })?; + if parsed <= 0 { + return Err(format!( + "invalid --known-at-micros '{value}' (expected a positive 64-bit integer >= 1)" + )); + } + known_at_micros = Some(parsed); + } + "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, + other => return Err(format!("unknown flag '{other}' for curate-qm-bars-1m")), + } + } + + if mongo.from_mongo { + if intraday_path.is_some() { + return Err("cannot combine '--from-mongo' with '--qm-intraday'".to_string()); + } + let mongo_opts = mongo.build_options()?; + let provider_mapping_path = + resolve_provider_mapping_input(curate_inputs, provider_mapping_path)?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let shard_count = + shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; + let known_at_micros = known_at_micros + .ok_or_else(|| "missing required flag '--known-at-micros'".to_string())?; + return Ok(CliAction::CurateQmBars1mMongo(CurateQmBars1mMongoArgs { + mongo: mongo_opts, + provider_mapping_path, + out_dir, + mapping_source: mapping_source + .unwrap_or_else(|| DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string()), + shard_count, + known_at_micros, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + })); + } + + if mongo.has_any_mongo_option() { + return Err("MongoDB streaming flags require '--from-mongo'".to_string()); + } + + let intraday_path = + intraday_path.ok_or_else(|| "missing required flag '--qm-intraday'".to_string())?; + let provider_mapping_path = + resolve_provider_mapping_input(curate_inputs, provider_mapping_path)?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let shard_count = + shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; + let known_at_micros = + known_at_micros.ok_or_else(|| "missing required flag '--known-at-micros'".to_string())?; + + Ok(CliAction::CurateQmBars1m(CurateQmBars1mArgs { + intraday_path, + provider_mapping_path, + out_dir, + mapping_source: mapping_source + .unwrap_or_else(|| DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string()), + shard_count, + known_at_micros, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + })) +} + +fn parse_curate_fx_1m_args(args: &[&str]) -> Result { + let mut mongo = MongoFlagState::default(); + let mut intraday_path: Option = None; + let mut out_dir: Option = None; + let mut shard_count: Option = None; + + let mut i = 0usize; + while i < args.len() { + let token = args[i]; + if !token.starts_with("--") { + return Err(format!( + "unexpected positional argument '{token}' for curate-fx-1m" + )); + } + + if token == "--from-mongo" { + if mongo.from_mongo { + return Err("duplicate flag '--from-mongo'".to_string()); + } + mongo.from_mongo = true; + i += 1; + continue; + } + + let (flag, value) = if let Some((k, v)) = token.split_once('=') { + i += 1; + (k, v) + } else { + let Some(&v) = args.get(i + 1) else { + return Err(format!("missing value for flag '{token}'")); + }; + if v.starts_with("--") { + return Err(format!("missing value for flag '{token}'")); + } + i += 2; + (token, v) }; + if mongo.try_parse_value_flag(flag, value, true)? { + continue; + } + match flag { "--eod-intraday" => set_path(&mut intraday_path, "--eod-intraday", value)?, "--out" => set_path(&mut out_dir, "--out", value)?, @@ -2139,6 +2540,27 @@ fn parse_curate_fx_1m_args(args: &[&str]) -> Result { } } + if mongo.from_mongo { + if intraday_path.is_some() { + return Err("cannot combine '--from-mongo' with '--eod-intraday'".to_string()); + } + let mongo_opts = mongo.build_options()?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let shard_count = + shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; + return Ok(CliAction::CurateFx1mMongo(CurateFx1mMongoArgs { + mongo: mongo_opts, + out_dir, + shard_count, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + })); + } + + if mongo.has_any_mongo_option() { + return Err("MongoDB streaming flags require '--from-mongo'".to_string()); + } + let intraday_path = intraday_path.ok_or_else(|| "missing required flag '--eod-intraday'".to_string())?; let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; @@ -2154,6 +2576,87 @@ fn parse_curate_fx_1m_args(args: &[&str]) -> Result { })) } +fn parse_curate_macro_args(args: &[&str]) -> Result { + let mut mongo = MongoFlagState::default(); + let mut te_data: Option = None; + let mut series_map: Option = None; + let mut out_dir: Option = None; + + let mut i = 0usize; + while i < args.len() { + let token = args[i]; + if !token.starts_with("--") { + return Err(format!( + "unexpected positional argument '{token}' for curate-macro" + )); + } + + if token == "--from-mongo" { + if mongo.from_mongo { + return Err("duplicate flag '--from-mongo'".to_string()); + } + mongo.from_mongo = true; + i += 1; + continue; + } + + let (flag, value) = if let Some((k, v)) = token.split_once('=') { + i += 1; + (k, v) + } else { + let Some(&v) = args.get(i + 1) else { + return Err(format!("missing value for flag '{token}'")); + }; + if v.starts_with("--") { + return Err(format!("missing value for flag '{token}'")); + } + i += 2; + (token, v) + }; + + if mongo.try_parse_value_flag(flag, value, false)? { + continue; + } + + match flag { + "--te-data" => set_path(&mut te_data, "--te-data", value)?, + "--series-map" => set_path(&mut series_map, "--series-map", value)?, + "--out" => set_path(&mut out_dir, "--out", value)?, + other => return Err(format!("unknown flag '{other}' for curate-macro")), + } + } + + if mongo.from_mongo { + if te_data.is_some() { + return Err("cannot combine '--from-mongo' with '--te-data'".to_string()); + } + let mongo_opts = mongo.build_options()?; + let series_map = + series_map.ok_or_else(|| "missing required flag '--series-map'".to_string())?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + return Ok(CliAction::CurateMacroMongo(CurateMacroMongoArgs { + mongo: mongo_opts, + series_map, + out_dir, + })); + } + + if mongo.has_any_mongo_option() { + return Err("MongoDB streaming flags require '--from-mongo'".to_string()); + } + + let te_data = te_data.ok_or_else(|| "missing required flag '--te-data'".to_string())?; + let series_map = + series_map.ok_or_else(|| "missing required flag '--series-map'".to_string())?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + + Ok(CliAction::CurateMacro(CurateMacroArgs { + te_data, + series_map, + out_dir, + })) +} + const ALLOWED_SEND_ILP_PREFIXES: [&str; 3] = ["bars_1m", "bars_1m_qm", "fx_1m"]; fn parse_send_ilp_args(args: &[&str]) -> Result { @@ -2228,8 +2731,16 @@ fn parse_send_ilp_args(args: &[&str]) -> Result { Ok(CliAction::SendIlp(SendIlpArgs { dir, prefix, addr })) } +fn redact_cli_error_secrets(msg: String) -> String { + redact_embedded_mongo_uris(&msg) +} + /// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`]. pub fn parse_args(args: &[String]) -> Result { + parse_args_inner(args).map_err(redact_cli_error_secrets) +} + +fn parse_args_inner(args: &[String]) -> Result { let slices: Vec<&str> = args.iter().map(String::as_str).collect(); match slices.as_slice() { [] | ["--help"] | ["-h"] => Ok(CliAction::Help), @@ -2244,9 +2755,11 @@ pub fn parse_args(args: &[String]) -> Result { ["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest), ["curate-events", rest @ ..] => parse_curate_events_args(rest), ["curate-bars-1m", rest @ ..] => parse_curate_bars_1m_args(rest), + ["curate-qm-bars-1m", rest @ ..] => parse_curate_qm_bars_1m_args(rest), ["curate-fx-1m", rest @ ..] => parse_curate_fx_1m_args(rest), ["curate-posts", rest @ ..] => parse_curate_posts_args(rest), ["curate-fundamentals", rest @ ..] => parse_curate_fundamentals_args(rest), + ["curate-macro", rest @ ..] => parse_curate_macro_args(rest), ["send-ilp", rest @ ..] => parse_send_ilp_args(rest), ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), ["bench-split", raw] => match raw.parse::() { @@ -4560,50 +5073,77 @@ mod tests { } #[test] - fn parse_curate_bars_1m_rejects_all_mongo_streaming_flags_without_echoing_values() { - let mongo_flags = [ - "--from-mongo", - "--mongo-uri", - "--mongo-uri-env", - "--batch-size", - "--limit", - "--date-gte", - "--date-lt", - "--with-qm-prices", - ]; - + fn parse_curate_bars_1m_mongo_flags_and_mixing_rules_hide_secrets() { let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock"; - for flag in mongo_flags { - // Bare form (at end of argv). - let err_bare = parse_args(&to_args(&["curate-bars-1m", flag])).unwrap_err(); - assert!( - err_bare.contains(flag) && err_bare.contains("file mode only"), - "bare {flag} should fail with file-mode error, got: {err_bare}" - ); - // Separated value form. - let err_sep = parse_args(&to_args(&["curate-bars-1m", flag, secret])).unwrap_err(); - assert!( - err_sep.contains(flag) && err_sep.contains("file mode only"), - "separated {flag} should fail with file-mode error, got: {err_sep}" - ); - assert!( - !err_sep.contains("s3cr3t_pw"), - "separated {flag} error leaked value: {err_sep}" - ); + // Mongo options without --from-mongo fail with clear message and no secret leak. + let err = parse_args(&to_args(&[ + "curate-bars-1m", + "--eod-intraday", + "i.bson", + "--qm-splits", + "s.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + &format!("--mongo-uri={secret}"), + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err.contains("s3cr3t_pw")); - // Equals form. - let eq_token = format!("{flag}={secret}"); - let err_eq = parse_args(&to_args(&["curate-bars-1m", &eq_token])).unwrap_err(); - assert!( - err_eq.contains(flag) && err_eq.contains("file mode only"), - "equals {flag} should fail with file-mode error, got: {err_eq}" - ); - assert!( - !err_eq.contains("s3cr3t_pw"), - "equals {flag} error leaked value: {err_eq}" - ); - } + // Combining --from-mongo with file-mode BSON flags fails closed. + let err = parse_args(&to_args(&[ + "curate-bars-1m", + "--from-mongo", + "--eod-intraday", + "i.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + ])) + .unwrap_err(); + assert_eq!( + err, + "cannot combine '--from-mongo' with '--eod-intraday' or '--qm-splits'" + ); + + // Valid --from-mongo invocation with date bounds. + let parsed = parse_args(&to_args(&[ + "curate-bars-1m", + "--from-mongo", + "--date-gte", + "2024-01-01", + "--date-lt", + "2024-01-02", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "4", + "--known-at-micros", + "1735689600000000", + ])) + .expect("valid curate-bars-1m --from-mongo"); + assert!(matches!( + parsed, + CliAction::CurateBars1mMongo(CurateBars1mMongoArgs { + shard_count: 4, + known_at_micros: 1_735_689_600_000_000, + .. + }) + )); } #[test] @@ -4800,45 +5340,56 @@ mod tests { } #[test] - fn parse_curate_fx_1m_rejects_all_mongo_streaming_flags_without_echoing_values() { - let mongo_flags = [ - "--from-mongo", - "--mongo-uri", - "--mongo-uri-env", - "--batch-size", - "--limit", - "--date-gte", - "--date-lt", - "--with-qm-prices", - ]; - + fn parse_curate_fx_1m_mongo_flags_and_mixing_rules_hide_secrets() { let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock"; - for flag in mongo_flags { - let expected = format!( - "MongoDB streaming flag '{flag}' is not supported by curate-fx-1m (file mode only)" - ); - // Bare form (at end of argv). - let err_bare = parse_args(&to_args(&["curate-fx-1m", flag])).unwrap_err(); - assert_eq!(err_bare, expected, "bare {flag} error mismatch"); + let err = parse_args(&to_args(&[ + "curate-fx-1m", + "--eod-intraday", + "i.bson", + "--out", + "o", + "--shards", + "2", + &format!("--mongo-uri={secret}"), + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err.contains("s3cr3t_pw")); - // Separated value form. - let err_sep = parse_args(&to_args(&["curate-fx-1m", flag, secret])).unwrap_err(); - assert_eq!(err_sep, expected, "separated {flag} error mismatch"); - assert!( - !err_sep.contains("s3cr3t_pw"), - "separated {flag} error leaked value: {err_sep}" - ); + let err = parse_args(&to_args(&[ + "curate-fx-1m", + "--from-mongo", + "--eod-intraday", + "i.bson", + "--out", + "o", + "--shards", + "2", + ])) + .unwrap_err(); + assert_eq!( + err, + "cannot combine '--from-mongo' with '--eod-intraday'" + ); - // Equals form. - let eq_token = format!("{flag}={secret}"); - let err_eq = parse_args(&to_args(&["curate-fx-1m", &eq_token])).unwrap_err(); - assert_eq!(err_eq, expected, "equals {flag} error mismatch"); - assert!( - !err_eq.contains("s3cr3t_pw"), - "equals {flag} error leaked value: {err_eq}" - ); - } + let parsed = parse_args(&to_args(&[ + "curate-fx-1m", + "--from-mongo", + "--date-gte", + "2024-01-01", + "--date-lt", + "2024-01-02", + "--out", + "o", + "--shards", + "4", + ])) + .expect("valid curate-fx-1m --from-mongo"); + assert!(matches!( + parsed, + CliAction::CurateFx1mMongo(CurateFx1mMongoArgs { shard_count: 4, .. }) + )); } #[test] @@ -5108,23 +5659,51 @@ mod tests { .unwrap_err(); assert_eq!(err, "unknown flag '--bogus' for curate-posts"); - for from_mongo_args in [ - &["curate-posts", "--from-mongo"][..], - &[ - "curate-posts", - "--from-mongo", - "--provider-mapping", - "m.tsv", - "--out", - "o", - "--timestamp-unit", - "seconds", - ][..], - &["curate-posts", "--from-mongo=true"][..], - ] { - let err = parse_args(&to_args(from_mongo_args)).unwrap_err(); - assert_eq!(err, "unknown flag '--from-mongo' for curate-posts"); - } + // Valid --from-mongo and flag-mixing rejections for curate-posts + let parsed_mongo = parse_args(&to_args(&[ + "curate-posts", + "--from-mongo", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .expect("valid curate-posts --from-mongo"); + assert!(matches!(parsed_mongo, CliAction::CuratePostsMongo(_))); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--from-mongo", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + ])) + .unwrap_err(); + assert_eq!(err, "cannot combine '--from-mongo' with '--ceo-posts'"); + + let err = parse_args(&to_args(&[ + "curate-posts", + "--ceo-posts", + "p.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--timestamp-unit", + "seconds", + "--mongo-uri", + "mongodb://u:secret_pw@localhost:27017/stock", + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err.contains("secret_pw")); // Positional argument rejected let err = parse_args(&to_args(&[ @@ -5263,6 +5842,7 @@ mod tests { ])), Ok(CliAction::CurateFundamentals(CurateFundamentalsArgs { qm_financials: PathBuf::from("fin.bson"), + qm_financials_old: None, qm_filings: PathBuf::from("fil.bson"), provider_mapping: PathBuf::from("map.tsv"), listing_venues: PathBuf::from("venues.tsv"), @@ -5357,6 +5937,7 @@ mod tests { ])), Ok(CliAction::CurateFundamentals(CurateFundamentalsArgs { qm_financials: PathBuf::from("fin2.bson"), + qm_financials_old: None, qm_filings: PathBuf::from("fil2.bson"), provider_mapping: PathBuf::from("map2.tsv"), listing_venues: PathBuf::from("venues2.tsv"), @@ -5633,33 +6214,120 @@ mod tests { let err = parse_args(&to_args(&dup_tok)).unwrap_err(); assert!(err.contains("duplicate flag '--quarterly-tokens'"), "{err}"); - // Unknown flags including --from-mongo and --mongo-uri (rejected before consuming a value) - for (args, expected_flag) in [ - (&["curate-fundamentals", "--bogus", "1"][..], "--bogus"), - (&["curate-fundamentals", "--from-mongo"][..], "--from-mongo"), - ( - &["curate-fundamentals", "--from-mongo", "--out", "o"][..], - "--from-mongo", - ), - ( - &["curate-fundamentals", "--from-mongo=true"][..], - "--from-mongo", - ), - ( - &["curate-fundamentals", "--mongo-uri", "mongodb://host"][..], - "--mongo-uri", - ), - ( - &["curate-fundamentals", "--mongo-uri-env=MONGODB_READ_URI"][..], - "--mongo-uri-env", - ), - ] { - let err = parse_args(&to_args(args)).unwrap_err(); - assert_eq!( - err, - format!("unknown flag '{expected_flag}' for curate-fundamentals") - ); - } + // Unknown flags and MongoDB / --qm-financials-old flag-mixing rules + let err = parse_args(&to_args(&["curate-fundamentals", "--bogus", "1"])).unwrap_err(); + assert_eq!(err, "unknown flag '--bogus' for curate-fundamentals"); + + let err = parse_args(&to_args(&[ + "curate-fundamentals", + "--from-mongo", + "--qm-financials", + "fin.bson", + "--provider-mapping", + "map.tsv", + "--listing-venues", + "venues.tsv", + "--out", + "o", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--fiscal-period", + "quarterly", + ])) + .unwrap_err(); + assert_eq!( + err, + "cannot combine '--from-mongo' with '--qm-financials', '--qm-financials-old', or '--qm-filings'" + ); + + let err = parse_args(&to_args(&[ + "curate-fundamentals", + "--qm-financials", + "fin.bson", + "--qm-filings", + "fil.bson", + "--provider-mapping", + "map.tsv", + "--listing-venues", + "venues.tsv", + "--out", + "o", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--fiscal-period", + "quarterly", + "--with-qm-financials-old", + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + + let parsed_with_old = parse_args(&to_args(&[ + "curate-fundamentals", + "--qm-financials", + "fin.bson", + "--qm-financials-old", + "fin-old.bson", + "--qm-filings", + "fil.bson", + "--provider-mapping", + "map.tsv", + "--listing-venues", + "venues.tsv", + "--out", + "o", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--fiscal-period", + "quarterly", + ])) + .expect("file mode with --qm-financials-old"); + assert!(matches!( + parsed_with_old, + CliAction::CurateFundamentals(CurateFundamentalsArgs { + qm_financials_old: Some(ref p), + .. + }) if p == Path::new("fin-old.bson") + )); + + let parsed_mongo = parse_args(&to_args(&[ + "curate-fundamentals", + "--from-mongo", + "--with-qm-financials-old", + "--provider-mapping", + "map.tsv", + "--listing-venues", + "venues.tsv", + "--out", + "o", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--fiscal-period", + "quarterly", + ])) + .expect("mongo mode with --with-qm-financials-old"); + assert!(matches!( + parsed_mongo, + CliAction::CurateFundamentalsMongo(CurateFundamentalsMongoArgs { + with_qm_financials_old: true, + .. + }) + )); // Positional argument rejected let err = parse_args(&to_args(&["curate-fundamentals", "extra"])).unwrap_err(); @@ -5972,4 +6640,109 @@ mod tests { .expect("space dir with equals and IPv6 equals addr"); assert_eq!(parsed_space, expected); } + + #[test] + fn parse_curate_macro_and_qm_bars_1m_file_and_mongo_modes() { + let macro_file = parse_args(&to_args(&[ + "curate-macro", + "--te-data", + "te.bson", + "--series-map", + "map.tsv", + "--out", + "out_macro", + ])) + .expect("curate-macro file mode"); + assert_eq!( + macro_file, + CliAction::CurateMacro(CurateMacroArgs { + te_data: PathBuf::from("te.bson"), + series_map: PathBuf::from("map.tsv"), + out_dir: PathBuf::from("out_macro"), + }) + ); + + let macro_mongo = parse_args(&to_args(&[ + "curate-macro", + "--from-mongo", + "--series-map", + "map.tsv", + "--out", + "out_macro", + ])) + .expect("curate-macro --from-mongo"); + assert!(matches!(macro_mongo, CliAction::CurateMacroMongo(_))); + + let err = parse_args(&to_args(&[ + "curate-macro", + "--from-mongo", + "--te-data", + "te.bson", + "--series-map", + "map.tsv", + "--out", + "out_macro", + ])) + .unwrap_err(); + assert_eq!(err, "cannot combine '--from-mongo' with '--te-data'"); + + let qm_file = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--qm-intraday", + "qm.bson", + "--provider-mapping", + "pm.tsv", + "--out", + "out_qm", + "--shards", + "4", + "--known-at-micros", + "1735689600000000", + ])) + .expect("curate-qm-bars-1m file mode"); + assert!(matches!( + qm_file, + CliAction::CurateQmBars1m(CurateQmBars1mArgs { + shard_count: 4, + known_at_micros: 1_735_689_600_000_000, + .. + }) + )); + + let qm_mongo = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--from-mongo", + "--date-gte", + "2024-01-01", + "--date-lt", + "2024-01-02", + "--provider-mapping", + "pm.tsv", + "--out", + "out_qm", + "--shards", + "4", + "--known-at-micros", + "1735689600000000", + ])) + .expect("curate-qm-bars-1m --from-mongo"); + assert!(matches!(qm_mongo, CliAction::CurateQmBars1mMongo(_))); + + let err = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--from-mongo", + "--qm-intraday", + "qm.bson", + "--provider-mapping", + "pm.tsv", + "--out", + "out_qm", + "--shards", + "4", + "--known-at-micros", + "1735689600000000", + ])) + .unwrap_err(); + assert_eq!(err, "cannot combine '--from-mongo' with '--qm-intraday'"); + } } diff --git a/tools/curate-etl/src/curate_fundamentals.rs b/tools/curate-etl/src/curate_fundamentals.rs index 02092a68..3fffc104 100644 --- a/tools/curate-etl/src/curate_fundamentals.rs +++ b/tools/curate-etl/src/curate_fundamentals.rs @@ -32,8 +32,8 @@ use std::path::Path; use crate::events::{parse_filing_timefiled, QmFiling}; use crate::fundamentals::{ - build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FundamentalsError, - FundamentalsStats, StatutoryLagVenue, + build_fundamentals_rows_with_legacy, build_fundamentals_snapshots, FinancialObservation, + FundamentalsError, FundamentalsStats, StatutoryLagVenue, }; use crate::parquet_fundamentals::{ write_fundamentals_pit_dataset, FundamentalsPitParquetRow, FundamentalsPitWriteOptions, @@ -172,6 +172,39 @@ where K: AsRef, IO: IntoIterator>, IF: IntoIterator>, +{ + curate_fundamentals_with_legacy( + observations, + std::iter::empty::>(), + filings, + mapping_source, + mapping, + venues, + k, + ) +} + +/// Pure `fundamentals_pit` curation stage merging primary (`qmFinancials`) and legacy +/// (`qmFinancials-old`) observations via [`build_fundamentals_rows_with_legacy`]. +/// +/// Rejects blank `mapping_source` with [`CurateFundamentalsError::EmptyMappingSource`] and `k == 0` +/// with [`CurateFundamentalsError::Fundamentals`] (`FundamentalsError::InvalidPeriodLimit`) before +/// consuming input iterators. +#[allow(clippy::too_many_arguments)] +pub fn curate_fundamentals_with_legacy( + primary_observations: IO, + legacy_observations: ILO, + filings: IF, + mapping_source: &str, + mapping: &ProviderMappingTable, + venues: &BTreeMap, + k: usize, +) -> Result +where + K: AsRef, + IO: IntoIterator>, + ILO: IntoIterator>, + IF: IntoIterator>, { if mapping_source.trim().is_empty() { return Err(CurateFundamentalsError::EmptyMappingSource); @@ -180,22 +213,42 @@ where return Err(FundamentalsError::InvalidPeriodLimit { k }.into()); } - let obs_iter = observations.into_iter(); + let primary_iter = primary_observations.into_iter(); + let legacy_iter = legacy_observations.into_iter(); let filings_iter = filings.into_iter(); let mut stats = CurateFundamentalsStats::default(); - let mut mapped_observations: Vec> = - Vec::with_capacity(obs_iter.size_hint().0); + let mut mapped_primary: Vec> = + Vec::with_capacity(primary_iter.size_hint().0); + let mut mapped_legacy: Vec> = + Vec::with_capacity(legacy_iter.size_hint().0); let mut mapped_filings: Vec> = Vec::with_capacity(filings_iter.size_hint().0); - for obs in obs_iter { + for obs in primary_iter { stats.observations_in += 1; let Some(listing_id) = mapping.resolve(mapping_source, obs.key.as_ref(), obs.period_end) else { stats.observations_dropped_unmapped += 1; continue; }; - mapped_observations.push(FinancialObservation { + mapped_primary.push(FinancialObservation { + key: listing_id, + period_end: obs.period_end, + fiscal_period: obs.fiscal_period, + currency: obs.currency, + report_date: obs.report_date, + fields: obs.fields, + }); + } + + for obs in legacy_iter { + stats.observations_in += 1; + let Some(listing_id) = mapping.resolve(mapping_source, obs.key.as_ref(), obs.period_end) + else { + stats.observations_dropped_unmapped += 1; + continue; + }; + mapped_legacy.push(FinancialObservation { key: listing_id, period_end: obs.period_end, fiscal_period: obs.fiscal_period, @@ -226,7 +279,8 @@ where }); } - let built = build_fundamentals_rows(mapped_observations, mapped_filings, venues); + let built = + build_fundamentals_rows_with_legacy(mapped_primary, mapped_legacy, mapped_filings, venues); stats.build = built.stats; let snapshots = build_fundamentals_snapshots(&built.rows, k)?; @@ -269,7 +323,50 @@ where IO: IntoIterator>, IF: IntoIterator>, { - let curated = curate_fundamentals(observations, filings, mapping_source, mapping, venues, k)?; + curate_and_write_fundamentals_with_legacy( + out_dir, + observations, + std::iter::empty::>(), + filings, + mapping_source, + mapping, + venues, + k, + options, + ) +} + +/// Thin end-to-end wrapper running [`curate_fundamentals_with_legacy`] and publishing the +/// resulting contract rows via [`write_fundamentals_pit_dataset`] to +/// `/fundamentals_pit/year=YYYY/part.parquet`. +#[allow(clippy::too_many_arguments)] +pub fn curate_and_write_fundamentals_with_legacy( + out_dir: P, + primary_observations: IO, + legacy_observations: ILO, + filings: IF, + mapping_source: &str, + mapping: &ProviderMappingTable, + venues: &BTreeMap, + k: usize, + options: FundamentalsPitWriteOptions, +) -> Result +where + P: AsRef, + K: AsRef, + IO: IntoIterator>, + ILO: IntoIterator>, + IF: IntoIterator>, +{ + let curated = curate_fundamentals_with_legacy( + primary_observations, + legacy_observations, + filings, + mapping_source, + mapping, + venues, + k, + )?; let write_stats = write_fundamentals_pit_dataset(out_dir, &curated.rows, options)?; Ok(CurateFundamentalsWriteReport { curate_stats: curated.stats, diff --git a/tools/curate-etl/src/fundamentals.rs b/tools/curate-etl/src/fundamentals.rs index 7ac7cae6..3523d862 100644 --- a/tools/curate-etl/src/fundamentals.rs +++ b/tools/curate-etl/src/fundamentals.rs @@ -408,6 +408,7 @@ struct EligibleObservation { report_date: Option, venue: StatutoryLagVenue, fields: FundamentalsFields, + is_legacy: bool, } #[derive(Debug, Clone, Copy)] @@ -428,6 +429,7 @@ struct ParsedPeriodicFiling { struct CandidateRow { row: FundamentalsRow, report_date: Option, + is_legacy: bool, } /// Builds sorted, unique bitemporal fundamentals rows from financial observations, periodic @@ -444,12 +446,58 @@ where IO: IntoIterator>, IF: IntoIterator>, { - let obs_iter = observations.into_iter(); + build_fundamentals_rows_with_legacy( + observations, + std::iter::empty::>(), + filings, + venues, + ) +} + +/// Builds sorted, unique bitemporal fundamentals rows by merging primary (`qmFinancials`) and +/// legacy (`qmFinancials-old`) financial observations alongside periodic filings and venue +/// statutory-lag classes. +/// +/// Merge precedence rules: +/// - Both primary and legacy observations feed `stats.observations_in` and filing-link earliest +/// period bounds so historical `qmFilings` can anchor `qmFinancials-old` periods. +/// - Distinct `known_at_utc_micros` vintages across both sources are preserved as separate +/// bitemporal versions (historical snapshots and restatements). +/// - Within a `(key, period_end, fiscal_period)` stream, an undated (`report_date: None`) legacy +/// `statutory_lag_estimate` candidate arriving after an already-accepted earlier row for the +/// same `fiscal_period` is dropped as a stale estimate (`observations_dropped_stale_estimate`). +/// - Within the same `(key, period_end, known_at_utc_micros)` group, primary (`qmFinancials`) +/// survivors supersede legacy (`qmFinancials-old`) survivors for the same `fiscal_period` +/// (`duplicate_collapsed`), while intra-collection conflicts remain dropped via +/// `duplicate_conflict_dropped`. +pub fn build_fundamentals_rows_with_legacy( + primary_observations: IO, + legacy_observations: ILO, + filings: IF, + venues: &BTreeMap, +) -> FundamentalsBuild +where + K: Ord + Clone, + IO: IntoIterator>, + ILO: IntoIterator>, + IF: IntoIterator>, +{ + let primary_iter = primary_observations.into_iter(); + let legacy_iter = legacy_observations.into_iter(); let mut stats = FundamentalsStats::default(); - let mut eligible_obs: Vec> = Vec::with_capacity(obs_iter.size_hint().0); + let mut eligible_obs: Vec> = Vec::with_capacity( + primary_iter + .size_hint() + .0 + .saturating_add(legacy_iter.size_hint().0), + ); let mut earliest_period_by_key_kind: BTreeMap<(K, FiscalPeriod), i32> = BTreeMap::new(); - for obs in obs_iter { + let tagged_obs = primary_iter + .map(|obs| (obs, false)) + .chain(legacy_iter.map(|obs| (obs, true))); + + for (obs, is_legacy) in tagged_obs { stats.observations_in += 1; let Some(&venue) = venues.get(&obs.key) else { @@ -491,6 +539,7 @@ where report_date: obs.report_date, venue, fields: obs.fields.normalize_zeros(), + is_legacy, }); } @@ -625,6 +674,7 @@ where fields: obs.fields, }, report_date: obs.report_date, + is_legacy: obs.is_legacy, }); } @@ -650,11 +700,13 @@ where pe_end += 1; } - // Track the newest accepted `report_date` seen at an earlier `known_at_utc_micros` for - // each `FiscalPeriod` so only accepted newer versions can suppress a stale statutory-lag - // estimate. + // Track the newest accepted `report_date` (and whether any row was already accepted) at + // an earlier `known_at_utc_micros` for each `FiscalPeriod` so only accepted earlier + // versions can suppress a stale statutory-lag estimate. let mut max_accepted_rd_q: Option = None; let mut max_accepted_rd_fy: Option = None; + let mut has_accepted_q = false; + let mut has_accepted_fy = false; let mut g_start = pe_start; while g_start < pe_end { @@ -664,21 +716,26 @@ where g_end += 1; } - // Filter out stale dated statutory-lag candidates before duplicate/conflict checks - // so a superseded estimate cannot cause an eligible estimate at the same fallback + // Filter out stale statutory-lag candidates before duplicate/conflict checks so a + // superseded estimate cannot cause an eligible estimate at the same fallback // timestamp to be rejected as conflicting. survivors.clear(); for idx in g_start..g_end { let cand = &candidates[idx]; - let prior_max_rd = match cand.row.fiscal_period { - FiscalPeriod::Quarterly => max_accepted_rd_q, - FiscalPeriod::Annual => max_accepted_rd_fy, + let (prior_max_rd, prior_has_accepted) = match cand.row.fiscal_period { + FiscalPeriod::Quarterly => (max_accepted_rd_q, has_accepted_q), + FiscalPeriod::Annual => (max_accepted_rd_fy, has_accepted_fy), }; - let is_stale_estimate = cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG - && cand - .report_date - .is_some_and(|rd_a| prior_max_rd.is_some_and(|rd_b| rd_b > rd_a)); - if is_stale_estimate { + let is_stale_dated_estimate = + cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG + && cand + .report_date + .is_some_and(|rd_a| prior_max_rd.is_some_and(|rd_b| rd_b > rd_a)); + let is_stale_undated_legacy_estimate = cand.is_legacy + && cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG + && cand.report_date.is_none() + && prior_has_accepted; + if is_stale_dated_estimate || is_stale_undated_legacy_estimate { stats.observations_dropped_stale_estimate += 1; } else { survivors.push(idx); @@ -690,6 +747,32 @@ where continue; } + // Within the same `(key, period_end, known_at_utc_micros)` group, primary + // (`qmFinancials`) survivors supersede legacy (`qmFinancials-old`) survivors for the + // same `FiscalPeriod` rather than triggering a cross-collection conflict drop. + let has_primary_q = survivors.iter().any(|&idx| { + !candidates[idx].is_legacy + && candidates[idx].row.fiscal_period == FiscalPeriod::Quarterly + }); + let has_primary_fy = survivors.iter().any(|&idx| { + !candidates[idx].is_legacy + && candidates[idx].row.fiscal_period == FiscalPeriod::Annual + }); + if has_primary_q || has_primary_fy { + let before = survivors.len(); + survivors.retain(|&idx| { + let cand = &candidates[idx]; + if !cand.is_legacy { + return true; + } + match cand.row.fiscal_period { + FiscalPeriod::Quarterly => !has_primary_q, + FiscalPeriod::Annual => !has_primary_fy, + } + }); + stats.duplicate_collapsed += before - survivors.len(); + } + let first = &candidates[survivors[0]].row; let all_identical = survivors[1..].iter().all(|&idx| { let other = &candidates[idx].row; @@ -711,12 +794,19 @@ where group_max_rd = Some(group_max_rd.map_or(rd, |m| m.max(rd))); } } - if let Some(rd) = group_max_rd { - let slot = match first.fiscal_period { - FiscalPeriod::Quarterly => &mut max_accepted_rd_q, - FiscalPeriod::Annual => &mut max_accepted_rd_fy, - }; - *slot = Some(slot.map_or(rd, |m| m.max(rd))); + match first.fiscal_period { + FiscalPeriod::Quarterly => { + has_accepted_q = true; + if let Some(rd) = group_max_rd { + max_accepted_rd_q = Some(max_accepted_rd_q.map_or(rd, |m| m.max(rd))); + } + } + FiscalPeriod::Annual => { + has_accepted_fy = true; + if let Some(rd) = group_max_rd { + max_accepted_rd_fy = Some(max_accepted_rd_fy.map_or(rd, |m| m.max(rd))); + } + } } stats.duplicate_collapsed += survivors.len() - 1; diff --git a/tools/curate-etl/src/fundamentals_tests.rs b/tools/curate-etl/src/fundamentals_tests.rs index a3919caf..8e6e71d9 100644 --- a/tools/curate-etl/src/fundamentals_tests.rs +++ b/tools/curate-etl/src/fundamentals_tests.rs @@ -1067,3 +1067,200 @@ fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() { assert!(fy_snap.has_estimated_lag); assert_eq!(fy_snap.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); } + +#[test] +fn legacy_merge_primary_supersedes_legacy_at_same_known_at_while_intra_primary_conflicts_still_drop() +{ + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q1_end = day(2024, 3, 31); + let filings = vec![filing("ACME", "2024-05-02T16:30:00 EDT", "10-Q")]; + + // Primary and legacy collide at identical known_at with differing revenue: primary wins. + let primary = vec![obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields_rev(120.0), + )]; + let legacy = vec![obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields_rev(100.0), + )]; + + let built = build_fundamentals_rows_with_legacy(primary, legacy, filings.clone(), &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.observations_in, 2); + assert_eq!(built.stats.rows_out, 1); + assert_eq!(built.stats.duplicate_collapsed, 1); + assert_eq!(built.stats.duplicate_conflict_dropped, 0); + assert_eq!(built.rows[0].fields.revenue, Some(120.0)); + + // Two conflicting primary observations + one legacy observation: legacy collapses, primary pair drops. + let conflicting_primary = vec![ + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields_rev(120.0), + ), + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields_rev(125.0), + ), + ]; + let legacy_dup = vec![obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 2)), + fields_rev(100.0), + )]; + let built_conflict = + build_fundamentals_rows_with_legacy(conflicting_primary, legacy_dup, filings, &venues); + assert_reconciliation(&built_conflict); + assert_eq!(built_conflict.stats.observations_in, 3); + assert_eq!(built_conflict.stats.rows_out, 0); + assert_eq!(built_conflict.stats.duplicate_collapsed, 1); + assert_eq!(built_conflict.stats.duplicate_conflict_dropped, 2); +} + +#[test] +fn legacy_merge_undated_legacy_statutory_lag_does_not_overwrite_earlier_filing_timestamp() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q1_end = day(2024, 3, 31); + // Dated 10-Q/A on May 10 anchors primary observation; undated legacy observation only links + // non-amended filings, so it falls back to statutory_lag_estimate on May 15 (45d after Q1). + let filings = vec![filing("ACME", "2024-05-10T16:30:00 EDT", "10-Q/A")]; + + let primary = vec![obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 10)), + fields_rev(210.0), + )]; + let legacy = vec![obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + None, + fields_rev(190.0), + )]; + + let built = build_fundamentals_rows_with_legacy(primary, legacy, filings, &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.observations_in, 2); + assert_eq!(built.stats.rows_out, 1); + assert_eq!(built.stats.rows_linked_to_filing, 1); + assert_eq!(built.stats.rows_statutory_lag_estimate, 0); + assert_eq!(built.stats.observations_dropped_stale_estimate, 1); + assert_eq!(built.rows[0].fields.revenue, Some(210.0)); + assert_eq!( + built.rows[0].known_at_source, + KNOWN_AT_SOURCE_FILING_TIMESTAMP + ); +} + +#[test] +fn legacy_merge_restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q3 = day(2023, 9, 30); + let q4 = day(2023, 12, 31); + let q1 = day(2024, 3, 31); + let q2 = day(2024, 6, 30); + + let filings = vec![ + filing("ACME", "2023-11-05T16:30:00 EST", "10-Q"), + filing("ACME", "2024-02-20T16:30:00 EST", "10-Q"), + filing("ACME", "2024-05-05T16:30:00 EDT", "10-Q"), + filing("ACME", "2024-08-05T16:30:00 EDT", "10-Q"), + filing("ACME", "2024-09-10T16:30:00 EDT", "10-Q/A"), + ]; + + // Historical quarters (Q3, Q4, original Q1) live in qmFinancials-old; Q2 + restated Q1 live + // in primary qmFinancials. + let legacy = vec![ + obs( + "ACME", + q3, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 5)), + fields_rev(100.0), + ), + obs( + "ACME", + q4, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 20)), + fields_rev(110.0), + ), + obs( + "ACME", + q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 5)), + fields_rev(120.0), + ), + ]; + let primary = vec![ + obs( + "ACME", + q2, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 8, 5)), + fields_rev(130.0), + ), + obs( + "ACME", + q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 9, 10)), + fields_rev(125.0), + ), + ]; + + let built = build_fundamentals_rows_with_legacy(primary, legacy, filings, &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.observations_in, 5); + assert_eq!(built.stats.rows_out, 5); + assert_eq!(built.stats.rows_linked_to_filing, 5); + assert_eq!(built.stats.rows_statutory_lag_estimate, 0); + + let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); + let ts_q2 = utc_micros(2024, 8, 5, 20, 30, 0); + let ts_q1_restated = utc_micros(2024, 9, 10, 20, 30, 0); + + let at_q2 = as_of(&snaps, "ACME", ts_q2).expect("snapshot after Q2 filing"); + assert_eq!(at_q2.periods[0].period_end, q2); + assert_eq!(at_q2.periods[0].fields.revenue, Some(130.0)); + assert_eq!(at_q2.periods[1].period_end, q1); + assert_eq!(at_q2.periods[1].fields.revenue, Some(120.0)); + assert_eq!(at_q2.ttm.as_ref().unwrap().flows.revenue, Some(460.0)); + + let at_restated = as_of(&snaps, "ACME", ts_q1_restated).expect("snapshot after Q1 restatement"); + assert_eq!(at_restated.periods[0].period_end, q2); + assert_eq!(at_restated.periods[0].fields.revenue, Some(130.0)); + assert_eq!(at_restated.periods[1].period_end, q1); + assert_eq!(at_restated.periods[1].fields.revenue, Some(125.0)); + assert_eq!(at_restated.ttm.as_ref().unwrap().flows.revenue, Some(465.0)); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index a16d00be..b2da757c 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -137,11 +137,11 @@ pub use events::{ KNOWN_AT_SOURCE_STATUTORY_LAG, }; pub use fundamentals::{ - as_of as fundamentals_as_of, build_fundamentals_rows, build_fundamentals_snapshots, - FinancialObservation, FiscalPeriod, FundamentalsBuild, FundamentalsError, FundamentalsFields, - FundamentalsPeriodSlot, FundamentalsRow, FundamentalsSnapshot, FundamentalsStats, - FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, ANNUAL_FILING_LINK_WINDOW_DAYS, - FUNDAMENTALS_FALLBACK_HOUR_ET, FUNDAMENTALS_FALLBACK_MINUTE_ET, + as_of as fundamentals_as_of, build_fundamentals_rows, build_fundamentals_rows_with_legacy, + build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, FundamentalsBuild, + FundamentalsError, FundamentalsFields, FundamentalsPeriodSlot, FundamentalsRow, + FundamentalsSnapshot, FundamentalsStats, FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, + ANNUAL_FILING_LINK_WINDOW_DAYS, FUNDAMENTALS_FALLBACK_HOUR_ET, FUNDAMENTALS_FALLBACK_MINUTE_ET, QUARTERLY_FILING_LINK_WINDOW_DAYS, STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, STATUTORY_LAG_US_TSX_ANNUAL_DAYS, STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, TTM_CONSECUTIVE_QUARTER_MAX_DAYS, @@ -272,9 +272,9 @@ pub use curate_posts::{ pub mod curate_fundamentals; pub use curate_fundamentals::{ - curate_and_write_fundamentals, curate_fundamentals, CurateFundamentalsError, - CurateFundamentalsOutput, CurateFundamentalsStats, CurateFundamentalsWriteError, - CurateFundamentalsWriteReport, + curate_and_write_fundamentals, curate_and_write_fundamentals_with_legacy, curate_fundamentals, + curate_fundamentals_with_legacy, CurateFundamentalsError, CurateFundamentalsOutput, + CurateFundamentalsStats, CurateFundamentalsWriteError, CurateFundamentalsWriteReport, }; pub mod curate_macro; @@ -336,20 +336,21 @@ pub use run_curate_bars::{ pub mod run_curate_bars_1m; pub use run_curate_bars_1m::{ - format_curate_bars_1m_report, run_curate_bars_1m, run_curate_bars_1m_with_readers, - CurateBars1mArgs, CurateBars1mRunReport, RunCurateBars1mError, - DEFAULT_BARS_1M_MAPPING_SOURCE, + format_curate_bars_1m_report, run_curate_bars_1m, run_curate_bars_1m_from_readers_to_dir, + run_curate_bars_1m_with_readers, CurateBars1mArgs, CurateBars1mRunReport, + RunCurateBars1mError, DEFAULT_BARS_1M_MAPPING_SOURCE, }; pub mod run_curate_fx_1m; pub use run_curate_fx_1m::{ - format_curate_fx_1m_report, run_curate_fx_1m, run_curate_fx_1m_with_readers, CurateFx1mArgs, - CurateFx1mRunReport, RunCurateFx1mError, + format_curate_fx_1m_report, run_curate_fx_1m, run_curate_fx_1m_from_reader_to_dir, + run_curate_fx_1m_with_readers, CurateFx1mArgs, CurateFx1mRunReport, RunCurateFx1mError, }; pub mod run_curate_qm_bars_1m; pub use run_curate_qm_bars_1m::{ - format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, run_curate_qm_bars_1m_with_readers, + format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, + run_curate_qm_bars_1m_from_reader_to_dir, run_curate_qm_bars_1m_with_readers, CurateQmBars1mArgs, CurateQmBars1mRunReport, RunCurateQmBars1mError, DEFAULT_QM_BARS_1M_MAPPING_SOURCE, }; @@ -384,15 +385,16 @@ pub use run_curate_posts::{ pub mod run_curate_fundamentals; pub use run_curate_fundamentals::{ format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals, - run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, - CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, + run_curate_fundamentals_with_optional_old_readers, run_curate_fundamentals_with_readers, + CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, CurateFundamentalsRunReport, + RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, }; pub mod run_curate_macro; pub use run_curate_macro::{ format_curate_macro_report, load_macro_series_map_tsv, run_curate_macro, - run_curate_macro_with_readers, CurateMacroArgs, CurateMacroRunReport, MacroSeriesMap, - RunCurateMacroError, MACRO_SERIES_MAP_HEADER, + run_curate_macro_from_reader, run_curate_macro_with_readers, CurateMacroArgs, + CurateMacroRunReport, MacroSeriesMap, RunCurateMacroError, MACRO_SERIES_MAP_HEADER, }; pub mod run_curate_shorts; @@ -409,10 +411,14 @@ pub use run_curate_events::{ pub mod run_mongo; pub use run_mongo::{ - run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo, - run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_mongo, - CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs, - CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError, + run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_bars_1m_mongo, + run_curate_corporate_actions_mongo, run_curate_events_mongo, run_curate_fundamentals_mongo, + run_curate_fx_1d_mongo, run_curate_fx_1m_mongo, run_curate_macro_mongo, run_curate_posts_mongo, + run_curate_qm_bars_1m_mongo, run_curate_shorts_mongo, CurateAdjFactorsMongoArgs, + CurateBars1dMongoArgs, CurateBars1mMongoArgs, CurateCorporateActionsMongoArgs, + CurateEventsMongoArgs, CurateFundamentalsMongoArgs, CurateFx1dMongoArgs, CurateFx1mMongoArgs, + CurateMacroMongoArgs, CuratePostsMongoArgs, CurateQmBars1mMongoArgs, CurateShortsMongoArgs, + RunMongoCurateError, }; #[cfg(test)] diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index ab9e6c05..6b63b16a 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -34,11 +34,15 @@ use curate_etl::run_curate_fundamentals::{ }; use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d}; use curate_etl::run_curate_fx_1m::{format_curate_fx_1m_report, run_curate_fx_1m}; +use curate_etl::run_curate_macro::{format_curate_macro_report, run_curate_macro}; use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts}; +use curate_etl::run_curate_qm_bars_1m::{format_curate_qm_bars_1m_report, run_curate_qm_bars_1m}; use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts}; use curate_etl::run_mongo::{ - run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo, - run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_mongo, + run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_bars_1m_mongo, + run_curate_corporate_actions_mongo, run_curate_events_mongo, run_curate_fundamentals_mongo, + run_curate_fx_1d_mongo, run_curate_fx_1m_mongo, run_curate_macro_mongo, run_curate_posts_mongo, + run_curate_qm_bars_1m_mongo, run_curate_shorts_mongo, }; const NAME: &str = env!("CARGO_PKG_NAME"); @@ -214,6 +218,40 @@ fn main() -> ExitCode { ExitCode::FAILURE } }, + Ok(CliAction::CurateBars1mMongo(curate_args)) => { + match run_curate_bars_1m_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_bars_1m_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + } + } + Ok(CliAction::CurateQmBars1m(curate_args)) => match run_curate_qm_bars_1m(&curate_args) { + Ok(report) => { + println!("{}", format_curate_qm_bars_1m_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + }, + Ok(CliAction::CurateQmBars1mMongo(curate_args)) => { + match run_curate_qm_bars_1m_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_qm_bars_1m_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + } + } Ok(CliAction::CurateFx1m(curate_args)) => match run_curate_fx_1m(&curate_args) { Ok(report) => { println!("{}", format_curate_fx_1m_report(&report)); @@ -224,6 +262,18 @@ fn main() -> ExitCode { ExitCode::FAILURE } }, + Ok(CliAction::CurateFx1mMongo(curate_args)) => { + match run_curate_fx_1m_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_fx_1m_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + } + } Ok(CliAction::CuratePosts(curate_args)) => match run_curate_posts(&curate_args) { Ok(report) => { println!("{}", format_curate_posts_report(&report)); @@ -234,6 +284,18 @@ fn main() -> ExitCode { ExitCode::FAILURE } }, + Ok(CliAction::CuratePostsMongo(curate_args)) => { + match run_curate_posts_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_posts_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + } + } Ok(CliAction::CurateFundamentals(curate_args)) => { match run_curate_fundamentals(&curate_args) { Ok(report) => { @@ -246,6 +308,40 @@ fn main() -> ExitCode { } } } + Ok(CliAction::CurateFundamentalsMongo(curate_args)) => { + match run_curate_fundamentals_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_fundamentals_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + } + } + Ok(CliAction::CurateMacro(curate_args)) => match run_curate_macro(&curate_args) { + Ok(report) => { + println!("{}", format_curate_macro_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + }, + Ok(CliAction::CurateMacroMongo(curate_args)) => { + match run_curate_macro_mongo(&curate_args) { + Ok(report) => { + println!("{}", format_curate_macro_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + } + } Ok(CliAction::SendIlp(send_args)) => match run_send_ilp(&send_args) { Ok(report) => { println!("{}", format_ilp_send_report(&report)); diff --git a/tools/curate-etl/src/mongo_stream.rs b/tools/curate-etl/src/mongo_stream.rs index 35564c58..fbfec4b5 100644 --- a/tools/curate-etl/src/mongo_stream.rs +++ b/tools/curate-etl/src/mongo_stream.rs @@ -9,7 +9,7 @@ //! backed by `mongodb::sync`. //! //! # Safety & Sealing Guarantees -//! - Closed [`SourceCollection`] allowlist matching the 8 M1 collections in +//! - Closed [`SourceCollection`] allowlist matching all 14 M1+M2 collections in //! `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. No API //! accepts a free-form collection name string. //! - Sealed read-only driver surface: [`ReadOnlyMongoClient`] requires a @@ -45,7 +45,7 @@ pub const DEFAULT_MONGO_BATCH_SIZE: u32 = 4_096; /// Maximum permitted MongoDB cursor batch size (matches `MAX_RAW_BSON_BATCH_SIZE`). pub const MAX_MONGO_BATCH_SIZE: u32 = 100_000; -/// Closed allowlist of the 8 M1 MongoDB source collections consumed by `curate-etl`. +/// Closed allowlist of the 14 M1+M2 MongoDB source collections consumed by `curate-etl`. /// /// Order and names match `RAW_BSON_EXPORT_COLLECTIONS` in /// `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. @@ -59,11 +59,17 @@ pub enum SourceCollection { CeoShorts, QmFilings, QmEarnings, + QmFinancials, + QmFinancialsOld, + CeoPosts, + TeData, + EodIntraday1M, + QmIntraday, } impl SourceCollection { - /// All 8 allowlisted M1 source collections in canonical order. - pub const ALL: [SourceCollection; 8] = [ + /// All 14 allowlisted M1+M2 source collections in canonical order. + pub const ALL: [SourceCollection; 14] = [ Self::EodPrices, Self::QmSplits, Self::QmDividends, @@ -72,6 +78,12 @@ impl SourceCollection { Self::CeoShorts, Self::QmFilings, Self::QmEarnings, + Self::QmFinancials, + Self::QmFinancialsOld, + Self::CeoPosts, + Self::TeData, + Self::EodIntraday1M, + Self::QmIntraday, ]; /// Exact MongoDB collection name. @@ -85,6 +97,12 @@ impl SourceCollection { Self::CeoShorts => "ceoShorts", Self::QmFilings => "qmFilings", Self::QmEarnings => "qmEarnings", + Self::QmFinancials => "qmFinancials", + Self::QmFinancialsOld => "qmFinancials-old", + Self::CeoPosts => "ceoPosts", + Self::TeData => "teData", + Self::EodIntraday1M => "eodIntraday1M", + Self::QmIntraday => "qmIntraday", } } @@ -99,11 +117,18 @@ impl SourceCollection { Self::CeoShorts => "symbol", Self::QmFilings => "symbol", Self::QmEarnings => "qmSearchCode", + Self::QmFinancials => "qmSearchCode", + Self::QmFinancialsOld => "qmSearchCode", + Self::CeoPosts => "ceoId", + Self::TeData => "teSymbol", + Self::EodIntraday1M => "eodSearchCode", + Self::QmIntraday => "qmSearchCode", } } /// Date/timestamp field used for range filters (`date_range`), or `None` - /// for document-per-symbol collections (`teMarketData`). + /// for document-per-symbol / non-range-filtered collections (`teMarketData`, + /// `qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`). pub const fn date_field(self) -> Option<&'static str> { match self { Self::EodPrices => Some("date"), @@ -114,18 +139,31 @@ impl SourceCollection { Self::CeoShorts => Some("timestamp"), Self::QmFilings => Some("timefiled"), Self::QmEarnings => Some("reportDate"), + Self::QmFinancials => None, + Self::QmFinancialsOld => None, + Self::CeoPosts => None, + Self::TeData => None, + Self::EodIntraday1M => Some("timestamp"), + Self::QmIntraday => Some("timestamp"), } } /// Returns `true` when the collection's [`Self::date_field`] is stored as a - /// BSON `DateTime` rather than a `YYYY-MM-DD` / ISO UTF-8 string. + /// BSON `DateTime` rather than a `YYYY-MM-DD` / ISO UTF-8 string or epoch seconds. /// - /// Verified empirically against live QA MongoDB (`m1-source-field-shapes.md`): - /// `qmEarnings.reportDate` (100% BSON `DateTime`) and `ceoShorts.timestamp` - /// (BSON `DateTime`), while `eodPrices.date`, `qmPrices.date`, `qmSplits.date`, + /// Verified empirically against live QA MongoDB (`m1-source-field-shapes.md` / + /// `design/DATA-CONTRACTS.md` §1): `qmEarnings.reportDate`, `ceoShorts.timestamp`, + /// and `qmIntraday.timestamp` are BSON `DateTime`s, while `eodIntraday1M.timestamp` + /// is UTC epoch seconds and `eodPrices.date`, `qmPrices.date`, `qmSplits.date`, /// `qmDividends.date`, and `qmFilings.timefiled` are UTF-8 strings. pub const fn date_field_is_bson_datetime(self) -> bool { - matches!(self, Self::QmEarnings | Self::CeoShorts) + matches!(self, Self::QmEarnings | Self::CeoShorts | Self::QmIntraday) + } + + /// Returns `true` when the collection's [`Self::date_field`] is stored as + /// UTC Unix epoch seconds (`Int32`/`Int64`), as in `eodIntraday1M.timestamp`. + pub const fn date_field_is_epoch_seconds(self) -> bool { + matches!(self, Self::EodIntraday1M) } } @@ -142,6 +180,8 @@ pub enum FilterDateValue { IsoString(String), /// BSON UTC `DateTime` expressed as milliseconds since the Unix epoch. BsonDateTimeMillis(i64), + /// UTC Unix timestamp expressed as integer seconds (`Bson::Int64`), used by `eodIntraday1M`. + EpochSeconds(i64), } impl FilterDateValue { @@ -149,6 +189,7 @@ impl FilterDateValue { match self { Self::IsoString(s) => Bson::String(s.clone()), Self::BsonDateTimeMillis(ms) => Bson::DateTime(DateTime::from_millis(*ms)), + Self::EpochSeconds(secs) => Bson::Int64(*secs), } } } @@ -259,20 +300,49 @@ impl MongoReadSpec { } Ok(()) } - Some(FilterDateValue::BsonDateTimeMillis(_)) => { - Err(MongoStreamError::InvalidDateRange { - collection, - detail: "qmFilings.timefiled is stored as an Eastern Time string; \ - only Eastern calendar-day boundaries (YYYY-MM-DD) are \ - supported for server-side ranges" - .to_owned(), - }) - } + Some( + FilterDateValue::BsonDateTimeMillis(_) + | FilterDateValue::EpochSeconds(_), + ) => Err(MongoStreamError::InvalidDateRange { + collection, + detail: "qmFilings.timefiled is stored as an Eastern Time string; \ + only Eastern calendar-day boundaries (YYYY-MM-DD) are \ + supported for server-side ranges" + .to_owned(), + }), None => Ok(()), }; validate_et_calendar_day(range.gte.as_ref(), "gte")?; validate_et_calendar_day(range.lt.as_ref(), "lt")?; } + if collection.date_field_is_epoch_seconds() { + for (label, bound) in [("gte", &range.gte), ("lt", &range.lt)] { + if let Some(val) = bound { + if !matches!(val, FilterDateValue::EpochSeconds(_)) { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: format!( + "{collection}.timestamp {label} must use EpochSeconds (UTC Unix seconds)" + ), + }); + } + } + } + } + if collection == SourceCollection::QmIntraday { + for (label, bound) in [("gte", &range.gte), ("lt", &range.lt)] { + if let Some(val) = bound { + if !matches!(val, FilterDateValue::BsonDateTimeMillis(_)) { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: format!( + "{collection}.timestamp {label} must use BsonDateTimeMillis (BSON DateTime)" + ), + }); + } + } + } + } if let (Some(gte), Some(lt)) = (&range.gte, &range.lt) { match (gte, lt) { (FilterDateValue::IsoString(a), FilterDateValue::IsoString(b)) => { @@ -294,6 +364,14 @@ impl MongoReadSpec { }); } } + (FilterDateValue::EpochSeconds(a), FilterDateValue::EpochSeconds(b)) => { + if a >= b { + return Err(MongoStreamError::InvalidDateRange { + collection, + detail: format!("gte ({a}) must be strictly less than lt ({b})"), + }); + } + } _ => { return Err(MongoStreamError::InvalidDateRange { collection, @@ -749,7 +827,7 @@ fn find_next_mongo_scheme(lower_slice: &str) -> Option<(usize, usize)> { } } -fn redact_embedded_mongo_uris(text: &str) -> String { +pub(crate) fn redact_embedded_mongo_uris(text: &str) -> String { let mut result = String::with_capacity(text.len()); let mut cursor = 0usize; let lower = text.to_ascii_lowercase(); @@ -1198,8 +1276,9 @@ impl MongoCliOptions { } /// Builds a [`MongoReadSpec`] using the collection's native BSON date representation: - /// `BsonDateTimeMillis` (UTC midnight) for BSON `DateTime` collections (`qmEarnings`, - /// `ceoShorts`) and `IsoString` for string-dated collections (`eodPrices`, `qmPrices`, + /// `EpochSeconds` (UTC midnight seconds) for `eodIntraday1M`, `BsonDateTimeMillis` + /// (UTC midnight millis) for BSON `DateTime` collections (`qmEarnings`, `ceoShorts`, + /// `qmIntraday`), and `IsoString` for string-dated collections (`eodPrices`, `qmPrices`, /// `qmSplits`, `qmDividends`, `qmFilings`). pub fn to_read_spec_for_collection( &self, @@ -1210,25 +1289,45 @@ impl MongoCliOptions { if !apply_date_range || (self.date_gte.is_none() && self.date_lt.is_none()) { return self.to_read_spec(key_eq, false); } - if !collection.date_field_is_bson_datetime() { - return self.to_read_spec(key_eq, true); + if collection.date_field_is_epoch_seconds() { + let to_secs = |raw: &String| -> FilterDateValue { + match parse_ymd_strict_days(raw) { + Some(days) => FilterDateValue::EpochSeconds(i64::from(days) * 86_400), + None => FilterDateValue::IsoString(raw.clone()), + } + }; + return MongoReadSpec { + key_eq, + date_range: Some(MongoDateRange { + gte: self.date_gte.as_ref().map(to_secs), + lt: self.date_lt.as_ref().map(to_secs), + }), + batch_size: self.batch_size, + limit: self.limit, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + }; } - let to_dt = |raw: &String| -> FilterDateValue { - match parse_ymd_strict_days(raw) { - Some(days) => FilterDateValue::BsonDateTimeMillis(i64::from(days) * MILLIS_PER_DAY), - None => FilterDateValue::IsoString(raw.clone()), - } - }; - MongoReadSpec { - key_eq, - date_range: Some(MongoDateRange { - gte: self.date_gte.as_ref().map(to_dt), - lt: self.date_lt.as_ref().map(to_dt), - }), - batch_size: self.batch_size, - limit: self.limit, - max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + if collection.date_field_is_bson_datetime() { + let to_dt = |raw: &String| -> FilterDateValue { + match parse_ymd_strict_days(raw) { + Some(days) => { + FilterDateValue::BsonDateTimeMillis(i64::from(days) * MILLIS_PER_DAY) + } + None => FilterDateValue::IsoString(raw.clone()), + } + }; + return MongoReadSpec { + key_eq, + date_range: Some(MongoDateRange { + gte: self.date_gte.as_ref().map(to_dt), + lt: self.date_lt.as_ref().map(to_dt), + }), + batch_size: self.batch_size, + limit: self.limit, + max_doc_bytes: DEFAULT_MAX_DOC_BYTES, + }; } + self.to_read_spec(key_eq, true) } } diff --git a/tools/curate-etl/src/mongo_stream_tests.rs b/tools/curate-etl/src/mongo_stream_tests.rs index 6685e8a2..ed4d8423 100644 --- a/tools/curate-etl/src/mongo_stream_tests.rs +++ b/tools/curate-etl/src/mongo_stream_tests.rs @@ -5,11 +5,16 @@ use std::path::PathBuf; use bson::raw::{cstr, RawDocumentBuf}; use bson::{Bson, DateTime}; +use crate::bson_ceo_posts::{CeoPostsFieldNames, CeoPostsTimestampUnit}; use crate::bson_qm_events::QmFilingsFieldNames; +use crate::bson_qm_financials::{QmFinancialsFieldNames, QmFinancialsFiscalPeriod}; use crate::bson_stream::{ - decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_filings_stream, - decode_qm_split_stream, BsonStreamError, BsonStreamOptions, MIN_BSON_DOC_BYTES, + decode_ceo_posts_stream, decode_eod_intraday_stream, decode_eod_price_stream, + decode_qm_dividend_stream, decode_qm_filings_stream, decode_qm_financials_stream, + decode_qm_intraday_stream, decode_qm_split_stream, decode_te_data_stream, BsonStreamError, + BsonStreamOptions, MIN_BSON_DOC_BYTES, }; +use crate::fundamentals::FiscalPeriod; use crate::mongo_safety::{ assert_read_only_mongo_uri, LocalHosts, ReadOnlyPolicy, ValidatedReadOnlyMongoUri, }; @@ -214,16 +219,6 @@ fn source_collection_allowlist_matches_export_raw_bson_ts_exactly() { let rust_names: Vec<&str> = SourceCollection::ALL.iter().map(|c| c.as_str()).collect(); let ts_name_refs: Vec<&str> = ts_names.iter().map(String::as_str).collect(); - let expected_m1 = vec![ - "eodPrices", - "qmSplits", - "qmDividends", - "qmPrices", - "teMarketData", - "ceoShorts", - "qmFilings", - "qmEarnings", - ]; let expected_ts = vec![ "eodPrices", "qmSplits", @@ -241,17 +236,15 @@ fn source_collection_allowlist_matches_export_raw_bson_ts_exactly() { "qmIntraday", ]; - assert_eq!(rust_names, expected_m1); assert_eq!( ts_name_refs, expected_ts, "RAW_BSON_EXPORT_COLLECTIONS must match the 14 M1+M2 collections in exact names and order" ); assert_eq!( - &ts_name_refs[..rust_names.len()], - rust_names.as_slice(), - "SourceCollection::ALL must match the M1 prefix of RAW_BSON_EXPORT_COLLECTIONS in exact names and order" + rust_names, ts_name_refs, + "SourceCollection::ALL must match RAW_BSON_EXPORT_COLLECTIONS in exact names and order" ); - assert_eq!(SourceCollection::ALL.len(), 8); + assert_eq!(SourceCollection::ALL.len(), 14); } // --------------------------------------------------------------------------- @@ -1792,66 +1785,134 @@ fn qm_filings_rejects_invalid_eastern_calendar_day_bounds() { #[test] fn source_collection_exhaustive_key_date_and_display_mappings() { - let expected: [(SourceCollection, &str, &str, Option<&str>); 8] = [ + let expected: [(SourceCollection, &str, &str, Option<&str>, bool, bool); 14] = [ ( SourceCollection::EodPrices, "eodPrices", "eodSearchCode", Some("date"), + false, + false, ), ( SourceCollection::QmSplits, "qmSplits", "qmSearchCode", Some("date"), + false, + false, ), ( SourceCollection::QmDividends, "qmDividends", "qmSearchCode", Some("date"), + false, + false, ), ( SourceCollection::QmPrices, "qmPrices", "qmSearchCode", Some("date"), + false, + false, ), ( SourceCollection::TeMarketData, "teMarketData", "teSymbol", None, + false, + false, ), ( SourceCollection::CeoShorts, "ceoShorts", "symbol", Some("timestamp"), + true, + false, ), ( SourceCollection::QmFilings, "qmFilings", "symbol", Some("timefiled"), + false, + false, ), ( SourceCollection::QmEarnings, "qmEarnings", "qmSearchCode", Some("reportDate"), + true, + false, + ), + ( + SourceCollection::QmFinancials, + "qmFinancials", + "qmSearchCode", + None, + false, + false, + ), + ( + SourceCollection::QmFinancialsOld, + "qmFinancials-old", + "qmSearchCode", + None, + false, + false, + ), + ( + SourceCollection::CeoPosts, + "ceoPosts", + "ceoId", + None, + false, + false, + ), + ( + SourceCollection::TeData, + "teData", + "teSymbol", + None, + false, + false, + ), + ( + SourceCollection::EodIntraday1M, + "eodIntraday1M", + "eodSearchCode", + Some("timestamp"), + false, + true, + ), + ( + SourceCollection::QmIntraday, + "qmIntraday", + "qmSearchCode", + Some("timestamp"), + true, + false, ), ]; assert_eq!(SourceCollection::ALL.len(), expected.len()); - for (actual, (exp_variant, exp_name, exp_key, exp_date)) in - SourceCollection::ALL.into_iter().zip(expected) + for ( + actual, + (exp_variant, exp_name, exp_key, exp_date, exp_is_dt, exp_is_secs), + ) in SourceCollection::ALL.into_iter().zip(expected) { assert_eq!(actual, exp_variant); assert_eq!(actual.as_str(), exp_name); assert_eq!(format!("{actual}"), exp_name); assert_eq!(actual.key_field(), exp_key); assert_eq!(actual.date_field(), exp_date); + assert_eq!(actual.date_field_is_bson_datetime(), exp_is_dt); + assert_eq!(actual.date_field_is_epoch_seconds(), exp_is_secs); } } @@ -1957,3 +2018,397 @@ fn cli_to_read_spec_for_collection_uses_bson_datetime_for_qm_earnings_and_iso_st Some(&Bson::DateTime(DateTime::from_millis(1_739_404_800_000))) ); } + +#[test] +fn m2_collections_date_range_typing_and_validation() { + let opts = super::MongoCliOptions { + date_gte: Some("2024-01-01".to_owned()), + date_lt: Some("2024-01-02".to_owned()), + ..super::MongoCliOptions::default() + }; + + // eodIntraday1M -> Bson::Int64 UTC epoch seconds + let eod_spec = opts.to_read_spec_for_collection( + SourceCollection::EodIntraday1M, + Some("CAD.FOREX".to_owned()), + true, + ); + let eod_doc = build_filter_document(SourceCollection::EodIntraday1M, &eod_spec) + .expect("eodIntraday1M EpochSeconds filter must succeed"); + assert_eq!( + eod_doc.get("eodSearchCode"), + Some(&Bson::String("CAD.FOREX".to_owned())) + ); + let eod_ts = eod_doc + .get_document("timestamp") + .expect("timestamp subdocument"); + assert_eq!(eod_ts.get("$gte"), Some(&Bson::Int64(1_704_067_200))); + assert_eq!(eod_ts.get("$lt"), Some(&Bson::Int64(1_704_153_600))); + + // qmIntraday -> Bson::DateTime UTC epoch millis + let qm_spec = opts.to_read_spec_for_collection(SourceCollection::QmIntraday, None, true); + let qm_doc = build_filter_document(SourceCollection::QmIntraday, &qm_spec) + .expect("qmIntraday BsonDateTimeMillis filter must succeed"); + let qm_ts = qm_doc + .get_document("timestamp") + .expect("timestamp subdocument"); + assert_eq!( + qm_ts.get("$gte"), + Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000))) + ); + assert_eq!( + qm_ts.get("$lt"), + Some(&Bson::DateTime(DateTime::from_millis(1_704_153_600_000))) + ); + + // Collections without date_field reject date_range with DateRangeNotSupported. + for coll in [ + SourceCollection::QmFinancials, + SourceCollection::QmFinancialsOld, + SourceCollection::CeoPosts, + SourceCollection::TeData, + ] { + let spec = opts.to_read_spec_for_collection(coll, None, true); + assert!( + matches!( + build_filter_document(coll, &spec), + Err(MongoStreamError::DateRangeNotSupported { collection }) if collection == coll + ), + "expected DateRangeNotSupported for {coll}" + ); + } + + // Wrong FilterDateValue variants are rejected for EodIntraday1M and QmIntraday. + for bad_val in [ + FilterDateValue::IsoString("2024-01-01".to_owned()), + FilterDateValue::BsonDateTimeMillis(1_704_067_200_000), + ] { + assert!(matches!( + build_filter_document( + SourceCollection::EodIntraday1M, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(bad_val), + lt: None, + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::EodIntraday1M, + .. + }) + )); + } + for bad_val in [ + FilterDateValue::IsoString("2024-01-01".to_owned()), + FilterDateValue::EpochSeconds(1_704_067_200), + ] { + assert!(matches!( + build_filter_document( + SourceCollection::QmIntraday, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(bad_val), + lt: None, + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::QmIntraday, + .. + }) + )); + } + // Unparsable date strings in MongoCliOptions stay IsoString and fail validation. + let bad_opts = super::MongoCliOptions { + date_gte: Some("not-a-date".to_owned()), + ..super::MongoCliOptions::default() + }; + assert!(matches!( + bad_opts + .to_read_spec_for_collection(SourceCollection::EodIntraday1M, None, true) + .validate(SourceCollection::EodIntraday1M), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::EodIntraday1M, + .. + }) + )); + assert!(matches!( + bad_opts + .to_read_spec_for_collection(SourceCollection::QmIntraday, None, true) + .validate(SourceCollection::QmIntraday), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::QmIntraday, + .. + }) + )); + // EpochSeconds gte >= lt fails validation. + assert!(matches!( + build_filter_document( + SourceCollection::EodIntraday1M, + &MongoReadSpec { + date_range: Some(MongoDateRange { + gte: Some(FilterDateValue::EpochSeconds(1_704_067_200)), + lt: Some(FilterDateValue::EpochSeconds(1_704_067_200)), + }), + ..MongoReadSpec::default() + } + ), + Err(MongoStreamError::InvalidDateRange { + collection: SourceCollection::EodIntraday1M, + .. + }) + )); +} + +#[test] +fn parity_m2_decoders_across_default_and_odd_buffers() { + // 1. qmFinancials + let fin_docs = { + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("qmSearchCode"), "AAPL:US"); + d1.append(cstr!("periodEndDate"), "2024-03-31"); + d1.append(cstr!("reportDate"), "2024-05-02"); + d1.append(cstr!("reportPeriod"), "Q1"); + d1.append(cstr!("currency"), "USD"); + d1.append(cstr!("revenue"), 90_000.0); + let mut d2 = RawDocumentBuf::new(); + d2.append(cstr!("qmSearchCode"), "BAD:US"); + d2.append(cstr!("periodEndDate"), "bad-date"); + d2.append(cstr!("reportPeriod"), "Q1"); + d2.append(cstr!("currency"), "USD"); + vec![d1.into_bytes(), d2.into_bytes()] + }; + let fin_concat = concat_docs(&fin_docs); + let fin_fields = QmFinancialsFieldNames::with_verified_defaults( + "currency", + Some("revenue"), + None, + None, + None, + None, + None, + ); + let fin_fp = QmFinancialsFiscalPeriod::Fixed(FiscalPeriod::Quarterly); + let mut exp_fin = Vec::new(); + let exp_fin_stats = decode_qm_financials_stream( + Cursor::new(&fin_concat), + BsonStreamOptions::default(), + &fin_fields, + fin_fp, + |o| exp_fin.push((o.key.to_owned(), o.period_end, o.fields.revenue.map(f64::to_bits))), + ) + .expect("baseline qmFinancials decode"); + assert_eq!(exp_fin.len(), 1); + for step in [usize::MAX, 1, 7, 37] { + let slices: Vec<&[u8]> = fin_docs.iter().map(Vec::as_slice).collect(); + let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&slices)); + let mut got = Vec::new(); + let stats = if step == usize::MAX { + decode_qm_financials_stream(&mut reader, BsonStreamOptions::default(), &fin_fields, fin_fp, |o| { + got.push((o.key.to_owned(), o.period_end, o.fields.revenue.map(f64::to_bits))); + }) + .expect("qmFinancials stream decode") + } else { + decode_qm_financials_stream( + CappedRead::new(&mut reader, step), + BsonStreamOptions::default(), + &fin_fields, + fin_fp, + |o| got.push((o.key.to_owned(), o.period_end, o.fields.revenue.map(f64::to_bits))), + ) + .expect("qmFinancials capped decode") + }; + assert_eq!(stats, exp_fin_stats); + assert_eq!(got, exp_fin); + } + + // 2. ceoPosts + let post_docs = { + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("ceoId"), "5001"); + d1.append(cstr!("spielId"), "sp-1"); + d1.append(cstr!("timestamp"), 1_710_000_000_i64); + d1.append(cstr!("edited"), false); + d1.append(cstr!("bot"), "0"); + d1.append(cstr!("userId"), "u1"); + d1.append(cstr!("spiel"), "hello world"); + vec![d1.into_bytes()] + }; + let post_concat = concat_docs(&post_docs); + let post_fields = CeoPostsFieldNames::default(); + let mut exp_posts = Vec::new(); + let exp_post_stats = decode_ceo_posts_stream( + Cursor::new(&post_concat), + BsonStreamOptions::default(), + &post_fields, + CeoPostsTimestampUnit::Seconds, + |p| exp_posts.push((p.key.to_owned(), p.spiel_id, p.timestamp_ms, p.text)), + ) + .expect("baseline ceoPosts decode"); + assert_eq!(exp_posts.len(), 1); + for step in [usize::MAX, 1, 7, 37] { + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(post_docs.clone())); + let mut got = Vec::new(); + let stats = if step == usize::MAX { + decode_ceo_posts_stream(&mut reader, BsonStreamOptions::default(), &post_fields, CeoPostsTimestampUnit::Seconds, |p| { + got.push((p.key.to_owned(), p.spiel_id, p.timestamp_ms, p.text)); + }) + .expect("ceoPosts stream decode") + } else { + decode_ceo_posts_stream( + CappedRead::new(&mut reader, step), + BsonStreamOptions::default(), + &post_fields, + CeoPostsTimestampUnit::Seconds, + |p| got.push((p.key.to_owned(), p.spiel_id, p.timestamp_ms, p.text)), + ) + .expect("ceoPosts capped decode") + }; + assert_eq!(stats, exp_post_stats); + assert_eq!(got, exp_posts); + } + + // 3. teData + let te_docs = { + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), "2024-01-31"); + pt.append(cstr!("v"), 3.1_f64); + let mut arr = bson::raw::RawArrayBuf::new(); + arr.push(pt); + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("teSymbol"), "US_CPI"); + d1.append(cstr!("country"), "United States"); + d1.append(cstr!("category"), "Inflation Rate"); + d1.append(cstr!("data"), arr); + vec![d1.into_bytes()] + }; + let te_concat = concat_docs(&te_docs); + let mut exp_te = Vec::new(); + let exp_te_stats = decode_te_data_stream( + Cursor::new(&te_concat), + BsonStreamOptions::default(), + |pt| exp_te.push((pt.te_symbol.to_owned(), pt.period_date, pt.value.to_bits())), + |_off, _err| {}, + ) + .expect("baseline teData decode"); + assert_eq!(exp_te.len(), 1); + for step in [usize::MAX, 1, 7, 37] { + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(te_docs.clone())); + let mut got = Vec::new(); + let stats = if step == usize::MAX { + decode_te_data_stream( + &mut reader, + BsonStreamOptions::default(), + |pt| got.push((pt.te_symbol.to_owned(), pt.period_date, pt.value.to_bits())), + |_off, _err| {}, + ) + .expect("teData stream decode") + } else { + decode_te_data_stream( + CappedRead::new(&mut reader, step), + BsonStreamOptions::default(), + |pt| got.push((pt.te_symbol.to_owned(), pt.period_date, pt.value.to_bits())), + |_off, _err| {}, + ) + .expect("teData capped decode") + }; + assert_eq!(stats, exp_te_stats); + assert_eq!(got, exp_te); + } + + // 4. eodIntraday1M + let eod_1m_docs = { + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("eodSearchCode"), "NVDA.US"); + d1.append(cstr!("timestamp"), 1_718_026_200_i64); + d1.append(cstr!("open"), 120.0_f64); + d1.append(cstr!("high"), 121.0_f64); + d1.append(cstr!("low"), 119.5_f64); + d1.append(cstr!("close"), 120.5_f64); + d1.append(cstr!("volume"), 5000.0_f64); + vec![d1.into_bytes()] + }; + let eod_1m_concat = concat_docs(&eod_1m_docs); + let mut exp_eod_1m = Vec::new(); + let exp_eod_1m_stats = decode_eod_intraday_stream( + Cursor::new(&eod_1m_concat), + BsonStreamOptions::default(), + |b| exp_eod_1m.push((b.eod_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("baseline eodIntraday1M decode"); + assert_eq!(exp_eod_1m.len(), 1); + for step in [usize::MAX, 1, 7, 37] { + let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(eod_1m_docs.clone())); + let mut got = Vec::new(); + let stats = if step == usize::MAX { + decode_eod_intraday_stream( + &mut reader, + BsonStreamOptions::default(), + |b| got.push((b.eod_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("eodIntraday1M stream decode") + } else { + decode_eod_intraday_stream( + CappedRead::new(&mut reader, step), + BsonStreamOptions::default(), + |b| got.push((b.eod_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("eodIntraday1M capped decode") + }; + assert_eq!(stats, exp_eod_1m_stats); + assert_eq!(got, exp_eod_1m); + } + + // 5. qmIntraday + let qm_1m_docs = { + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("qmSearchCode"), "NVDA:US"); + d1.append(cstr!("timestamp"), DateTime::from_millis(1_718_026_200_000)); + d1.append(cstr!("open"), 120.0_f64); + d1.append(cstr!("high"), 121.0_f64); + d1.append(cstr!("low"), 119.5_f64); + d1.append(cstr!("close"), 120.5_f64); + d1.append(cstr!("sharevolume"), 5000.0_f64); + vec![d1.into_bytes()] + }; + let qm_1m_concat = concat_docs(&qm_1m_docs); + let mut exp_qm_1m = Vec::new(); + let exp_qm_1m_stats = decode_qm_intraday_stream( + Cursor::new(&qm_1m_concat), + BsonStreamOptions::default(), + |b| exp_qm_1m.push((b.qm_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("baseline qmIntraday decode"); + assert_eq!(exp_qm_1m.len(), 1); + for step in [usize::MAX, 1, 7, 37] { + let slices: Vec<&[u8]> = qm_1m_docs.iter().map(Vec::as_slice).collect(); + let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&slices)); + let mut got = Vec::new(); + let stats = if step == usize::MAX { + decode_qm_intraday_stream( + &mut reader, + BsonStreamOptions::default(), + |b| got.push((b.qm_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("qmIntraday stream decode") + } else { + decode_qm_intraday_stream( + CappedRead::new(&mut reader, step), + BsonStreamOptions::default(), + |b| got.push((b.qm_search_code.to_owned(), b.ts, b.close.to_bits())), + |_off, _err| {}, + ) + .expect("qmIntraday capped decode") + }; + assert_eq!(stats, exp_qm_1m_stats); + assert_eq!(got, exp_qm_1m); + } +} diff --git a/tools/curate-etl/src/run_curate_bars_1m.rs b/tools/curate-etl/src/run_curate_bars_1m.rs index 86c6c8e5..87a65a00 100644 --- a/tools/curate-etl/src/run_curate_bars_1m.rs +++ b/tools/curate-etl/src/run_curate_bars_1m.rs @@ -761,6 +761,28 @@ where Ok(report) } +/// Runs the bounded-memory `bars_1m` curation pipeline from arbitrary raw-BSON [`io::Read`] +/// streams (such as read-only MongoDB cursors), running full directory preflight, exclusive `.tmp` +/// staging, atomic `hard_link` publication to `/bars_1m.shard-.ilp`, and rollback +/// cleanup on failure with zero intermediate `.bson` scratch files. +pub fn run_curate_bars_1m_from_readers_to_dir( + args: &CurateBars1mArgs, + intraday: RI, + splits: RS, +) -> Result +where + RI: io::Read, + RS: io::Read, +{ + run_curate_bars_1m_to_dir_with_hooks( + args, + intraday, + splits, + |_shard_idx, file| SyncedBufFile::new(file), + |_shard_idx, _final_path| {}, + ) +} + /// Runs the bounded-memory file-to-file `bars_1m` curation pipeline, publishing exactly /// `args.shard_count` QuestDB ILP v2 files (`/bars_1m.shard-.ilp`). pub fn run_curate_bars_1m( @@ -783,13 +805,7 @@ pub fn run_curate_bars_1m( } })?; - run_curate_bars_1m_to_dir_with_hooks( - args, - intraday_file, - splits_file, - |_shard_idx, file| SyncedBufFile::new(file), - |_shard_idx, _final_path| {}, - ) + run_curate_bars_1m_from_readers_to_dir(args, intraday_file, splits_file) } /// Formats [`CurateBars1mRunReport`] into a deterministic machine-readable `key=value` summary. diff --git a/tools/curate-etl/src/run_curate_fundamentals.rs b/tools/curate-etl/src/run_curate_fundamentals.rs index f62c9e70..fe5fce66 100644 --- a/tools/curate-etl/src/run_curate_fundamentals.rs +++ b/tools/curate-etl/src/run_curate_fundamentals.rs @@ -63,7 +63,8 @@ use crate::bson_stream::{ BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, }; use crate::curate_fundamentals::{ - curate_and_write_fundamentals, CurateFundamentalsStats, CurateFundamentalsWriteError, + curate_and_write_fundamentals_with_legacy, CurateFundamentalsStats, + CurateFundamentalsWriteError, }; use crate::events::QmFiling; use crate::fundamentals::{FinancialObservation, FiscalPeriod, StatutoryLagVenue}; @@ -112,6 +113,7 @@ impl CurateFundamentalsFiscalPeriod { #[derive(Debug, Clone, PartialEq, Eq)] pub struct CurateFundamentalsArgs { pub qm_financials: PathBuf, + pub qm_financials_old: Option, pub qm_filings: PathBuf, pub provider_mapping: PathBuf, pub listing_venues: PathBuf, @@ -165,6 +167,7 @@ impl CurateFundamentalsArgs { ) -> Self { Self { qm_financials, + qm_financials_old: None, qm_filings, provider_mapping, listing_venues, @@ -618,7 +621,7 @@ fn validate_out_dir_and_inputs( let resolved_out = resolve_normalized_path(&args.out_dir); let resolved_fundamentals = resolve_normalized_path(&fundamentals_dir); - let resolved_inputs = [ + let mut resolved_inputs = vec![ ( "qm-financials", &args.qm_financials, @@ -640,6 +643,13 @@ fn validate_out_dir_and_inputs( resolve_normalized_path(&args.listing_venues), ), ]; + if let Some(old_path) = &args.qm_financials_old { + resolved_inputs.push(( + "qm-financials-old", + old_path, + resolve_normalized_path(old_path), + )); + } for (label, input_path, resolved_in) in &resolved_inputs { if *resolved_in == resolved_out @@ -774,12 +784,13 @@ fn filings_bson_error_offset(err: &BsonQmEventsError) -> u64 { } fn map_financials_stream_error( + label: &'static str, path: &Path, err: BsonQmFinancialsStreamError, ) -> RunCurateFundamentalsError { match err { BsonQmFinancialsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream { - label: "qm-financials", + label, path: path.to_path_buf(), source, }, @@ -847,6 +858,7 @@ struct DecodedFundamentalsInputs { mapping: ProviderMappingTable, venues: BTreeMap, observations: Vec>>, + legacy_observations: Vec>>, filings: Vec>>, financials_docs_framed: u64, financials_bytes_read: u64, @@ -858,14 +870,17 @@ struct DecodedFundamentalsInputs { filings_decode: BsonQmFilingsDecodeStats, } -fn decode_inputs_from_openers( +fn decode_inputs_from_openers( args: &CurateFundamentalsArgs, open_financials: FF, + open_financials_old: Option<(&Path, FO)>, open_filings: FL, ) -> Result where RF: io::Read, FF: FnOnce() -> Result, + RO: io::Read, + FO: FnOnce() -> Result, RL: io::Read, FL: FnOnce() -> Result, { @@ -916,10 +931,10 @@ where // Stream and decode qmFinancials, releasing the chunk reader immediately afterward. let ( observations, - financials_docs_framed, - financials_bytes_read, - financials_peak_chunk_bytes, - financials_decode, + mut financials_docs_framed, + mut financials_bytes_read, + mut financials_peak_chunk_bytes, + mut financials_decode, ) = { let financials_stream = open_financials()?; let mut financials_reader = @@ -944,7 +959,7 @@ where }); }) }) - .map_err(|err| map_financials_stream_error(&args.qm_financials, err))?; + .map_err(|err| map_financials_stream_error("qm-financials", &args.qm_financials, err))?; ( observations, @@ -955,6 +970,42 @@ where ) }; + // Optionally stream and decode legacy qmFinancials-old, accumulating framing & decode stats. + let mut legacy_observations: Vec>> = Vec::new(); + if let Some((old_path, open_old)) = open_financials_old { + let old_stream = open_old()?; + let mut old_reader = + RawBsonChunkReader::with_options(old_stream, BsonStreamOptions::default()).map_err( + |source| RunCurateFundamentalsError::BsonStream { + label: "qm-financials-old", + path: old_path.to_path_buf(), + source, + }, + )?; + + let old_decode = args + .fiscal_period + .with_borrowed(|fp| { + decode_qm_financials_chunks(&mut old_reader, &financials_fields, fp, |obs| { + let key = intern_key(&mut key_interner, obs.key); + legacy_observations.push(FinancialObservation { + key, + period_end: obs.period_end, + fiscal_period: obs.fiscal_period, + currency: obs.currency, + report_date: obs.report_date, + fields: obs.fields, + }); + }) + }) + .map_err(|err| map_financials_stream_error("qm-financials-old", old_path, err))?; + + financials_docs_framed += old_reader.docs_framed(); + financials_bytes_read += old_reader.bytes_read(); + financials_peak_chunk_bytes = financials_peak_chunk_bytes.max(old_reader.buffer_capacity()); + financials_decode.merge(&old_decode); + } + // Stream and decode qmFilings, reusing the same key interner and releasing the chunk reader. let (filings, filings_docs_framed, filings_bytes_read, filings_peak_chunk_bytes, filings_decode) = { let filings_stream = open_filings()?; @@ -986,6 +1037,7 @@ where mapping, venues, observations, + legacy_observations, filings, financials_docs_framed, financials_bytes_read, @@ -998,25 +1050,29 @@ where }) } -fn run_curate_fundamentals_from_openers( +fn run_curate_fundamentals_from_openers( args: &CurateFundamentalsArgs, open_financials: FF, + open_financials_old: Option<(&Path, FO)>, open_filings: FL, ) -> Result where RF: io::Read, FF: FnOnce() -> Result, + RO: io::Read, + FO: FnOnce() -> Result, RL: io::Read, FL: FnOnce() -> Result, { let start = Instant::now(); validate_out_dir_and_inputs(args)?; - let decoded = decode_inputs_from_openers(args, open_financials, open_filings)?; + let decoded = decode_inputs_from_openers(args, open_financials, open_financials_old, open_filings)?; - let write_report = curate_and_write_fundamentals( + let write_report = curate_and_write_fundamentals_with_legacy( &args.out_dir, decoded.observations, + decoded.legacy_observations, decoded.filings, &args.mapping_source, &decoded.mapping, @@ -1045,7 +1101,7 @@ where } /// Runs the end-to-end `curate-fundamentals` file-to-Parquet pipeline via -/// [`curate_and_write_fundamentals`]. +/// [`curate_and_write_fundamentals_with_legacy`]. /// /// Any validation, path-alias, I/O, TSV, mapping, BSON framing/corruption, or curation error /// returns before touching `args.out_dir`, leaving any pre-existing @@ -1053,6 +1109,17 @@ where pub fn run_curate_fundamentals( args: &CurateFundamentalsArgs, ) -> Result { + let open_old = args.qm_financials_old.as_deref().map(|old_path| { + let opener = move || { + File::open(old_path).map_err(|source| RunCurateFundamentalsError::OpenInput { + label: "qm-financials-old", + path: old_path.to_path_buf(), + source, + }) + }; + (old_path, opener) + }); + run_curate_fundamentals_from_openers( args, || { @@ -1064,6 +1131,7 @@ pub fn run_curate_fundamentals( } }) }, + open_old, || { File::open(&args.qm_filings).map_err(|source| RunCurateFundamentalsError::OpenInput { label: "qm-filings", @@ -1082,7 +1150,35 @@ pub fn run_curate_fundamentals_with_readers( financials_reader: RF, filings_reader: RL, ) -> Result { - run_curate_fundamentals_from_openers(args, || Ok(financials_reader), || Ok(filings_reader)) + run_curate_fundamentals_with_optional_old_readers( + args, + financials_reader, + None::, + filings_reader, + ) +} + +/// Runs `curate-fundamentals` from arbitrary raw-BSON [`io::Read`] streams with an optional +/// legacy `qmFinancials-old` stream, running full preflight validation and loading +/// `provider_mapping.tsv` / `listing_venues.tsv` from disk. +pub fn run_curate_fundamentals_with_optional_old_readers( + args: &CurateFundamentalsArgs, + financials_reader: RF, + financials_old_reader: Option, + filings_reader: RL, +) -> Result { + let fallback_old_path = Path::new("qmFinancials-old"); + let old_path = args + .qm_financials_old + .as_deref() + .unwrap_or(fallback_old_path); + let open_old = financials_old_reader.map(|r| (old_path, move || Ok(r))); + run_curate_fundamentals_from_openers( + args, + || Ok(financials_reader), + open_old, + || Ok(filings_reader), + ) } /// Formats [`CurateFundamentalsRunReport`] into a deterministic machine-readable `key=value` diff --git a/tools/curate-etl/src/run_curate_fundamentals_tests.rs b/tools/curate-etl/src/run_curate_fundamentals_tests.rs index 37afd1bf..001ff80a 100644 --- a/tools/curate-etl/src/run_curate_fundamentals_tests.rs +++ b/tools/curate-etl/src/run_curate_fundamentals_tests.rs @@ -15,8 +15,9 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use super::{ format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals, - run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, - CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, + run_curate_fundamentals_with_optional_old_readers, run_curate_fundamentals_with_readers, + CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, CurateFundamentalsRunReport, + RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, }; use crate::bson_qm_events::decode_qm_filing_buffer; use crate::bson_qm_financials::decode_qm_financials_buffer; @@ -2757,3 +2758,141 @@ fn listing_venues_missing_file_reports_open_error_with_path() { assert!(matches!(err, RunCurateFundamentalsError::OpenInput { ref path, .. } if path.ends_with("nope.tsv"))); assert!(err.to_string().contains(&path.display().to_string())); } + +#[test] +fn qm_financials_old_merges_with_conservation_and_reader_parity() { + let tmp = TempDirGuard::new("qm-financials-old-merge"); + let fin_path = tmp.path().join("qmFinancials.bson"); + let old_path = tmp.path().join("qmFinancials-old.bson"); + let fil_path = tmp.path().join("qmFilings.bson"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let ven_path = tmp.path().join("listing_venues.tsv"); + let out_file = tmp.path().join("out_file"); + let out_reader = tmp.path().join("out_reader"); + + fs::write(&map_path, "qm\tACME:US\t101\t2020-01-01\t\n").unwrap(); + fs::write(&ven_path, "101\tus_tsx\n").unwrap(); + + let fields = |rev: f64| FundamentalsFields { + revenue: Some(rev), + net_income: Some(rev * 0.1), + operating_cash_flow: Some(rev * 0.15), + total_assets: Some(rev * 5.0), + total_equity: Some(rev * 2.0), + shares_outstanding: Some(1_000.0), + }; + + // Primary has Q2 + restated Q1 + a collision with old Q1 at same filing timestamp. + let mut fin_bytes = Vec::new(); + fin_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2024-06-30", + Some("2024-08-05"), + "Q2", + "USD", + fields(130.0), + )); + fin_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2024-03-31", + Some("2024-09-10"), + "Q1", + "USD", + fields(125.0), + )); + fs::write(&fin_path, &fin_bytes).unwrap(); + + // Legacy has historical Q3, Q4, original Q1 (and an older duplicate Q2 at same known_at that primary supersedes). + let mut old_bytes = Vec::new(); + old_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2023-09-30", + Some("2023-11-05"), + "Q3", + "USD", + fields(100.0), + )); + old_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2023-12-31", + Some("2024-02-20"), + "Q4", + "USD", + fields(110.0), + )); + old_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2024-03-31", + Some("2024-05-05"), + "Q1", + "USD", + fields(120.0), + )); + old_bytes.extend_from_slice(&make_financials_doc( + Some("ACME:US"), + "2024-06-30", + Some("2024-08-05"), + "Q2", + "USD", + fields(99.0), + )); + fs::write(&old_path, &old_bytes).unwrap(); + + let mut fil_bytes = Vec::new(); + for (ts, form) in [ + ("2023-11-05T16:30:00 EST", "10-Q"), + ("2024-02-20T16:30:00 EST", "10-Q"), + ("2024-05-05T16:30:00 EDT", "10-Q"), + ("2024-08-05T16:30:00 EDT", "10-Q"), + ("2024-09-10T16:30:00 EDT", "10-Q/A"), + ] { + fil_bytes.extend_from_slice(&make_filing_doc(Some("ACME:US"), ts, form, None, None)); + } + fs::write(&fil_path, &fil_bytes).unwrap(); + + let mut file_args = default_test_args( + fin_path.clone(), + fil_path.clone(), + map_path.clone(), + ven_path.clone(), + out_file.clone(), + ); + file_args.qm_financials_old = Some(old_path.clone()); + + let file_report = run_curate_fundamentals(&file_args).expect("file-mode merge must succeed"); + assert_eq!(file_report.financials_docs_framed, 6); + assert_eq!(file_report.financials_decode.docs_in, 6); + assert_eq!(file_report.financials_decode.rows_out, 6); + assert_eq!(file_report.curate_stats.observations_in, 6); + assert_eq!(file_report.curate_stats.build.duplicate_collapsed, 1); + assert_eq!(file_report.curate_stats.build.duplicate_conflict_dropped, 0); + assert_eq!(file_report.curate_stats.rows_out, 5); + assert_eq!(file_report.write_stats.rows_written, 5); + + let mut reader_args = file_args.clone(); + reader_args.out_dir = out_reader.clone(); + let reader_report = run_curate_fundamentals_with_optional_old_readers( + &reader_args, + Cursor::new(&fin_bytes), + Some(Cursor::new(&old_bytes)), + Cursor::new(&fil_bytes), + ) + .expect("reader-mode merge must succeed"); + + assert_eq!( + reader_report.financials_docs_framed, + file_report.financials_docs_framed + ); + assert_eq!(reader_report.curate_stats, file_report.curate_stats); + assert_eq!(reader_report.write_stats, file_report.write_stats); + assert_eq!(snapshot_tree(&out_file), snapshot_tree(&out_reader)); + + // Path overlap guard catches qm-financials-old inside out_dir/fundamentals_pit. + let mut bad_args = file_args; + bad_args.qm_financials_old = Some(out_file.join("fundamentals_pit").join("year=2024")); + let err = run_curate_fundamentals(&bad_args).expect_err("overlapping qm-financials-old must fail"); + assert!( + err.to_string().contains("qm-financials-old"), + "expected qm-financials-old in overlap error, got: {err}" + ); +} diff --git a/tools/curate-etl/src/run_curate_fx_1m.rs b/tools/curate-etl/src/run_curate_fx_1m.rs index 7c938c0b..1eb1cece 100644 --- a/tools/curate-etl/src/run_curate_fx_1m.rs +++ b/tools/curate-etl/src/run_curate_fx_1m.rs @@ -476,6 +476,25 @@ where ) } +/// Runs the `fx_1m` curation pipeline from an arbitrary raw-BSON [`io::Read`] stream (such as a +/// read-only MongoDB cursor), running full directory preflight, exclusive `.tmp` staging, atomic +/// `hard_link` publication to `/fx_1m.shard-.ilp`, and rollback cleanup on failure +/// with zero intermediate `.bson` scratch files. +pub fn run_curate_fx_1m_from_reader_to_dir( + args: &CurateFx1mArgs, + intraday: R, +) -> Result +where + R: io::Read, +{ + run_curate_fx_1m_to_dir_with_hooks( + args, + intraday, + |_shard_idx, file| SyncedBufFile::new(file), + |_shard_idx, _final_path| {}, + ) +} + /// Runs the file-to-file `fx_1m` curation pipeline, publishing exactly `args.shard_count` QuestDB /// ILP v2 files (`/fx_1m.shard-.ilp`). pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result { @@ -489,12 +508,7 @@ pub fn run_curate_fx_1m(args: &CurateFx1mArgs) -> Result Self { + pub(crate) fn with_input_paths(self, te_data: &Path, series_map: &Path) -> Self { match self { Self::ReadInput { role, @@ -577,6 +577,25 @@ pub fn run_curate_macro_with_readers( }) } +/// Runs `curate-macro` from an arbitrary raw-BSON `teData` [`io::Read`] stream (such as a +/// read-only MongoDB cursor) and a `series_map_path` TSV on disk, validating `series_map_path` +/// before reading `te_data` and attaching `te_data_path` / `series_map_path` to any error. +pub fn run_curate_macro_from_reader( + te_data_path: &Path, + te_data: RT, + series_map_path: &Path, + out_dir: &Path, +) -> Result { + let series_map_file = + File::open(series_map_path).map_err(|source| RunCurateMacroError::OpenInput { + role: ROLE_SERIES_MAP, + path: series_map_path.to_path_buf(), + source, + })?; + run_curate_macro_with_readers(te_data, series_map_file, out_dir) + .map_err(|err| err.with_input_paths(te_data_path, series_map_path)) +} + /// Runs file-mode `curate-macro` by opening `args.series_map` and `args.te_data` and delegating /// to [`run_curate_macro_with_readers`]. /// diff --git a/tools/curate-etl/src/run_curate_qm_bars_1m.rs b/tools/curate-etl/src/run_curate_qm_bars_1m.rs index 0d6ec861..9aba09af 100644 --- a/tools/curate-etl/src/run_curate_qm_bars_1m.rs +++ b/tools/curate-etl/src/run_curate_qm_bars_1m.rs @@ -544,6 +544,25 @@ where ) } +/// Runs the bounded-memory `qmIntraday` -> `bars_1m` curation pipeline from an arbitrary raw-BSON +/// [`io::Read`] stream (such as a read-only MongoDB cursor), running full directory preflight, +/// exclusive `.tmp` staging, atomic `hard_link` publication to `/bars_1m_qm.shard-.ilp`, +/// and rollback cleanup on failure with zero intermediate `.bson` scratch files. +pub fn run_curate_qm_bars_1m_from_reader_to_dir( + args: &CurateQmBars1mArgs, + intraday: R, +) -> Result +where + R: io::Read, +{ + run_curate_qm_bars_1m_to_dir_with_hooks( + args, + intraday, + |_shard_idx, file| SyncedBufFile::new(file), + |_shard_idx, _final_path| {}, + ) +} + /// Runs the bounded-memory file-to-file `qmIntraday` -> `bars_1m` curation pipeline, publishing /// exactly `args.shard_count` QuestDB ILP v2 files (`/bars_1m_qm.shard-.ilp`). pub fn run_curate_qm_bars_1m( @@ -558,12 +577,7 @@ pub fn run_curate_qm_bars_1m( source, })?; - run_curate_qm_bars_1m_to_dir_with_hooks( - args, - intraday_file, - |_shard_idx, file| SyncedBufFile::new(file), - |_shard_idx, _final_path| {}, - ) + run_curate_qm_bars_1m_from_reader_to_dir(args, intraday_file) } /// Formats [`CurateQmBars1mRunReport`] into a deterministic machine-readable `key=value` summary. diff --git a/tools/curate-etl/src/run_mongo.rs b/tools/curate-etl/src/run_mongo.rs index b36af63e..da83d322 100644 --- a/tools/curate-etl/src/run_mongo.rs +++ b/tools/curate-etl/src/run_mongo.rs @@ -1,18 +1,22 @@ -//! Direct read-only MongoDB streaming runners for all six M1 `curate-*` CLI commands. +//! Direct read-only MongoDB streaming runners for all M1 and M2 `curate-*` CLI commands. //! //! Uses [`ReadOnlyMongoClient`] (constructed strictly from [`crate::ValidatedReadOnlyMongoUri`]) //! to open zero-copy raw-BSON cursors over allowlisted [`SourceCollection`]s and feeds them -//! directly into the shared `run_curate_*_with_readers` pipelines with zero intermediate `.bson` +//! directly into the shared `run_curate_*` reader pipelines with zero intermediate `.bson` //! scratch files. use std::collections::BTreeSet; use std::error::Error; use std::fmt; +use std::io; use std::path::{Path, PathBuf}; +use crate::bson_ceo_posts::{CeoPostsFieldNames, CeoPostsTimestampUnit}; use crate::bson_ceo_shorts::CeoShortsFieldNames; use crate::bson_qm_events::{QmEarningsFieldNames, QmFilingsFieldNames}; +use crate::bson_stream::BsonStreamOptions; use crate::curate_adj::AdjPointInTimeFence; +use crate::ilp::IlpWriterOptions; use crate::mongo_stream::{ MongoCliOptions, MongoReadSpec, MongoStreamError, ReadOnlyMongoClient, SourceCollection, }; @@ -23,6 +27,10 @@ use crate::run_curate_bars::{ load_provider_mapping_tsv, run_curate_bars_1d_with_readers, CurateBars1dRunReport, RunCurateBarsError, }; +use crate::run_curate_bars_1m::{ + run_curate_bars_1m_from_readers_to_dir, CurateBars1mArgs, CurateBars1mRunReport, + RunCurateBars1mError, +}; use crate::run_curate_corporate_actions::{ run_curate_corporate_actions_with_readers, CurateCorporateActionsRunReport, RunCurateCorporateActionsError, @@ -30,9 +38,26 @@ use crate::run_curate_corporate_actions::{ use crate::run_curate_events::{ run_curate_events_with_readers, CurateEventsRunReport, RunCurateEventsError, }; +use crate::run_curate_fundamentals::{ + run_curate_fundamentals_with_optional_old_readers, CurateFundamentalsArgs, + CurateFundamentalsFiscalPeriod, CurateFundamentalsRunReport, RunCurateFundamentalsError, +}; use crate::run_curate_fx::{ run_curate_fx_1d_with_readers, CurateFx1dRunReport, RunCurateFxError, EOD_CAD_FOREX_CODE, }; +use crate::run_curate_fx_1m::{ + run_curate_fx_1m_from_reader_to_dir, CurateFx1mArgs, CurateFx1mRunReport, RunCurateFx1mError, +}; +use crate::run_curate_macro::{ + run_curate_macro_from_reader, CurateMacroRunReport, RunCurateMacroError, +}; +use crate::run_curate_posts::{ + run_curate_posts_with_reader, CuratePostsRunReport, RunCuratePostsError, +}; +use crate::run_curate_qm_bars_1m::{ + run_curate_qm_bars_1m_from_reader_to_dir, CurateQmBars1mArgs, CurateQmBars1mRunReport, + RunCurateQmBars1mError, +}; use crate::run_curate_shorts::{ run_curate_shorts_with_reader, CurateShortsRunReport, RunCurateShortsError, }; @@ -47,6 +72,12 @@ pub enum RunMongoCurateError { Fx(RunCurateFxError), Shorts(RunCurateShortsError), Events(RunCurateEventsError), + Fundamentals(RunCurateFundamentalsError), + Posts(RunCuratePostsError), + Macro(RunCurateMacroError), + Bars1m(RunCurateBars1mError), + QmBars1m(RunCurateQmBars1mError), + Fx1m(RunCurateFx1mError), } impl fmt::Display for RunMongoCurateError { @@ -59,6 +90,12 @@ impl fmt::Display for RunMongoCurateError { Self::Fx(e) => write!(f, "{e}"), Self::Shorts(e) => write!(f, "{e}"), Self::Events(e) => write!(f, "{e}"), + Self::Fundamentals(e) => write!(f, "{e}"), + Self::Posts(e) => write!(f, "{e}"), + Self::Macro(e) => write!(f, "{e}"), + Self::Bars1m(e) => write!(f, "{e}"), + Self::QmBars1m(e) => write!(f, "{e}"), + Self::Fx1m(e) => write!(f, "{e}"), } } } @@ -73,6 +110,12 @@ impl Error for RunMongoCurateError { Self::Fx(e) => Some(e), Self::Shorts(e) => Some(e), Self::Events(e) => Some(e), + Self::Fundamentals(e) => Some(e), + Self::Posts(e) => Some(e), + Self::Macro(e) => Some(e), + Self::Bars1m(e) => Some(e), + Self::QmBars1m(e) => Some(e), + Self::Fx1m(e) => Some(e), } } } @@ -150,6 +193,175 @@ pub struct CurateEventsMongoArgs { pub mapping_source: String, } +/// Parsed arguments for `curate-fundamentals --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateFundamentalsMongoArgs { + pub mongo: MongoCliOptions, + pub with_qm_financials_old: bool, + pub provider_mapping: PathBuf, + pub listing_venues: PathBuf, + pub out_dir: PathBuf, + pub financials_key_field: String, + pub financials_period_end_field: String, + pub financials_report_date_field: String, + pub financials_report_period_field: String, + pub financials_currency_field: String, + pub financials_revenue_field: Option, + pub financials_net_income_field: Option, + pub financials_operating_cash_flow_field: Option, + pub financials_total_assets_field: Option, + pub financials_total_equity_field: Option, + pub financials_shares_outstanding_field: Option, + pub fiscal_period: CurateFundamentalsFiscalPeriod, + pub filings_key_field: String, + pub filings_timefiled_field: String, + pub filings_form_type_field: String, + pub filings_filing_id_field: Option, + pub filings_url_field: Option, + pub mapping_source: String, + pub k: usize, +} + +impl CurateFundamentalsMongoArgs { + pub(crate) fn to_file_args(&self) -> CurateFundamentalsArgs { + CurateFundamentalsArgs { + qm_financials: mongo_virtual_path(SourceCollection::QmFinancials), + qm_financials_old: self + .with_qm_financials_old + .then(|| mongo_virtual_path(SourceCollection::QmFinancialsOld)), + qm_filings: mongo_virtual_path(SourceCollection::QmFilings), + provider_mapping: self.provider_mapping.clone(), + listing_venues: self.listing_venues.clone(), + out_dir: self.out_dir.clone(), + financials_key_field: self.financials_key_field.clone(), + financials_period_end_field: self.financials_period_end_field.clone(), + financials_report_date_field: self.financials_report_date_field.clone(), + financials_report_period_field: self.financials_report_period_field.clone(), + financials_currency_field: self.financials_currency_field.clone(), + financials_revenue_field: self.financials_revenue_field.clone(), + financials_net_income_field: self.financials_net_income_field.clone(), + financials_operating_cash_flow_field: self + .financials_operating_cash_flow_field + .clone(), + financials_total_assets_field: self.financials_total_assets_field.clone(), + financials_total_equity_field: self.financials_total_equity_field.clone(), + financials_shares_outstanding_field: self.financials_shares_outstanding_field.clone(), + fiscal_period: self.fiscal_period.clone(), + filings_key_field: self.filings_key_field.clone(), + filings_timefiled_field: self.filings_timefiled_field.clone(), + filings_form_type_field: self.filings_form_type_field.clone(), + filings_filing_id_field: self.filings_filing_id_field.clone(), + filings_url_field: self.filings_url_field.clone(), + mapping_source: self.mapping_source.clone(), + k: self.k, + } + } +} + +/// Parsed arguments for `curate-posts --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CuratePostsMongoArgs { + pub mongo: MongoCliOptions, + pub provider_mapping: PathBuf, + pub out_dir: PathBuf, + pub timestamp_unit: CeoPostsTimestampUnit, + pub key_field: String, + pub spiel_id_field: String, + pub timestamp_field: String, + pub edited_field: String, + pub bot_field: String, + pub user_id_field: String, + pub text_field: String, + pub mapping_source: String, +} + +/// Parsed arguments for `curate-macro --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateMacroMongoArgs { + pub mongo: MongoCliOptions, + pub series_map: PathBuf, + pub out_dir: PathBuf, +} + +/// Parsed arguments for `curate-bars-1m --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateBars1mMongoArgs { + pub mongo: MongoCliOptions, + pub provider_mapping_path: PathBuf, + pub out_dir: PathBuf, + pub mapping_source: String, + pub shard_count: usize, + pub known_at_micros: i64, + pub stream_options: BsonStreamOptions, + pub ilp_options: IlpWriterOptions, +} + +impl CurateBars1mMongoArgs { + pub(crate) fn to_file_args(&self) -> CurateBars1mArgs { + CurateBars1mArgs { + intraday_path: mongo_virtual_path(SourceCollection::EodIntraday1M), + splits_path: mongo_virtual_path(SourceCollection::QmSplits), + provider_mapping_path: self.provider_mapping_path.clone(), + out_dir: self.out_dir.clone(), + mapping_source: self.mapping_source.clone(), + shard_count: self.shard_count, + known_at_micros: self.known_at_micros, + stream_options: self.stream_options, + ilp_options: self.ilp_options, + } + } +} + +/// Parsed arguments for `curate-qm-bars-1m --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateQmBars1mMongoArgs { + pub mongo: MongoCliOptions, + pub provider_mapping_path: PathBuf, + pub out_dir: PathBuf, + pub mapping_source: String, + pub shard_count: usize, + pub known_at_micros: i64, + pub stream_options: BsonStreamOptions, + pub ilp_options: IlpWriterOptions, +} + +impl CurateQmBars1mMongoArgs { + pub(crate) fn to_file_args(&self) -> CurateQmBars1mArgs { + CurateQmBars1mArgs { + intraday_path: mongo_virtual_path(SourceCollection::QmIntraday), + provider_mapping_path: self.provider_mapping_path.clone(), + out_dir: self.out_dir.clone(), + mapping_source: self.mapping_source.clone(), + shard_count: self.shard_count, + known_at_micros: self.known_at_micros, + stream_options: self.stream_options, + ilp_options: self.ilp_options, + } + } +} + +/// Parsed arguments for `curate-fx-1m --from-mongo`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateFx1mMongoArgs { + pub mongo: MongoCliOptions, + pub out_dir: PathBuf, + pub shard_count: usize, + pub stream_options: BsonStreamOptions, + pub ilp_options: IlpWriterOptions, +} + +impl CurateFx1mMongoArgs { + pub(crate) fn to_file_args(&self) -> CurateFx1mArgs { + CurateFx1mArgs { + intraday_path: mongo_virtual_path(SourceCollection::EodIntraday1M), + out_dir: self.out_dir.clone(), + shard_count: self.shard_count, + stream_options: self.stream_options, + ilp_options: self.ilp_options, + } + } +} + fn mongo_virtual_path(collection: SourceCollection) -> PathBuf { PathBuf::from(format!("mongodb://{}", collection.as_str())) } @@ -496,8 +708,333 @@ pub fn run_curate_events_mongo( result } +pub(crate) fn fundamentals_read_specs( + args: &CurateFundamentalsMongoArgs, +) -> (MongoReadSpec, Option, MongoReadSpec) { + let fin_spec = args + .mongo + .to_read_spec_for_collection(SourceCollection::QmFinancials, None, true); + let fin_old_spec = args.with_qm_financials_old.then(|| { + args.mongo + .to_read_spec_for_collection(SourceCollection::QmFinancialsOld, None, true) + }); + let filings_spec = MongoReadSpec { + batch_size: args.mongo.batch_size, + limit: args.mongo.limit, + ..MongoReadSpec::default() + }; + (fin_spec, fin_old_spec, filings_spec) +} + +pub(crate) fn run_curate_fundamentals_mongo_with_readers( + args: &CurateFundamentalsMongoArgs, + financials_reader: RF, + financials_old_reader: Option, + filings_reader: RL, +) -> Result { + let file_args = args.to_file_args(); + run_curate_fundamentals_with_optional_old_readers( + &file_args, + financials_reader, + financials_old_reader, + filings_reader, + ) + .map_err(RunMongoCurateError::Fundamentals) +} + +/// Streams `qmFinancials`, optional `qmFinancials-old`, and `qmFilings` directly from read-only +/// MongoDB into `fundamentals_pit/year=YYYY/part.parquet`. +pub fn run_curate_fundamentals_mongo( + args: &CurateFundamentalsMongoArgs, +) -> Result { + let (fin_spec, fin_old_spec, filings_spec) = fundamentals_read_specs(args); + let mut checks = vec![ + (SourceCollection::QmFinancials, fin_spec.clone()), + (SourceCollection::QmFilings, filings_spec.clone()), + ]; + if let Some(old_spec) = &fin_old_spec { + checks.push((SourceCollection::QmFinancialsOld, old_spec.clone())); + } + let client = connect_and_validate_specs(&args.mongo, &checks)?; + + let result = { + let fin_reader = client + .open_raw_cursor(SourceCollection::QmFinancials, &fin_spec) + .map_err(RunMongoCurateError::Mongo)?; + let fin_old_reader = if let Some(old_spec) = &fin_old_spec { + Some( + client + .open_raw_cursor(SourceCollection::QmFinancialsOld, old_spec) + .map_err(RunMongoCurateError::Mongo)?, + ) + } else { + None + }; + let filings_reader = client + .open_raw_cursor(SourceCollection::QmFilings, &filings_spec) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_fundamentals_mongo_with_readers(args, fin_reader, fin_old_reader, filings_reader) + }; + + client.shutdown(); + result +} + +pub(crate) fn posts_read_spec(args: &CuratePostsMongoArgs) -> MongoReadSpec { + args.mongo + .to_read_spec_for_collection(SourceCollection::CeoPosts, None, true) +} + +pub(crate) fn run_curate_posts_mongo_with_reader( + args: &CuratePostsMongoArgs, + posts_reader: R, +) -> Result { + let fields = CeoPostsFieldNames { + key: args.key_field.as_str(), + spiel_id: args.spiel_id_field.as_str(), + timestamp: args.timestamp_field.as_str(), + edited: args.edited_field.as_str(), + bot: args.bot_field.as_str(), + user_id: args.user_id_field.as_str(), + text: args.text_field.as_str(), + }; + let posts_path = mongo_virtual_path(SourceCollection::CeoPosts); + run_curate_posts_with_reader( + &args.provider_mapping, + &args.mapping_source, + &fields, + args.timestamp_unit, + (&posts_path, posts_reader), + &args.out_dir, + ) + .map_err(RunMongoCurateError::Posts) +} + +/// Streams `ceoPosts` directly from read-only MongoDB into `events/year=YYYY/part-posts.parquet`. +pub fn run_curate_posts_mongo( + args: &CuratePostsMongoArgs, +) -> Result { + let posts_spec = posts_read_spec(args); + let client = connect_and_validate_specs( + &args.mongo, + &[(SourceCollection::CeoPosts, posts_spec.clone())], + )?; + + let result = { + let posts_reader = client + .open_raw_cursor(SourceCollection::CeoPosts, &posts_spec) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_posts_mongo_with_reader(args, posts_reader) + }; + + client.shutdown(); + result +} + +pub(crate) fn macro_read_spec(args: &CurateMacroMongoArgs) -> MongoReadSpec { + args.mongo + .to_read_spec_for_collection(SourceCollection::TeData, None, true) +} + +pub(crate) fn run_curate_macro_mongo_with_reader( + args: &CurateMacroMongoArgs, + te_data_reader: R, +) -> Result { + let te_path = mongo_virtual_path(SourceCollection::TeData); + run_curate_macro_from_reader(&te_path, te_data_reader, &args.series_map, &args.out_dir) + .map_err(RunMongoCurateError::Macro) +} + +/// Streams `teData` directly from read-only MongoDB alongside caller-owned `series_map.tsv` +/// into `macro/part.parquet`. +pub fn run_curate_macro_mongo( + args: &CurateMacroMongoArgs, +) -> Result { + let te_spec = macro_read_spec(args); + let client = + connect_and_validate_specs(&args.mongo, &[(SourceCollection::TeData, te_spec.clone())])?; + + let result = { + let te_reader = client + .open_raw_cursor(SourceCollection::TeData, &te_spec) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_macro_mongo_with_reader(args, te_reader) + }; + + client.shutdown(); + result +} + +pub(crate) fn bars_1m_read_specs(args: &CurateBars1mMongoArgs) -> (MongoReadSpec, MongoReadSpec) { + let splits_spec = MongoReadSpec { + batch_size: args.mongo.batch_size, + ..MongoReadSpec::default() + }; + let intraday_spec = + args.mongo + .to_read_spec_for_collection(SourceCollection::EodIntraday1M, None, true); + (splits_spec, intraday_spec) +} + +pub(crate) fn run_curate_bars_1m_mongo_with_readers( + args: &CurateBars1mMongoArgs, + intraday_reader: RI, + splits_reader: RS, +) -> Result { + let file_args = args.to_file_args(); + run_curate_bars_1m_from_readers_to_dir(&file_args, intraday_reader, splits_reader) + .map_err(RunMongoCurateError::Bars1m) +} + +/// Streams `qmSplits` and `eodIntraday1M` directly from read-only MongoDB into +/// `/bars_1m.shard-.ilp`. +/// +/// `qmSplits` is always read without a date-range filter so post-bar cumulative split factors +/// remain exact. When `--limit` is not set, `eodIntraday1M` is streamed in indexed `$in` key +/// chunks (`250` keys/chunk) derived from `provider_mapping.tsv`. +pub fn run_curate_bars_1m_mongo( + args: &CurateBars1mMongoArgs, +) -> Result { + let (splits_spec, intraday_spec) = bars_1m_read_specs(args); + let client = connect_and_validate_specs( + &args.mongo, + &[ + (SourceCollection::QmSplits, splits_spec.clone()), + (SourceCollection::EodIntraday1M, intraday_spec.clone()), + ], + )?; + + let use_key_chunks = args.mongo.limit.is_none(); + let eod_keys = if use_key_chunks { + unique_mapping_keys_for_source(&args.provider_mapping_path, &args.mapping_source) + .map_err(|e| RunMongoCurateError::Bars1m(RunCurateBars1mError::LoadReference(e)))? + } else { + Vec::new() + }; + + let result = { + let splits_reader = client + .open_raw_cursor(SourceCollection::QmSplits, &splits_spec) + .map_err(RunMongoCurateError::Mongo)?; + if use_key_chunks { + let intraday_reader = client + .open_raw_cursor_for_keys( + SourceCollection::EodIntraday1M, + &intraday_spec, + &eod_keys, + 250, + ) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_bars_1m_mongo_with_readers(args, intraday_reader, splits_reader) + } else { + let intraday_reader = client + .open_raw_cursor(SourceCollection::EodIntraday1M, &intraday_spec) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_bars_1m_mongo_with_readers(args, intraday_reader, splits_reader) + } + }; + + client.shutdown(); + result +} + +pub(crate) fn qm_bars_1m_read_spec(args: &CurateQmBars1mMongoArgs) -> MongoReadSpec { + args.mongo + .to_read_spec_for_collection(SourceCollection::QmIntraday, None, true) +} + +pub(crate) fn run_curate_qm_bars_1m_mongo_with_reader( + args: &CurateQmBars1mMongoArgs, + intraday_reader: R, +) -> Result { + let file_args = args.to_file_args(); + run_curate_qm_bars_1m_from_reader_to_dir(&file_args, intraday_reader) + .map_err(RunMongoCurateError::QmBars1m) +} + +/// Streams `qmIntraday` directly from read-only MongoDB into +/// `/bars_1m_qm.shard-.ilp`. +/// +/// When `--limit` is not set, `qmIntraday` is streamed in indexed `$in` key chunks (`250` +/// keys/chunk) derived from `provider_mapping.tsv`. +pub fn run_curate_qm_bars_1m_mongo( + args: &CurateQmBars1mMongoArgs, +) -> Result { + let intraday_spec = qm_bars_1m_read_spec(args); + let client = connect_and_validate_specs( + &args.mongo, + &[(SourceCollection::QmIntraday, intraday_spec.clone())], + )?; + + let use_key_chunks = args.mongo.limit.is_none(); + let qm_keys = if use_key_chunks { + unique_mapping_keys_for_source(&args.provider_mapping_path, &args.mapping_source) + .map_err(|e| RunMongoCurateError::QmBars1m(RunCurateQmBars1mError::LoadReference(e)))? + } else { + Vec::new() + }; + + let result = if use_key_chunks { + let intraday_reader = client + .open_raw_cursor_for_keys(SourceCollection::QmIntraday, &intraday_spec, &qm_keys, 250) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_qm_bars_1m_mongo_with_reader(args, intraday_reader) + } else { + let intraday_reader = client + .open_raw_cursor(SourceCollection::QmIntraday, &intraday_spec) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_qm_bars_1m_mongo_with_reader(args, intraday_reader) + }; + + client.shutdown(); + result +} + +pub(crate) fn fx_1m_read_spec(args: &CurateFx1mMongoArgs) -> MongoReadSpec { + args.mongo.to_read_spec_for_collection( + SourceCollection::EodIntraday1M, + Some(EOD_CAD_FOREX_CODE.to_owned()), + true, + ) +} + +pub(crate) fn run_curate_fx_1m_mongo_with_reader( + args: &CurateFx1mMongoArgs, + intraday_reader: R, +) -> Result { + let file_args = args.to_file_args(); + run_curate_fx_1m_from_reader_to_dir(&file_args, intraday_reader) + .map_err(RunMongoCurateError::Fx1m) +} + +/// Streams `eodIntraday1M` (`eodSearchCode == "CAD.FOREX"`) directly from read-only MongoDB into +/// `/fx_1m.shard-.ilp`. +pub fn run_curate_fx_1m_mongo( + args: &CurateFx1mMongoArgs, +) -> Result { + let fx_spec = fx_1m_read_spec(args); + let client = connect_and_validate_specs( + &args.mongo, + &[(SourceCollection::EodIntraday1M, fx_spec.clone())], + )?; + + let result = { + let intraday_reader = client + .open_raw_cursor(SourceCollection::EodIntraday1M, &fx_spec) + .map_err(RunMongoCurateError::Mongo)?; + run_curate_fx_1m_mongo_with_reader(args, intraday_reader) + }; + + client.shutdown(); + result +} + /// Formats a virtual path label for diagnostics (keeps `Path` import used cleanly). #[allow(dead_code)] fn _assert_path_ref(path: &Path) -> &Path { path } + +#[cfg(test)] +#[path = "run_mongo_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_mongo_tests.rs b/tools/curate-etl/src/run_mongo_tests.rs new file mode 100644 index 00000000..a921bc06 --- /dev/null +++ b/tools/curate-etl/src/run_mongo_tests.rs @@ -0,0 +1,824 @@ +use std::collections::BTreeMap; +use std::fs; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf}; +use bson::{Bson, DateTime}; + +use super::{ + bars_1m_read_specs, fundamentals_read_specs, fx_1m_read_spec, macro_read_spec, posts_read_spec, + qm_bars_1m_read_spec, run_curate_bars_1m_mongo, run_curate_bars_1m_mongo_with_readers, + run_curate_fundamentals_mongo, run_curate_fundamentals_mongo_with_readers, + run_curate_fx_1m_mongo, run_curate_fx_1m_mongo_with_reader, run_curate_macro_mongo, + run_curate_macro_mongo_with_reader, run_curate_posts_mongo, + run_curate_posts_mongo_with_reader, run_curate_qm_bars_1m_mongo, + run_curate_qm_bars_1m_mongo_with_reader, CurateBars1mMongoArgs, CurateFundamentalsMongoArgs, + CurateFx1mMongoArgs, CurateMacroMongoArgs, CuratePostsMongoArgs, CurateQmBars1mMongoArgs, + RunMongoCurateError, +}; +use crate::bson_ceo_posts::{ + CeoPostsTimestampUnit, DEFAULT_BOT_FIELD, DEFAULT_EDITED_FIELD, DEFAULT_KEY_FIELD, + DEFAULT_SPIEL_ID_FIELD, DEFAULT_TEXT_FIELD, DEFAULT_TIMESTAMP_FIELD, DEFAULT_USER_ID_FIELD, +}; +use crate::bson_qm_events::{DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD}; +use crate::bson_qm_financials::{ + DEFAULT_QM_FINANCIALS_KEY_FIELD, DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD, + DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD, DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD, +}; +use crate::bson_stream::BsonStreamOptions; +use crate::fundamentals::FiscalPeriod; +use crate::ilp::IlpWriterOptions; +use crate::mongo_stream::{ + build_filter_document, MongoCliOptions, MongoStreamError, MongoUriSource, RawBsonCursorReader, + SliceRawDocumentSource, SourceCollection, VecRawDocumentSource, +}; +use crate::run_curate_bars_1m::{ + run_curate_bars_1m, CurateBars1mArgs, DEFAULT_BARS_1M_MAPPING_SOURCE, +}; +use crate::run_curate_fundamentals::{ + run_curate_fundamentals, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, + DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, +}; +use crate::run_curate_fx_1m::{run_curate_fx_1m, CurateFx1mArgs}; +use crate::run_curate_macro::{run_curate_macro, CurateMacroArgs, MACRO_SERIES_MAP_HEADER}; +use crate::run_curate_posts::{ + run_curate_posts, CuratePostsArgs, DEFAULT_MAPPING_SOURCE as DEFAULT_POSTS_MAPPING_SOURCE, +}; +use crate::run_curate_qm_bars_1m::{ + run_curate_qm_bars_1m, CurateQmBars1mArgs, DEFAULT_QM_BARS_1M_MAPPING_SOURCE, +}; + +static TEMP_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-run-mongo-test-{label}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp test dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +struct CappedRead { + inner: R, + max_step: usize, +} + +impl CappedRead { + fn new(inner: R, max_step: usize) -> Self { + Self { inner, max_step } + } +} + +impl Read for CappedRead { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let cap = buf.len().min(self.max_step); + self.inner.read(&mut buf[..cap]) + } +} + +fn concat_docs(docs: &[Vec]) -> Vec { + let mut out = Vec::new(); + for d in docs { + out.extend_from_slice(d); + } + out +} + +fn snapshot_files(root: &Path) -> BTreeMap> { + fn walk(base: &Path, dir: &Path, out: &mut BTreeMap>) { + if !dir.exists() { + return; + } + for entry in fs::read_dir(dir).expect("read_dir") { + let entry = entry.expect("dir entry"); + let path = entry.path(); + if path.is_dir() { + walk(base, &path, out); + } else { + let rel = path.strip_prefix(base).expect("strip_prefix").to_path_buf(); + out.insert(rel, fs::read(&path).expect("read file")); + } + } + } + let mut out = BTreeMap::new(); + walk(root, root, &mut out); + out +} + +fn make_fin_doc( + key: &str, + period_end: &str, + report_date: &str, + report_period: &str, + rev: f64, +) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), key); + doc.append(cstr!("periodEndDate"), period_end); + doc.append(cstr!("reportDate"), report_date); + doc.append(cstr!("reportPeriod"), report_period); + doc.append(cstr!("currency"), "USD"); + doc.append(cstr!("revenue"), rev); + doc.into_bytes() +} + +fn make_filing_doc(key: &str, timefiled: &str, form_type: &str) -> Vec { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("symbol"), key); + doc.append(cstr!("timefiled"), timefiled); + doc.append(cstr!("formType"), form_type); + doc.into_bytes() +} + +#[test] +fn parity_curate_fundamentals_mongo_cursor_matches_file_mode_with_and_without_old() { + let tmp = TempDirGuard::new("parity-fundamentals"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let ven_path = tmp.path().join("listing_venues.tsv"); + fs::write(&map_path, "qm\tACME:US\t101\t2020-01-01\t\n").unwrap(); + fs::write(&ven_path, "101\tus_tsx\n").unwrap(); + + let fin_docs = vec![ + make_fin_doc("ACME:US", "2024-06-30", "2024-08-05", "Q2", 130.0), + make_fin_doc("ACME:US", "2024-03-31", "2024-09-10", "Q1", 125.0), + ]; + let old_docs = vec![ + make_fin_doc("ACME:US", "2023-09-30", "2023-11-05", "Q3", 100.0), + make_fin_doc("ACME:US", "2023-12-31", "2024-02-20", "Q4", 110.0), + make_fin_doc("ACME:US", "2024-03-31", "2024-05-05", "Q1", 120.0), + ]; + let fil_docs = vec![ + make_filing_doc("ACME:US", "2023-11-05T16:30:00 EST", "10-Q"), + make_filing_doc("ACME:US", "2024-02-20T16:30:00 EST", "10-Q"), + make_filing_doc("ACME:US", "2024-05-05T16:30:00 EDT", "10-Q"), + make_filing_doc("ACME:US", "2024-08-05T16:30:00 EDT", "10-Q"), + make_filing_doc("ACME:US", "2024-09-10T16:30:00 EDT", "10-Q/A"), + ]; + + let fin_path = tmp.path().join("qmFinancials.bson"); + let old_path = tmp.path().join("qmFinancials-old.bson"); + let fil_path = tmp.path().join("qmFilings.bson"); + fs::write(&fin_path, concat_docs(&fin_docs)).unwrap(); + fs::write(&old_path, concat_docs(&old_docs)).unwrap(); + fs::write(&fil_path, concat_docs(&fil_docs)).unwrap(); + + for with_old in [false, true] { + let out_file = tmp.path().join(format!("out_file_{with_old}")); + let out_mongo = tmp.path().join(format!("out_mongo_{with_old}")); + + let mut file_args = CurateFundamentalsArgs::with_verified_defaults( + fin_path.clone(), + fil_path.clone(), + map_path.clone(), + ven_path.clone(), + out_file.clone(), + "currency", + Some("revenue".to_string()), + None, + None, + None, + None, + None, + CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly), + "formType", + 4, + ); + if with_old { + file_args.qm_financials_old = Some(old_path.clone()); + } + let file_rep = run_curate_fundamentals(&file_args).expect("file-mode fundamentals"); + + let mongo_args = CurateFundamentalsMongoArgs { + mongo: MongoCliOptions::default(), + with_qm_financials_old: with_old, + provider_mapping: map_path.clone(), + listing_venues: ven_path.clone(), + out_dir: out_mongo.clone(), + financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(), + financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(), + financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(), + financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string(), + financials_currency_field: "currency".to_string(), + financials_revenue_field: Some("revenue".to_string()), + financials_net_income_field: None, + financials_operating_cash_flow_field: None, + financials_total_assets_field: None, + financials_total_equity_field: None, + financials_shares_outstanding_field: None, + fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly), + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: "formType".to_string(), + filings_filing_id_field: None, + filings_url_field: None, + mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(), + k: 4, + }; + + let fin_slices: Vec<&[u8]> = fin_docs.iter().map(Vec::as_slice).collect(); + let fin_reader = CappedRead::new( + RawBsonCursorReader::new(SliceRawDocumentSource::new(&fin_slices)), + 7, + ); + let old_reader = with_old.then(|| { + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(old_docs.clone())), + 13, + ) + }); + let fil_reader = CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(fil_docs.clone())), + 11, + ); + + let mongo_rep = run_curate_fundamentals_mongo_with_readers( + &mongo_args, + fin_reader, + old_reader, + fil_reader, + ) + .expect("mongo-cursor fundamentals"); + + assert_eq!(mongo_rep.curate_stats, file_rep.curate_stats); + assert_eq!(mongo_rep.write_stats, file_rep.write_stats); + assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file)); + } +} + +#[test] +fn parity_curate_posts_mongo_cursor_matches_file_mode_byte_for_byte() { + let tmp = TempDirGuard::new("parity-posts"); + let map_path = tmp.path().join("provider_mapping.tsv"); + fs::write(&map_path, "ceo\t5001\t202\t2020-01-01\t\n").unwrap(); + + let mut d1 = RawDocumentBuf::new(); + d1.append(cstr!("ceoId"), "5001"); + d1.append(cstr!("spielId"), "p1"); + d1.append(cstr!("timestamp"), 1_710_000_000_i64); + d1.append(cstr!("edited"), 1_710_003_600_i64); + d1.append(cstr!("bot"), "0"); + d1.append(cstr!("userId"), "u1"); + d1.append(cstr!("spiel"), "edited post body"); + + let mut d2 = RawDocumentBuf::new(); + d2.append(cstr!("ceoId"), "5001"); + d2.append(cstr!("spielId"), "p2"); + d2.append(cstr!("timestamp"), 1_710_010_000_i64); + d2.append(cstr!("edited"), false); + d2.append(cstr!("bot"), "1"); + d2.append(cstr!("userId"), "bot"); + d2.append(cstr!("spiel"), "newswire release"); + + let docs = vec![d1.into_bytes(), d2.into_bytes()]; + let bson_path = tmp.path().join("ceoPosts.bson"); + fs::write(&bson_path, concat_docs(&docs)).unwrap(); + + let out_file = tmp.path().join("out_file"); + let out_mongo = tmp.path().join("out_mongo"); + + let file_rep = run_curate_posts(&CuratePostsArgs { + ceo_posts: bson_path, + provider_mapping: map_path.clone(), + out_dir: out_file.clone(), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: DEFAULT_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_EDITED_FIELD.to_string(), + bot_field: DEFAULT_BOT_FIELD.to_string(), + user_id_field: DEFAULT_USER_ID_FIELD.to_string(), + text_field: DEFAULT_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), + }) + .expect("file-mode posts"); + + let mongo_args = CuratePostsMongoArgs { + mongo: MongoCliOptions::default(), + provider_mapping: map_path, + out_dir: out_mongo.clone(), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: DEFAULT_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_EDITED_FIELD.to_string(), + bot_field: DEFAULT_BOT_FIELD.to_string(), + user_id_field: DEFAULT_USER_ID_FIELD.to_string(), + text_field: DEFAULT_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), + }; + let reader = CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(docs)), + 5, + ); + let mongo_rep = run_curate_posts_mongo_with_reader(&mongo_args, reader).expect("mongo posts"); + + assert_eq!(mongo_rep.curate_stats, file_rep.curate_stats); + assert_eq!(mongo_rep.write_stats, file_rep.write_stats); + assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file)); +} + +#[test] +fn parity_curate_macro_mongo_cursor_matches_file_mode_byte_for_byte() { + let tmp = TempDirGuard::new("parity-macro"); + let map_path = tmp.path().join("series_map.tsv"); + fs::write( + &map_path, + format!( + "{MACRO_SERIES_MAP_HEADER}\nUS_CPI\tUnited States\tInflation Rate\tUS\tcpi_yoy\tmonthly_release\n" + ), + ) + .unwrap(); + + let mut pt = RawDocumentBuf::new(); + pt.append(cstr!("d"), "2024-01-31"); + pt.append(cstr!("v"), 3.1_f64); + let mut data_arr = RawArrayBuf::new(); + data_arr.push(pt); + let mut fpt = RawDocumentBuf::new(); + fpt.append(cstr!("d"), "2025-01-31"); + fpt.append(cstr!("v"), 9.9_f64); + let mut forecast_arr = RawArrayBuf::new(); + forecast_arr.push(fpt); + + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("teSymbol"), "US_CPI"); + doc.append(cstr!("country"), "United States"); + doc.append(cstr!("category"), "Inflation Rate"); + doc.append(cstr!("data"), data_arr); + doc.append(cstr!("forecast"), forecast_arr); + + let docs = vec![doc.into_bytes()]; + let bson_path = tmp.path().join("teData.bson"); + fs::write(&bson_path, concat_docs(&docs)).unwrap(); + + let out_file = tmp.path().join("out_file"); + let out_mongo = tmp.path().join("out_mongo"); + + let file_rep = run_curate_macro(&CurateMacroArgs { + te_data: bson_path, + series_map: map_path.clone(), + out_dir: out_file.clone(), + }) + .expect("file-mode macro"); + + let mongo_args = CurateMacroMongoArgs { + mongo: MongoCliOptions::default(), + series_map: map_path, + out_dir: out_mongo.clone(), + }; + let reader = CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(docs)), + 7, + ); + let mongo_rep = run_curate_macro_mongo_with_reader(&mongo_args, reader).expect("mongo macro"); + + assert_eq!(mongo_rep, file_rep); + assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file)); +} + +#[test] +fn parity_curate_1m_ilp_mongo_cursors_match_file_mode_byte_for_byte() { + let tmp = TempDirGuard::new("parity-1m-ilp"); + let map_path = tmp.path().join("provider_mapping.tsv"); + fs::write( + &map_path, + "eod\tNVDA.US\t301\t2020-01-01\t\nqm\tNVDA:US\t301\t2020-01-01\t\n", + ) + .unwrap(); + + // qmSplits: 10:1 split on 2024-06-10 + let mut sp = RawDocumentBuf::new(); + sp.append(cstr!("qmSearchCode"), "NVDA:US"); + sp.append(cstr!("date"), "2024-06-10"); + sp.append(cstr!("splitratio"), 10.0_f64); + let split_docs = vec![sp.into_bytes()]; + + // eodIntraday1M: equity bar + CAD.FOREX bar + let mut b_eq = RawDocumentBuf::new(); + b_eq.append(cstr!("eodSearchCode"), "NVDA.US"); + b_eq.append(cstr!("timestamp"), 1_717_767_000_i64); // 2024-06-07 13:30:00Z (09:30 ET) + b_eq.append(cstr!("open"), 120.0_f64); + b_eq.append(cstr!("high"), 121.0_f64); + b_eq.append(cstr!("low"), 119.0_f64); + b_eq.append(cstr!("close"), 120.5_f64); + b_eq.append(cstr!("volume"), 1000.0_f64); + + let mut b_fx = RawDocumentBuf::new(); + b_fx.append(cstr!("eodSearchCode"), "CAD.FOREX"); + b_fx.append(cstr!("timestamp"), 1_717_767_000_i64); + b_fx.append(cstr!("open"), 1.3700_f64); + b_fx.append(cstr!("high"), 1.3710_f64); + b_fx.append(cstr!("low"), 1.3690_f64); + b_fx.append(cstr!("close"), 1.3705_f64); + b_fx.append(cstr!("volume"), 0.0_f64); + + let eod_1m_docs = vec![b_eq.into_bytes(), b_fx.into_bytes()]; + + // qmIntraday: raw bar + let mut b_qm = RawDocumentBuf::new(); + b_qm.append(cstr!("qmSearchCode"), "NVDA:US"); + b_qm.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); + b_qm.append(cstr!("open"), 1200.0_f64); + b_qm.append(cstr!("high"), 1210.0_f64); + b_qm.append(cstr!("low"), 1190.0_f64); + b_qm.append(cstr!("close"), 1205.0_f64); + b_qm.append(cstr!("sharevolume"), 100.0_f64); + let qm_1m_docs = vec![b_qm.into_bytes()]; + + let splits_path = tmp.path().join("qmSplits.bson"); + let eod_path = tmp.path().join("eodIntraday1M.bson"); + let qm_path = tmp.path().join("qmIntraday.bson"); + fs::write(&splits_path, concat_docs(&split_docs)).unwrap(); + fs::write(&eod_path, concat_docs(&eod_1m_docs)).unwrap(); + fs::write(&qm_path, concat_docs(&qm_1m_docs)).unwrap(); + + // Shared output dirs prove bars_1m, bars_1m_qm, and fx_1m co-exist in one --out dir. + let out_file = tmp.path().join("out_file"); + let out_mongo = tmp.path().join("out_mongo"); + let known_at = 1_750_000_000_000_000_i64; + + // 1. curate-bars-1m + let file_b1m = run_curate_bars_1m(&CurateBars1mArgs { + intraday_path: eod_path.clone(), + splits_path, + provider_mapping_path: map_path.clone(), + out_dir: out_file.clone(), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect("file bars_1m"); + let mongo_b1m = run_curate_bars_1m_mongo_with_readers( + &CurateBars1mMongoArgs { + mongo: MongoCliOptions::default(), + provider_mapping_path: map_path.clone(), + out_dir: out_mongo.clone(), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }, + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(eod_1m_docs.clone())), + 9, + ), + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(split_docs)), + 5, + ), + ) + .expect("mongo bars_1m"); + assert_eq!(mongo_b1m.curate_stats, file_b1m.curate_stats); + assert_eq!(mongo_b1m.ilp_stats, file_b1m.ilp_stats); + + // 2. curate-qm-bars-1m in the same --out dir + let file_qm1m = run_curate_qm_bars_1m(&CurateQmBars1mArgs { + intraday_path: qm_path, + provider_mapping_path: map_path.clone(), + out_dir: out_file.clone(), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect("file qm_bars_1m"); + let qm_slices: Vec<&[u8]> = qm_1m_docs.iter().map(Vec::as_slice).collect(); + let mongo_qm1m = run_curate_qm_bars_1m_mongo_with_reader( + &CurateQmBars1mMongoArgs { + mongo: MongoCliOptions::default(), + provider_mapping_path: map_path, + out_dir: out_mongo.clone(), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: known_at, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }, + CappedRead::new( + RawBsonCursorReader::new(SliceRawDocumentSource::new(&qm_slices)), + 7, + ), + ) + .expect("mongo qm_bars_1m"); + assert_eq!(mongo_qm1m.curate_stats, file_qm1m.curate_stats); + assert_eq!(mongo_qm1m.ilp_stats, file_qm1m.ilp_stats); + + // 3. curate-fx-1m in the same --out dir + let file_fx1m = run_curate_fx_1m(&CurateFx1mArgs { + intraday_path: eod_path, + out_dir: out_file.clone(), + shard_count: 2, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect("file fx_1m"); + let mongo_fx1m = run_curate_fx_1m_mongo_with_reader( + &CurateFx1mMongoArgs { + mongo: MongoCliOptions::default(), + out_dir: out_mongo.clone(), + shard_count: 2, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }, + CappedRead::new( + RawBsonCursorReader::new(VecRawDocumentSource::new(eod_1m_docs)), + 11, + ), + ) + .expect("mongo fx_1m"); + assert_eq!(mongo_fx1m.curate_stats, file_fx1m.curate_stats); + assert_eq!(mongo_fx1m.ilp_stats, file_fx1m.ilp_stats); + + assert_eq!(snapshot_files(&out_mongo), snapshot_files(&out_file)); +} + +#[test] +fn m2_mongo_read_specs_enforce_filter_types_and_key_scoping() { + let opts = MongoCliOptions { + date_gte: Some("2024-01-01".to_owned()), + date_lt: Some("2024-01-02".to_owned()), + ..MongoCliOptions::default() + }; + + // curate-fx-1m scopes to eodSearchCode == "CAD.FOREX" + Int64 epoch seconds. + let fx_args = CurateFx1mMongoArgs { + mongo: opts.clone(), + out_dir: PathBuf::from("out"), + shard_count: 2, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }; + let fx_spec = fx_1m_read_spec(&fx_args); + let fx_doc = build_filter_document(SourceCollection::EodIntraday1M, &fx_spec).unwrap(); + assert_eq!( + fx_doc.get("eodSearchCode"), + Some(&Bson::String("CAD.FOREX".to_owned())) + ); + let fx_ts = fx_doc.get_document("timestamp").unwrap(); + assert_eq!(fx_ts.get("$gte"), Some(&Bson::Int64(1_704_067_200))); + assert_eq!(fx_ts.get("$lt"), Some(&Bson::Int64(1_704_153_600))); + + // curate-bars-1m keeps qmSplits unfiltered on dates, eodIntraday1M as Int64 epoch seconds. + let b1m_args = CurateBars1mMongoArgs { + mongo: opts.clone(), + provider_mapping_path: PathBuf::from("pm.tsv"), + out_dir: PathBuf::from("out"), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: 1, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }; + let (splits_spec, intraday_spec) = bars_1m_read_specs(&b1m_args); + assert!(splits_spec.date_range.is_none()); + let b1m_doc = build_filter_document(SourceCollection::EodIntraday1M, &intraday_spec).unwrap(); + assert_eq!( + b1m_doc.get_document("timestamp").unwrap().get("$gte"), + Some(&Bson::Int64(1_704_067_200)) + ); + + // curate-qm-bars-1m uses Bson::DateTime millis. + let qm_args = CurateQmBars1mMongoArgs { + mongo: opts.clone(), + provider_mapping_path: PathBuf::from("pm.tsv"), + out_dir: PathBuf::from("out"), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: 1, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }; + let qm_spec = qm_bars_1m_read_spec(&qm_args); + let qm_doc = build_filter_document(SourceCollection::QmIntraday, &qm_spec).unwrap(); + assert_eq!( + qm_doc.get_document("timestamp").unwrap().get("$gte"), + Some(&Bson::DateTime(DateTime::from_millis(1_704_067_200_000))) + ); + + // Non-date-ranged M2 collections fail closed with DateRangeNotSupported. + let fin_args = CurateFundamentalsMongoArgs { + mongo: opts.clone(), + with_qm_financials_old: true, + provider_mapping: PathBuf::from("pm.tsv"), + listing_venues: PathBuf::from("lv.tsv"), + out_dir: PathBuf::from("out"), + financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(), + financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(), + financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(), + financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string(), + financials_currency_field: "currency".to_string(), + financials_revenue_field: None, + financials_net_income_field: None, + financials_operating_cash_flow_field: None, + financials_total_assets_field: None, + financials_total_equity_field: None, + financials_shares_outstanding_field: None, + fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly), + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: "formType".to_string(), + filings_filing_id_field: None, + filings_url_field: None, + mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(), + k: 4, + }; + let (fin_spec, fin_old_spec, filings_spec) = fundamentals_read_specs(&fin_args); + assert!(matches!( + fin_spec.validate(SourceCollection::QmFinancials), + Err(MongoStreamError::DateRangeNotSupported { + collection: SourceCollection::QmFinancials + }) + )); + assert!(matches!( + fin_old_spec + .unwrap() + .validate(SourceCollection::QmFinancialsOld), + Err(MongoStreamError::DateRangeNotSupported { + collection: SourceCollection::QmFinancialsOld + }) + )); + assert!(filings_spec.date_range.is_none()); + + let posts_spec = posts_read_spec(&CuratePostsMongoArgs { + mongo: opts.clone(), + provider_mapping: PathBuf::from("pm.tsv"), + out_dir: PathBuf::from("out"), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: DEFAULT_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_EDITED_FIELD.to_string(), + bot_field: DEFAULT_BOT_FIELD.to_string(), + user_id_field: DEFAULT_USER_ID_FIELD.to_string(), + text_field: DEFAULT_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), + }); + assert!(matches!( + posts_spec.validate(SourceCollection::CeoPosts), + Err(MongoStreamError::DateRangeNotSupported { + collection: SourceCollection::CeoPosts + }) + )); + + let macro_spec = macro_read_spec(&CurateMacroMongoArgs { + mongo: opts, + series_map: PathBuf::from("sm.tsv"), + out_dir: PathBuf::from("out"), + }); + assert!(matches!( + macro_spec.validate(SourceCollection::TeData), + Err(MongoStreamError::DateRangeNotSupported { + collection: SourceCollection::TeData + }) + )); +} + +#[test] +fn m2_mongo_runners_fail_closed_on_trading_admin_and_unauthenticated_qa_uris() { + let tmp = TempDirGuard::new("mongo-safety-m2"); + let secret = "S3CR3T_ADMIN_PASS_999"; + let bad_uris = [ + format!("mongodb://trading_admin:{secret}@localhost:27017/stock?authSource=admin"), + "mongodb://localhost:27017/stock".to_string(), + ]; + + for (idx, uri) in bad_uris.iter().enumerate() { + let mongo = MongoCliOptions { + uri_source: MongoUriSource::Literal(uri.clone()), + ..MongoCliOptions::default() + }; + + let out_fin = tmp.path().join(format!("fin_{idx}")); + let err = run_curate_fundamentals_mongo(&CurateFundamentalsMongoArgs { + mongo: mongo.clone(), + with_qm_financials_old: true, + provider_mapping: tmp.path().join("pm.tsv"), + listing_venues: tmp.path().join("lv.tsv"), + out_dir: out_fin.clone(), + financials_key_field: DEFAULT_QM_FINANCIALS_KEY_FIELD.to_string(), + financials_period_end_field: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD.to_string(), + financials_report_date_field: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD.to_string(), + financials_report_period_field: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD.to_string(), + financials_currency_field: "currency".to_string(), + financials_revenue_field: None, + financials_net_income_field: None, + financials_operating_cash_flow_field: None, + financials_total_assets_field: None, + financials_total_equity_field: None, + financials_shares_outstanding_field: None, + fiscal_period: CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Quarterly), + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: "formType".to_string(), + filings_filing_id_field: None, + filings_url_field: None, + mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(), + k: 4, + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_fin.exists()); + + let out_posts = tmp.path().join(format!("posts_{idx}")); + let err = run_curate_posts_mongo(&CuratePostsMongoArgs { + mongo: mongo.clone(), + provider_mapping: tmp.path().join("pm.tsv"), + out_dir: out_posts.clone(), + timestamp_unit: CeoPostsTimestampUnit::Seconds, + key_field: DEFAULT_KEY_FIELD.to_string(), + spiel_id_field: DEFAULT_SPIEL_ID_FIELD.to_string(), + timestamp_field: DEFAULT_TIMESTAMP_FIELD.to_string(), + edited_field: DEFAULT_EDITED_FIELD.to_string(), + bot_field: DEFAULT_BOT_FIELD.to_string(), + user_id_field: DEFAULT_USER_ID_FIELD.to_string(), + text_field: DEFAULT_TEXT_FIELD.to_string(), + mapping_source: DEFAULT_POSTS_MAPPING_SOURCE.to_string(), + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_posts.exists()); + + let out_macro = tmp.path().join(format!("macro_{idx}")); + let err = run_curate_macro_mongo(&CurateMacroMongoArgs { + mongo: mongo.clone(), + series_map: tmp.path().join("sm.tsv"), + out_dir: out_macro.clone(), + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_macro.exists()); + + let out_b1m = tmp.path().join(format!("b1m_{idx}")); + let err = run_curate_bars_1m_mongo(&CurateBars1mMongoArgs { + mongo: mongo.clone(), + provider_mapping_path: tmp.path().join("pm.tsv"), + out_dir: out_b1m.clone(), + mapping_source: DEFAULT_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: 1, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_b1m.exists()); + + let out_qm1m = tmp.path().join(format!("qm1m_{idx}")); + let err = run_curate_qm_bars_1m_mongo(&CurateQmBars1mMongoArgs { + mongo: mongo.clone(), + provider_mapping_path: tmp.path().join("pm.tsv"), + out_dir: out_qm1m.clone(), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 2, + known_at_micros: 1, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_qm1m.exists()); + + let out_fx1m = tmp.path().join(format!("fx1m_{idx}")); + let err = run_curate_fx_1m_mongo(&CurateFx1mMongoArgs { + mongo, + out_dir: out_fx1m.clone(), + shard_count: 2, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + .expect_err("unsafe URI must fail closed"); + assert!(matches!(err, RunMongoCurateError::Mongo(_))); + assert!(!err.to_string().contains(secret)); + assert!(!out_fx1m.exists()); + } +} diff --git a/tools/curate-etl/tests/curate_bars_1m.rs b/tools/curate-etl/tests/curate_bars_1m.rs index f1b43972..9ade034d 100644 --- a/tools/curate-etl/tests/curate_bars_1m.rs +++ b/tools/curate-etl/tests/curate_bars_1m.rs @@ -619,7 +619,10 @@ fn curate_bars_1m_binary_parse_error_prints_usage_hides_secret_and_writes_nothin assert!(!output.status.success()); assert!(output.stdout.is_empty()); let stderr = String::from_utf8_lossy(&output.stderr); - assert!(stderr.contains("file mode only"), "stderr: {stderr}"); + assert!( + stderr.contains("MongoDB streaming flags require '--from-mongo'"), + "stderr: {stderr}" + ); assert!(stderr.contains("curate-bars-1m --eod-intraday"), "usage expected: {stderr}"); assert!(!stderr.contains("s3cr3t_pw"), "secret leaked: {stderr}"); assert!(!out.exists(), "parse failure must not create --out"); diff --git a/tools/curate-etl/tests/curate_fundamentals.rs b/tools/curate-etl/tests/curate_fundamentals.rs index b5fef7b5..4660479f 100644 --- a/tools/curate-etl/tests/curate_fundamentals.rs +++ b/tools/curate-etl/tests/curate_fundamentals.rs @@ -493,7 +493,7 @@ fn cli_fails_closed_without_creating_out_dir_on_invalid_flags() { let mut lines_mongo = stderr_mongo.lines(); assert_eq!( lines_mongo.next(), - Some("error: unknown flag '--from-mongo' for curate-fundamentals") + Some("error: cannot combine '--from-mongo' with '--qm-financials', '--qm-financials-old', or '--qm-filings'") ); assert_eq!(lines_mongo.next(), Some("Usage:")); assert!( @@ -690,7 +690,7 @@ fn cli_parse_time_config_errors_fail_closed_before_touching_out() { ), ( &["--fiscal-period", "quarterly", "--mongo-uri", "mongodb://localhost:27017/stock"], - "error: unknown flag '--mongo-uri' for curate-fundamentals", + "error: MongoDB streaming flags require '--from-mongo'", ), ( &["--fiscal-period", "quarterly", "--k", "0"], @@ -716,3 +716,97 @@ fn cli_parse_time_config_errors_fail_closed_before_touching_out() { ); } } + +#[test] +fn cli_supports_qm_financials_old_curate_inputs_and_blocks_unsafe_mongo_uri() { + let dir = TempDir::new("old-and-curate-inputs"); + write_restatement_fixture(&dir.0); + + // Create a committed curate-inputs/ + current symlink layout. + let inputs_root = dir.0.join("curate_inputs"); + let gen_dir = inputs_root.join("gen-1"); + std::fs::create_dir_all(&gen_dir).unwrap(); + std::fs::copy( + dir.0.join("provider_mapping.tsv"), + gen_dir.join("provider_mapping.tsv"), + ) + .unwrap(); + std::fs::copy( + dir.0.join("listing_venues.tsv"), + gen_dir.join("listing_venues.tsv"), + ) + .unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(&gen_dir, inputs_root.join("current")).unwrap(); + + // Run with --qm-financials-old (empty BSON) + --curate-inputs. + let old_bson = dir.0.join("qmFinancials-old.bson"); + std::fs::write(&old_bson, b"").unwrap(); + let out_dir = dir.0.join("out_curate_inputs"); + let res = cli() + .current_dir(&dir.0) + .args([ + "--qm-financials", + "qmFinancials.bson", + "--qm-financials-old", + "qmFinancials-old.bson", + "--qm-filings", + "qmFilings.bson", + "--curate-inputs", + "curate_inputs", + "--out", + "out_curate_inputs", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--quarterly-tokens", + "Q1,Q2,Q3,Q4", + ]) + .output() + .expect("run curate-fundamentals with --qm-financials-old and --curate-inputs"); + assert!( + res.status.success(), + "stderr: {}", + String::from_utf8_lossy(&res.stderr) + ); + assert!(out_dir.join("fundamentals_pit").is_dir()); + + // Fail-closed mongo_safety check on trading_admin URI: redacts password and creates no --out. + let out_unsafe = dir.0.join("out_unsafe_mongo"); + let secret = "T212_ADMIN_SECRET_PW"; + let unsafe_uri = + format!("mongodb://trading_admin:{secret}@localhost:27017/stock?authSource=admin"); + let res_unsafe = cli() + .current_dir(&dir.0) + .args([ + "--from-mongo", + "--mongo-uri", + &unsafe_uri, + "--with-qm-financials-old", + "--curate-inputs", + "curate_inputs", + "--out", + "out_unsafe_mongo", + "--currency-field", + "currency", + "--filings-form-type-field", + "formType", + "--k", + "4", + "--fiscal-period", + "quarterly", + ]) + .output() + .expect("run curate-fundamentals --from-mongo with trading_admin"); + assert_eq!(res_unsafe.status.code(), Some(1)); + assert!(res_unsafe.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&res_unsafe.stderr); + assert!( + !stderr.contains(secret), + "secret leaked in stderr: {stderr}" + ); + assert!(!out_unsafe.exists(), "unsafe URI must not create --out"); +} diff --git a/tools/curate-etl/tests/curate_posts.rs b/tools/curate-etl/tests/curate_posts.rs index 0f2f2614..c75d85d6 100644 --- a/tools/curate-etl/tests/curate_posts.rs +++ b/tools/curate-etl/tests/curate_posts.rs @@ -221,8 +221,12 @@ fn cli_publishes_runner_equivalent_posts_and_copublishes_with_curate_events() { fn cli_reports_usage_for_invalid_posts_flags() { for (args, error) in [ ( - &["--from-mongo"][..], - "unknown flag '--from-mongo' for curate-posts", + &["--from-mongo", "--ceo-posts", "p.bson"][..], + "cannot combine '--from-mongo' with '--ceo-posts'", + ), + ( + &["--mongo-uri", "mongodb://u:s3cr3t@localhost:27017/stock"][..], + "MongoDB streaming flags require '--from-mongo'", ), ( &["--timestamp-unit", "--out=x"][..],