diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index b211e43d..09c40ff5 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1701,7 +1701,22 @@ curate-etl curate-bars-1m \ - **Global sort & deduplication with bounded non-FX memory:** Calls `curate_and_write_fx_1m_from_bson` once over the entire input stream so `ts` sorting and deduplication (bitwise-identical OHLC collapse vs. conflicting-group drop) are global across all BSON stream chunks, then calls `IlpShardedWriter::finish()` once after clean EOF. Because `Fx1mAccumulator::push` counts wrong-code rows and returns before appending, peak memory is bounded by accepted `CAD.FOREX` rows plus `BsonStreamOptions::chunk_capacity_bytes` (growing only for a single document up to `max_doc_bytes`) and bounded per-shard output buffers. - **Single-pair sharding & empty runs:** Every curated row carries `pair = "USDCAD"`, `source = "eod"`, and EODHD's UTC microsecond bar-start `ts` (preserving CAD-per-USD OHLC bits without implying bar-close observability at bar start), routing all rows deterministically to `shard_for_fx_pair("USDCAD", shard_count)` while publishing all other shards as empty files. Empty or wrong-code-only inputs succeed with `rows_written == 0` and publish the full set of empty shard files. -- **Fail-closed publication:** Reuses the shared `run_curate_bars_1m` staging and publication helpers parameterized by table name (`fx_1m`): preflight rejects any pre-existing `fx_1m.shard-.ilp` in `out_dir` regardless of `shard_count` (while allowing `bars_1m.shard-*.ilp` to coexist untouched), writes to exclusively created temp files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any error. CLI wiring, `--from-mongo`, and live QuestDB load remain follow-ups. +- **Fail-closed publication:** Reuses the shared `run_curate_bars_1m` staging and publication helpers parameterized by table name (`fx_1m`): preflight rejects any pre-existing `fx_1m.shard-.ilp` in `out_dir` regardless of `shard_count` (while allowing `bars_1m.shard-*.ilp` to coexist untouched), writes to exclusively created temp files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only final files created by the current run on any error. File-mode CLI wiring is available via `curate-fx-1m` below; `--from-mongo` and live QuestDB load remain follow-ups. + +### `curate-fx-1m` Command (`M2.3o`) + +File-mode CLI command wiring `run_curate_fx_1m` into the `curate-etl` binary: + +```bash +curate-etl curate-fx-1m \ + --eod-intraday eodIntraday1M.bson \ + --out ./out \ + --shards 4 +``` + +- **Required flags:** `--eod-intraday ` (local concatenated raw BSON `eodIntraday1M` dump), `--out `, and `--shards ` (positive base-10 integer, no default). +- **Outputs & fail-closed publication:** writes `/fx_1m.shard-.ilp` (`00`..``) and prints the `format_curate_fx_1m_report` summary to stdout. Inherits the runner's fail-closed preflight and staging/rollback guarantees (refuses to overwrite existing `fx_1m.shard-*.ilp` files and leaves no partial shard or staging files on error). +- **File mode only:** MongoDB streaming flags (such as `--from-mongo` and `--mongo-uri`) are rejected; `--from-mongo` streaming and live QuestDB ingestion remain follow-ups. ## `run_curate_qm_bars_1m` Bounded-Memory File-to-File Runner (`M2.3m`) diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index c2316640..625fdea9 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -47,6 +47,7 @@ use crate::run_curate_bars_1m::{CurateBars1mArgs, DEFAULT_BARS_1M_MAPPING_SOURCE use crate::run_curate_corporate_actions::CurateCorporateActionsArgs; use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE}; use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL}; +use crate::run_curate_fx_1m::CurateFx1mArgs; use crate::run_curate_shorts::{CurateShortsArgs, DEFAULT_MAPPING_SOURCE}; use crate::run_mongo::{ CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs, @@ -72,6 +73,7 @@ pub enum CliAction { CurateEvents(CurateEventsArgs), CurateEventsMongo(CurateEventsMongoArgs), CurateBars1m(CurateBars1mArgs), + CurateFx1m(CurateFx1mArgs), BenchSplit(usize), BenchAdj(usize), BenchCorporateActions(usize), @@ -135,6 +137,8 @@ pub fn format_usage(name: &str, version: &str) -> String { 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-fx-1m --eod-intraday --out --shards \n\ + Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-.ilp\n\ {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ {name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\ {name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\ @@ -184,6 +188,7 @@ pub fn format_usage_stderr(name: &str) -> String { {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-fx-1m --eod-intraday --out --shards \n\ {name} bench-split [rows]\n\ {name} bench-adj [events]\n\ {name} bench-corporate-actions [events]\n\ @@ -1584,6 +1589,106 @@ fn parse_curate_bars_1m_args(args: &[&str]) -> Result { })) } +fn parse_curate_fx_1m_args(args: &[&str]) -> Result { + 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" + )); + } + + 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)" + )); + } + + 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) + }; + + 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(()) + }; + + match flag { + "--eod-intraday" => set_path(&mut intraday_path, "--eod-intraday", value)?, + "--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); + } + other => return Err(format!("unknown flag '{other}' for curate-fx-1m")), + } + } + + 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())?; + let shard_count = + shard_count.ok_or_else(|| "missing required flag '--shards'".to_string())?; + + Ok(CliAction::CurateFx1m(CurateFx1mArgs { + intraday_path, + out_dir, + shard_count, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + })) +} + /// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`]. pub fn parse_args(args: &[String]) -> Result { let slices: Vec<&str> = args.iter().map(String::as_str).collect(); @@ -1600,6 +1705,7 @@ 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-fx-1m", rest @ ..] => parse_curate_fx_1m_args(rest), ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), ["bench-split", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)), @@ -3957,4 +4063,239 @@ mod tests { ); } } + + #[test] + fn parse_curate_fx_1m_valid_space_and_equals_forms() { + let expected = CliAction::CurateFx1m(CurateFx1mArgs { + intraday_path: PathBuf::from("A"), + out_dir: PathBuf::from("B"), + shard_count: 4, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }); + + let parsed_space = parse_args(&to_args(&[ + "curate-fx-1m", + "--eod-intraday", + "A", + "--out", + "B", + "--shards", + "4", + ])) + .expect("valid curate-fx-1m args in space form"); + assert_eq!(parsed_space, expected); + + let parsed_eq = parse_args(&to_args(&[ + "curate-fx-1m", + "--eod-intraday=A", + "--out=B", + "--shards=4", + ])) + .expect("valid curate-fx-1m args in equals form"); + assert_eq!(parsed_eq, expected); + } + + #[test] + fn curate_fx_1m_usage_mentions_command_and_all_flags() { + let expected_flags = ["--eod-intraday", "--out", "--shards"]; + let usage = format_usage("curate-etl", "0.1.0"); + let usage_stderr = format_usage_stderr("curate-etl"); + let usage_line = usage + .lines() + .find(|line| line.trim_start().starts_with("curate-etl curate-fx-1m ")) + .expect("format_usage missing curate-fx-1m command line"); + let stderr_line = usage_stderr + .lines() + .find(|line| line.trim_start().starts_with("curate-etl curate-fx-1m ")) + .expect("format_usage_stderr missing curate-fx-1m command line"); + for flag in expected_flags { + assert!( + usage_line.contains(flag), + "format_usage curate-fx-1m line missing {flag}: {usage_line}" + ); + assert!( + stderr_line.contains(flag), + "format_usage_stderr curate-fx-1m line missing {flag}: {stderr_line}" + ); + } + } + + #[test] + fn parse_curate_fx_1m_rejects_missing_required_flags() { + let required: [(&str, &str); 3] = [ + ("--eod-intraday", "intraday.bson"), + ("--out", "out_dir"), + ("--shards", "4"), + ]; + + for omit in 0..required.len() { + let mut argv: Vec<&str> = vec!["curate-fx-1m"]; + for (idx, &(flag, val)) in required.iter().enumerate() { + if idx != omit { + argv.push(flag); + argv.push(val); + } + } + let err = parse_args(&to_args(&argv)).unwrap_err(); + let missing_flag = required[omit].0; + assert!( + err.contains(&format!("missing required flag '{missing_flag}'")), + "expected missing required flag '{missing_flag}', got: {err}" + ); + } + } + + #[test] + fn parse_curate_fx_1m_rejects_duplicates_empty_missing_value_unknown_and_positional() { + let base = [ + "curate-fx-1m", + "--eod-intraday", + "i.bson", + "--out", + "o", + "--shards", + "4", + ]; + + // Duplicate flags (path and numeric). + for (flag, extra_val) in [ + ("--eod-intraday", "i2.bson"), + ("--out", "o2"), + ("--shards", "2"), + ] { + let mut argv = base.to_vec(); + argv.push(flag); + argv.push(extra_val); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains(&format!("duplicate flag '{flag}'")), + "expected duplicate error for {flag}, got: {err}" + ); + } + + // Empty values via --flag=. + for flag in ["--eod-intraday", "--out", "--shards"] { + let empty_token = format!("{flag}="); + let err = parse_args(&to_args(&["curate-fx-1m", &empty_token])).unwrap_err(); + assert!( + err.contains(&format!("empty value for flag '{flag}'")), + "expected empty value error for {flag}, got: {err}" + ); + } + + // Flag at end of input or followed by another flag. + let err = parse_args(&to_args(&["curate-fx-1m", "--eod-intraday"])).unwrap_err(); + assert!( + err.contains("missing value for flag '--eod-intraday'"), + "{err}" + ); + let err = parse_args(&to_args(&["curate-fx-1m", "--shards", "--out", "o"])).unwrap_err(); + assert!(err.contains("missing value for flag '--shards'"), "{err}"); + + // Unknown flag. + let mut unknown = base.to_vec(); + unknown.push("--nope"); + unknown.push("1"); + let err = parse_args(&to_args(&unknown)).unwrap_err(); + assert!( + err.contains("unknown flag '--nope' for curate-fx-1m"), + "{err}" + ); + + // Bars-only flags must be rejected as unknown flags. + for (flag, val) in [ + ("--qm-splits", "splits.bson"), + ("--provider-mapping", "mapping.tsv"), + ("--known-at-micros", "1735689600000000"), + ("--mapping-source", "eod"), + ] { + let mut argv = base.to_vec(); + argv.push(flag); + argv.push(val); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains(&format!("unknown flag '{flag}' for curate-fx-1m")), + "expected unknown flag error for {flag}, got: {err}" + ); + } + + // Positional argument. + let err = parse_args(&to_args(&["curate-fx-1m", "positional"])).unwrap_err(); + assert!( + err.contains("unexpected positional argument 'positional' for curate-fx-1m"), + "{err}" + ); + } + + #[test] + fn parse_curate_fx_1m_rejects_invalid_shards() { + let base_without_shards = [ + "curate-fx-1m", + "--eod-intraday", + "i.bson", + "--out", + "o", + ]; + + for bad_shards in [ + "0", + "-1", + "+1", + "1.5", + "abc", + "999999999999999999999999999999999999999", + ] { + let mut argv = base_without_shards.to_vec(); + argv.push("--shards"); + argv.push(bad_shards); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains("invalid --shards"), + "expected invalid --shards for '{bad_shards}', got: {err}" + ); + } + } + + #[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", + ]; + + 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"); + + // 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}" + ); + + // 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}" + ); + } + } } diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 27f1151b..4f08f450 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -29,6 +29,7 @@ use curate_etl::run_curate_corporate_actions::{ }; use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events}; 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_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, @@ -208,6 +209,16 @@ fn main() -> ExitCode { ExitCode::FAILURE } }, + Ok(CliAction::CurateFx1m(curate_args)) => match run_curate_fx_1m(&curate_args) { + Ok(report) => { + println!("{}", format_curate_fx_1m_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + }, Ok(CliAction::BenchSplit(rows)) => { let report = match run_split_benchmark(rows) { Ok(report) => report,