T-207: M2.2t — tools/curate-etl: curate-macro CLI command (file mode) wiring the existing run_curate_macro into cli.rs + main.rs with parser tests and an end-to-end test (no new crates, no bench changes, no live Mongo)
This commit is contained in:
parent
436616b343
commit
66a0f99157
4 changed files with 708 additions and 2 deletions
|
|
@ -1833,7 +1833,7 @@ curate-etl send-ilp \
|
|||
- **Governance & provenance:** Quant Research owns the coarse regime-use policy; the caller owns the explicit `(country_iso, indicator)` lag mapping. TradingEconomics indicator names are **not** hardcoded because live `teIndicators` / `teData` names are unverified in this crate. Because `teData` carries final-revised `{d, v}` values without verified release dates or historical vintages, availability starts strictly at `known_at` (`00:00:00 UTC` of `period_date + lag_days`), tagged `known_at_source = "publication_lag_estimate"` (`MACRO_KNOWN_AT_SOURCE`).
|
||||
- **Locked lag classes (`MacroLagClass`):** `PolicyRate` (`+1d`, `POLICY_RATE_LAG_DAYS`), `MonthlyRelease` (`+35d`, `MONTHLY_RELEASE_LAG_DAYS`), `Gdp65` (`+65d`, `GDP65_LAG_DAYS`), and `Gdp90` (`+90d`, `GDP90_LAG_DAYS`).
|
||||
- **Fail-closed filtering, deduplication & overflow:** Unmapped `(country_iso, indicator)` pairs are skipped first (`skipped_unmapped_indicator`) and never given a default lag; non-finite values on mapped pairs are skipped (`skipped_non_finite_value`). Surviving rows are sorted by `(country_iso, indicator, period_date)`; bitwise-identical (`f64::to_bits()`) duplicates collapse (`skipped_duplicate`), while conflicting values (including `+0.0` vs. `-0.0`) return `MacroError::ConflictingDuplicate`. Checked `i32` date addition and `i64` microsecond scaling return `MacroError::KnownAtOverflow` rather than panicking. `MacroBuildStats` satisfies `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`.
|
||||
- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow<K>>`) atomically to `<out_dir>/macro/part.parquet` (6-column Zstd contract schema); deferred: CLI command (`curate-macro`), `macroAsOf` DuckDB reader, and live MongoDB access.
|
||||
- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow<K>>`) atomically to `<out_dir>/macro/part.parquet` (6-column Zstd contract schema); deferred: `macroAsOf` DuckDB reader and live MongoDB access.
|
||||
|
||||
## Zero-Copy `teData` BSON Decoder (`M2.2p`)
|
||||
|
||||
|
|
@ -1856,4 +1856,19 @@ curate-etl send-ilp \
|
|||
|
||||
- **Caller-owned series-map TSV (`load_macro_series_map_tsv`):** Requires the exact line-1 header `te_symbol<TAB>country<TAB>category<TAB>country_iso<TAB>indicator<TAB>lag_class` (LF or CRLF line endings). Each data row must have 6 nonempty tab-separated columns with verbatim `(te_symbol, country, category)` keys (no trimming, no case folding), unique key triples (duplicates fail closed even when targets match), and an exact `lag_class` token in `policy_rate`, `monthly_release`, `gdp65`, or `gdp90`. There is no hardcoded default mapping or default lag class.
|
||||
- **Buffering, decode & fail-closed behavior:** Validates the full series map first, buffers the concatenated `teData` BSON input in memory (memory grows with dump size), counts per-document/per-point semantic rejects in `BsonTeDataDecodeStats`, and fails closed on the first structural BSON error (`TruncatedDocument`, `CorruptDocumentLength`, `CorruptBson`, `CorruptPointBson`) before publishing. Any I/O, TSV, structural BSON, or curation error (such as `ConflictingLagClass`) returns a single-line `RunCurateMacroError` and leaves `out_dir` and any pre-existing `<out_dir>/macro/part.parquet` byte-identical. Empty or all-unmapped inputs preserve `curate_and_write_macro`'s zero-row no-op.
|
||||
- **Governance, provenance & reproducibility:** Quant Research owns the coarse regime-use policy and the caller owns the mapping. Because `teData` carries final-revised `{d, v}` values without verified release timestamps or historical vintages, observations become available strictly at the estimated `known_at` (`00:00:00 UTC` of `period_date + lag_days`, `known_at_source = "publication_lag_estimate"`) for coarse regime use. For reproducible checks, pin the `teData` BSON dump and series-map TSV together against the pure stage and fixed expected rows. Real QA `teData` provider-label verification remains a manual host check, and `curate-macro` CLI / `--from-mongo` wiring are separate follow-ups.
|
||||
- **Governance, provenance & reproducibility:** Quant Research owns the coarse regime-use policy and the caller owns the mapping. Because `teData` carries final-revised `{d, v}` values without verified release timestamps or historical vintages, observations become available strictly at the estimated `known_at` (`00:00:00 UTC` of `period_date + lag_days`, `known_at_source = "publication_lag_estimate"`) for coarse regime use. For reproducible checks, pin the `teData` BSON dump and series-map TSV together against the pure stage and fixed expected rows. Real QA `teData` provider-label verification remains a manual host check, and `--from-mongo` streaming remains a separate follow-up.
|
||||
|
||||
## `curate-macro` Command (`M2.2t`)
|
||||
|
||||
File-mode CLI command wiring `run_curate_macro` into the `curate-etl` binary to curate a local `teData` raw BSON dump and caller-supplied series-map TSV into `<out>/macro/part.parquet`:
|
||||
|
||||
```bash
|
||||
curate-etl curate-macro \
|
||||
--te-data ./teData.bson \
|
||||
--series-map ./series-map.tsv \
|
||||
--out ./out
|
||||
```
|
||||
|
||||
- **Required flags (no defaults):** `--te-data <teData.bson>`, `--series-map <series-map.tsv>`, and `--out <dir>` are all required (accepting both `--flag value` and `--flag=value`). Duplicate flags, empty values, positional arguments, and unknown flags (including `--from-mongo` and `--mongo-uri*`) are rejected at parse time before touching `--out`.
|
||||
- **Series-map TSV & lag tokens:** `--series-map` must start with the exact 6-column header `te_symbol<TAB>country<TAB>category<TAB>country_iso<TAB>indicator<TAB>lag_class` with verbatim keys and `lag_class` in `{policy_rate, monthly_release, gdp65, gdp90}`; no country, indicator, or lag-class defaults are built in.
|
||||
- **Output, fail-closed & zero-row behavior:** Prints `format_curate_macro_report` to stdout on exit `0` and atomically publishes `<out>/macro/part.parquet` (empty or all-unmapped inputs succeed as a zero-row no-op without writing). Runtime errors (missing input, invalid TSV, structural BSON corruption, or curation error) print a single-line `error: ...` to stderr and exit non-zero without creating `--out` or modifying any pre-existing `<out>/macro/part.parquet`; CLI parse errors print `error: ...` followed by `Usage:` to stderr and exit non-zero.
|
||||
|
|
|
|||
|
|
@ -66,6 +66,7 @@ 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,
|
||||
};
|
||||
|
|
@ -97,6 +98,7 @@ pub enum CliAction {
|
|||
CurateFx1m(CurateFx1mArgs),
|
||||
CuratePosts(CuratePostsArgs),
|
||||
CurateFundamentals(CurateFundamentalsArgs),
|
||||
CurateMacro(CurateMacroArgs),
|
||||
SendIlp(SendIlpArgs),
|
||||
BenchSplit(usize),
|
||||
BenchAdj(usize),
|
||||
|
|
@ -167,6 +169,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
Curate ceoPosts from BSON + provider_mapping TSV into <out>/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 <path> --qm-filings <path> --provider-mapping <path> --listing-venues <path> --out <dir> --currency-field <name> --filings-form-type-field <name> --k <N> (--fiscal-period <quarterly|annual> | [--quarterly-tokens <a,b,..>] [--annual-tokens <a,b,..>]) [--financials-key-field <name>] [--period-end-field <name>] [--report-date-field <name>] [--report-period-field <name>] [--revenue-field <path>] [--net-income-field <path>] [--operating-cash-flow-field <path>] [--total-assets-field <path>] [--total-equity-field <path>] [--shares-outstanding-field <path>] [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--mapping-source <name>]\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-macro --te-data <teData.bson> --series-map <series-map.tsv> --out <dir>\n\
|
||||
Curate lagged macro regime series from teData BSON + caller-supplied 6-column series-map TSV into macro/part.parquet (file mode only; no default mappings or lag classes)\n\
|
||||
{name} send-ilp --dir <dir> --prefix <bars_1m|bars_1m_qm|fx_1m> --addr <host:port>\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\
|
||||
|
|
@ -221,6 +225,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} curate-fx-1m --eod-intraday <path> --out <dir> --shards <N>\n\
|
||||
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
|
||||
{name} curate-fundamentals --qm-financials <path> --qm-filings <path> --provider-mapping <path> --listing-venues <path> --out <dir> --currency-field <name> --filings-form-type-field <name> --k <N> (--fiscal-period <quarterly|annual> | [--quarterly-tokens <a,b,..>] [--annual-tokens <a,b,..>]) [--financials-key-field <name>] [--period-end-field <name>] [--report-date-field <name>] [--report-period-field <name>] [--revenue-field <path>] [--net-income-field <path>] [--operating-cash-flow-field <path>] [--total-assets-field <path>] [--total-equity-field <path>] [--shares-outstanding-field <path>] [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--mapping-source <name>]\n\
|
||||
{name} curate-macro --te-data <teData.bson> --series-map <series-map.tsv> --out <dir>\n\
|
||||
{name} send-ilp --dir <dir> --prefix <bars_1m|bars_1m_qm|fx_1m> --addr <host:port>\n\
|
||||
{name} bench-split [rows]\n\
|
||||
{name} bench-adj [events]\n\
|
||||
|
|
@ -1626,6 +1631,63 @@ fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result<CliAction, Stri
|
|||
Ok(CliAction::CurateFundamentals(parsed))
|
||||
}
|
||||
|
||||
fn parse_curate_macro_args(args: &[&str]) -> Result<CliAction, String> {
|
||||
parse_curate_macro_args_inner(args).map_err(|e| sanitize_single_line(&e))
|
||||
}
|
||||
|
||||
fn parse_curate_macro_args_inner(args: &[&str]) -> Result<CliAction, String> {
|
||||
let mut te_data: Option<PathBuf> = None;
|
||||
let mut series_map: Option<PathBuf> = None;
|
||||
let mut out_dir: Option<PathBuf> = 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"
|
||||
));
|
||||
}
|
||||
|
||||
let flag_name = token.split_once('=').map_or(token, |(flag, _)| flag);
|
||||
if !matches!(flag_name, "--te-data" | "--series-map" | "--out") {
|
||||
return Err(format!("unknown flag '{flag_name}' for curate-macro"));
|
||||
}
|
||||
|
||||
let (flag, value) = if let Some((flag, v)) = token.split_once('=') {
|
||||
i += 1;
|
||||
(flag, 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)
|
||||
};
|
||||
|
||||
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")),
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}))
|
||||
}
|
||||
|
||||
fn parse_curate_events_args(args: &[&str]) -> Result<CliAction, String> {
|
||||
let mut mongo = MongoFlagState::default();
|
||||
let mut qm_filings: Option<PathBuf> = None;
|
||||
|
|
@ -2247,6 +2309,7 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["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::<usize>() {
|
||||
|
|
@ -5972,4 +6035,172 @@ mod tests {
|
|||
.expect("space dir with equals and IPv6 equals addr");
|
||||
assert_eq!(parsed_space, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_macro_parsing_validation_and_usage() {
|
||||
let usage_sig = "curate-macro --te-data <teData.bson> --series-map <series-map.tsv> --out <dir>";
|
||||
let usage = format_usage("curate-etl", "0.1.0");
|
||||
assert!(usage.contains(usage_sig), "{usage}");
|
||||
let usage_stderr = format_usage_stderr("curate-etl");
|
||||
assert!(usage_stderr.contains(usage_sig), "{usage_stderr}");
|
||||
|
||||
// Happy path: separated form
|
||||
let parsed = parse_args(&to_args(&[
|
||||
"curate-macro",
|
||||
"--te-data",
|
||||
"/tmp/teData.bson",
|
||||
"--series-map",
|
||||
"/tmp/series-map.tsv",
|
||||
"--out",
|
||||
"/tmp/curated",
|
||||
]))
|
||||
.expect("separated curate-macro args");
|
||||
assert_eq!(
|
||||
parsed,
|
||||
CliAction::CurateMacro(CurateMacroArgs {
|
||||
te_data: PathBuf::from("/tmp/teData.bson"),
|
||||
series_map: PathBuf::from("/tmp/series-map.tsv"),
|
||||
out_dir: PathBuf::from("/tmp/curated"),
|
||||
})
|
||||
);
|
||||
|
||||
// Happy path: `--flag=value` (including `=` inside path and `--`-prefixed literal dir)
|
||||
let parsed_eq = parse_args(&to_args(&[
|
||||
"curate-macro",
|
||||
"--te-data=/tmp/year=2025/teData.bson",
|
||||
"--series-map=/tmp/v=1/series-map.tsv",
|
||||
"--out=--literal-dir",
|
||||
]))
|
||||
.expect("equals curate-macro args");
|
||||
assert_eq!(
|
||||
parsed_eq,
|
||||
CliAction::CurateMacro(CurateMacroArgs {
|
||||
te_data: PathBuf::from("/tmp/year=2025/teData.bson"),
|
||||
series_map: PathBuf::from("/tmp/v=1/series-map.tsv"),
|
||||
out_dir: PathBuf::from("--literal-dir"),
|
||||
})
|
||||
);
|
||||
|
||||
// Happy path: reordered mixed flags
|
||||
let parsed_reordered = parse_args(&to_args(&[
|
||||
"curate-macro",
|
||||
"--out",
|
||||
"out_dir",
|
||||
"--series-map=map.tsv",
|
||||
"--te-data",
|
||||
"te.bson",
|
||||
]))
|
||||
.expect("reordered curate-macro args");
|
||||
assert_eq!(
|
||||
parsed_reordered,
|
||||
CliAction::CurateMacro(CurateMacroArgs {
|
||||
te_data: PathBuf::from("te.bson"),
|
||||
series_map: PathBuf::from("map.tsv"),
|
||||
out_dir: PathBuf::from("out_dir"),
|
||||
})
|
||||
);
|
||||
|
||||
// Bare `curate-macro` fails with missing required flag
|
||||
let err = parse_args(&to_args(&["curate-macro"])).unwrap_err();
|
||||
assert_eq!(err, "missing required flag '--te-data'");
|
||||
|
||||
// Omitting each required flag
|
||||
let required: [(&str, &str); 3] = [
|
||||
("--te-data", "teData.bson"),
|
||||
("--series-map", "series-map.tsv"),
|
||||
("--out", "out"),
|
||||
];
|
||||
for omit in 0..required.len() {
|
||||
let mut argv = vec!["curate-macro"];
|
||||
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();
|
||||
assert_eq!(err, format!("missing required flag '{}'", required[omit].0));
|
||||
}
|
||||
|
||||
// Duplicate flags
|
||||
let base = [
|
||||
"curate-macro",
|
||||
"--te-data",
|
||||
"teData.bson",
|
||||
"--series-map",
|
||||
"series-map.tsv",
|
||||
"--out",
|
||||
"out",
|
||||
];
|
||||
for (flag, extra) in [
|
||||
("--te-data", "--te-data=other.bson"),
|
||||
("--series-map", "--series-map=other.tsv"),
|
||||
("--out", "--out=other_out"),
|
||||
] {
|
||||
let mut argv = base.to_vec();
|
||||
argv.push(extra);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert_eq!(err, format!("duplicate flag '{flag}'"));
|
||||
}
|
||||
|
||||
// Empty values in both `--flag ""` and `--flag=` forms
|
||||
for flag in ["--te-data", "--series-map", "--out"] {
|
||||
let err_space = parse_args(&to_args(&["curate-macro", flag, ""])).unwrap_err();
|
||||
assert_eq!(err_space, format!("empty value for flag '{flag}'"));
|
||||
|
||||
let eq_token = format!("{flag}=");
|
||||
let err_eq = parse_args(&to_args(&["curate-macro", &eq_token])).unwrap_err();
|
||||
assert_eq!(err_eq, format!("empty value for flag '{flag}'"));
|
||||
}
|
||||
|
||||
// Missing values at EOF and before another `--flag`
|
||||
for flag in ["--te-data", "--series-map", "--out"] {
|
||||
let err_eof = parse_args(&to_args(&["curate-macro", flag])).unwrap_err();
|
||||
assert_eq!(err_eof, format!("missing value for flag '{flag}'"));
|
||||
}
|
||||
let err_before_flag = parse_args(&to_args(&[
|
||||
"curate-macro",
|
||||
"--te-data",
|
||||
"--out",
|
||||
"out",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert_eq!(err_before_flag, "missing value for flag '--te-data'");
|
||||
|
||||
// Unknown flags including --from-mongo and --mongo-uri* (checked before consuming value)
|
||||
for (argv, expected_flag) in [
|
||||
(&["curate-macro", "--bogus", "1"][..], "--bogus"),
|
||||
(&["curate-macro", "--from-mongo"][..], "--from-mongo"),
|
||||
(&["curate-macro", "--from-mongo=true"][..], "--from-mongo"),
|
||||
(
|
||||
&["curate-macro", "--from-mongo", "--out", "o"][..],
|
||||
"--from-mongo",
|
||||
),
|
||||
(
|
||||
&["curate-macro", "--mongo-uri", "mongodb://host"][..],
|
||||
"--mongo-uri",
|
||||
),
|
||||
(
|
||||
&["curate-macro", "--mongo-uri-env=MONGODB_READ_URI"][..],
|
||||
"--mongo-uri-env",
|
||||
),
|
||||
] {
|
||||
let err = parse_args(&to_args(argv)).unwrap_err();
|
||||
assert_eq!(err, format!("unknown flag '{expected_flag}' for curate-macro"));
|
||||
}
|
||||
|
||||
// Positional arguments rejected (including single-dash token)
|
||||
for pos in ["extra", "-x"] {
|
||||
let err = parse_args(&to_args(&["curate-macro", pos])).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
format!("unexpected positional argument '{pos}' for curate-macro")
|
||||
);
|
||||
}
|
||||
|
||||
// Multiline tokens are sanitized to a single diagnostic line
|
||||
let err = parse_args(&to_args(&["curate-macro", "bad\nline\rarg"])).unwrap_err();
|
||||
assert!(!err.contains('\n') && !err.contains('\r'), "{err:?}");
|
||||
assert!(err.contains("bad\\nline\\rarg"), "{err:?}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ 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_shorts::{format_curate_shorts_report, run_curate_shorts};
|
||||
use curate_etl::run_mongo::{
|
||||
|
|
@ -246,6 +247,16 @@ fn main() -> ExitCode {
|
|||
}
|
||||
}
|
||||
}
|
||||
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::SendIlp(send_args)) => match run_send_ilp(&send_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_ilp_send_report(&report));
|
||||
|
|
|
|||
449
tools/curate-etl/tests/curate_macro.rs
Normal file
449
tools/curate-etl/tests/curate_macro.rs
Normal file
|
|
@ -0,0 +1,449 @@
|
|||
//! End-to-end tests for the file-mode `curate-macro` CLI.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf};
|
||||
use bson::DateTime;
|
||||
use curate_etl::macro_series::{
|
||||
MACRO_KNOWN_AT_SOURCE, MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS,
|
||||
};
|
||||
use curate_etl::run_curate_macro::{
|
||||
format_curate_macro_report, run_curate_macro, CurateMacroArgs, MACRO_SERIES_MAP_HEADER,
|
||||
};
|
||||
use curate_etl::split::ymd_to_epoch_days;
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
use parquet::record::{Field, Row};
|
||||
|
||||
const MICROS_PER_DAY: i64 = 86_400_000_000;
|
||||
|
||||
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(label: &str) -> Self {
|
||||
let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"curate-macro-cli-{label}-{}-{seq}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create isolated test directory");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn cli() -> Command {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_curate-etl"));
|
||||
command.arg("curate-macro");
|
||||
command
|
||||
}
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn make_point_doc(d: &str, v: f64) -> RawDocumentBuf {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("d"), d);
|
||||
pt.append(cstr!("v"), v);
|
||||
pt
|
||||
}
|
||||
|
||||
fn make_te_data_doc(
|
||||
te_symbol: &str,
|
||||
country: &str,
|
||||
category: &str,
|
||||
data_points: &[(&str, f64)],
|
||||
forecast_points: &[(&str, f64)],
|
||||
) -> RawDocumentBuf {
|
||||
let mut data_arr = RawArrayBuf::new();
|
||||
for &(d, v) in data_points {
|
||||
data_arr.push(make_point_doc(d, v));
|
||||
}
|
||||
|
||||
let mut forecast_arr = RawArrayBuf::new();
|
||||
for &(d, v) in forecast_points {
|
||||
forecast_arr.push(make_point_doc(d, v));
|
||||
}
|
||||
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("teSymbol"), te_symbol);
|
||||
doc.append(cstr!("name"), format!("{country} {category}"));
|
||||
doc.append(cstr!("unit"), "percent");
|
||||
doc.append(cstr!("source"), "TradingEconomics");
|
||||
doc.append(cstr!("frequency"), "Monthly");
|
||||
doc.append(cstr!("country"), country);
|
||||
doc.append(cstr!("category"), category);
|
||||
doc.append(cstr!("data"), data_arr);
|
||||
doc.append(cstr!("forecast"), forecast_arr);
|
||||
doc.append(
|
||||
cstr!("lastUpdated"),
|
||||
DateTime::from_millis(1_710_000_000_000),
|
||||
);
|
||||
doc.append(cstr!("createdAt"), DateTime::from_millis(1_700_000_000_000));
|
||||
doc
|
||||
}
|
||||
|
||||
fn write_macro_fixture(dir: &Path) -> (PathBuf, PathBuf) {
|
||||
let te_data_path = dir.join("teData.bson");
|
||||
let series_map_path = dir.join("series-map.tsv");
|
||||
|
||||
let map_tsv = format!(
|
||||
"{MACRO_SERIES_MAP_HEADER}\n\
|
||||
USIR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\
|
||||
CACPI\tCanada\tInflation Rate\tCA\tcpi_yoy\tmonthly_release\n"
|
||||
);
|
||||
fs::write(&series_map_path, map_tsv).unwrap();
|
||||
|
||||
// Fixture covers:
|
||||
// - US policy_rate (+1d lag) with 2 valid points + 1 invalid date + forecast sentinel points
|
||||
// - CA monthly_release (+35d lag) with 2 valid points + forecast sentinel points
|
||||
// - One unmapped series whose points must be dropped into `dropped_unmapped_series`
|
||||
let docs = [
|
||||
make_te_data_doc(
|
||||
"USIR",
|
||||
"United States",
|
||||
"Interest Rate",
|
||||
&[
|
||||
("2024-03-20", 5.5),
|
||||
("not-a-date", 99.0),
|
||||
("2024-01-31", 5.25),
|
||||
],
|
||||
&[("2025-12-31", 999.25)],
|
||||
),
|
||||
make_te_data_doc(
|
||||
"CACPI",
|
||||
"Canada",
|
||||
"Inflation Rate",
|
||||
&[("2024-02-29", 2.8), ("2024-01-31", 2.9)],
|
||||
&[("2025-06-30", 888.5)],
|
||||
),
|
||||
make_te_data_doc(
|
||||
"UNMAPPED",
|
||||
"Germany",
|
||||
"GDP",
|
||||
&[("2024-03-31", 1.2)],
|
||||
&[("2025-03-31", 777.0)],
|
||||
),
|
||||
];
|
||||
|
||||
let mut raw_bson = Vec::new();
|
||||
for doc in &docs {
|
||||
raw_bson.extend_from_slice(doc.as_bytes());
|
||||
}
|
||||
fs::write(&te_data_path, raw_bson).unwrap();
|
||||
|
||||
(te_data_path, series_map_path)
|
||||
}
|
||||
|
||||
fn col<'a>(row: &'a Row, name: &str) -> &'a Field {
|
||||
row.get_column_iter()
|
||||
.find(|(col_name, _)| col_name.as_str() == name)
|
||||
.unwrap_or_else(|| panic!("missing Parquet column '{name}'"))
|
||||
.1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage() {
|
||||
let dir = TempDir::new("e2e");
|
||||
let (te_data_path, series_map_path) = write_macro_fixture(&dir.0);
|
||||
|
||||
let baseline_dir = dir.0.join("baseline");
|
||||
let baseline_args = CurateMacroArgs {
|
||||
te_data: te_data_path,
|
||||
series_map: series_map_path,
|
||||
out_dir: baseline_dir.clone(),
|
||||
};
|
||||
let baseline_report = run_curate_macro(&baseline_args).expect("run library baseline");
|
||||
|
||||
// Verify fixture counts and conservation equations.
|
||||
assert_eq!(baseline_report.series_map_entries, 2);
|
||||
let d = &baseline_report.decode_stats;
|
||||
let c = &baseline_report.curate_stats;
|
||||
let w = &baseline_report.write_stats;
|
||||
assert_eq!(d.docs_in, 3);
|
||||
assert_eq!(d.docs_accepted, 3);
|
||||
assert_eq!(d.docs_rejected_total(), 0);
|
||||
assert_eq!(d.docs_in, d.docs_accepted + d.docs_rejected_total());
|
||||
assert_eq!(d.points_in, 6);
|
||||
assert_eq!(d.points_decoded, 5);
|
||||
assert_eq!(d.rejected_invalid_date, 1);
|
||||
assert_eq!(d.points_in, d.points_decoded + d.rejected_total());
|
||||
assert_eq!(d.points_decoded, c.points_in);
|
||||
assert_eq!(c.dropped_unmapped_series, 1);
|
||||
assert_eq!(c.builder.input, 4);
|
||||
assert_eq!(c.points_in, c.dropped_unmapped_series + c.builder.input);
|
||||
assert_eq!(c.rows_out, 4);
|
||||
assert_eq!(c.rows_out, c.builder.emitted);
|
||||
assert_eq!(c.rows_out, w.rows_written);
|
||||
assert_eq!(c.series_out, 2);
|
||||
assert_eq!(w.files_written, 1);
|
||||
|
||||
let expected_stdout = format!("{}\n", format_curate_macro_report(&baseline_report));
|
||||
let baseline_parquet = fs::read(baseline_dir.join("macro/part.parquet"))
|
||||
.expect("read baseline macro/part.parquet");
|
||||
|
||||
// First CLI run (mixed space and `=` flag forms).
|
||||
let cli_out = dir.0.join("cli_out");
|
||||
let result = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args([
|
||||
"--te-data",
|
||||
"teData.bson",
|
||||
"--series-map=series-map.tsv",
|
||||
"--out",
|
||||
"cli_out",
|
||||
])
|
||||
.output()
|
||||
.expect("run curate-macro");
|
||||
|
||||
assert!(result.status.success(), "{result:?}");
|
||||
assert!(
|
||||
result.stderr.is_empty(),
|
||||
"unexpected stderr: {}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout");
|
||||
assert_eq!(stdout, expected_stdout);
|
||||
|
||||
let cli_parquet_path = cli_out.join("macro/part.parquet");
|
||||
assert!(cli_parquet_path.is_file(), "expected macro/part.parquet");
|
||||
let cli_parquet = fs::read(&cli_parquet_path).expect("read cli macro/part.parquet");
|
||||
assert_eq!(
|
||||
cli_parquet, baseline_parquet,
|
||||
"CLI Parquet output must be byte-identical to library baseline"
|
||||
);
|
||||
|
||||
// Second fresh CLI run must also be byte-identical.
|
||||
let cli_out_2 = dir.0.join("cli_out_2");
|
||||
let result_2 = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args([
|
||||
"--out=cli_out_2",
|
||||
"--series-map",
|
||||
"series-map.tsv",
|
||||
"--te-data=teData.bson",
|
||||
])
|
||||
.output()
|
||||
.expect("run curate-macro second time");
|
||||
assert!(result_2.status.success(), "{result_2:?}");
|
||||
assert!(result_2.stderr.is_empty());
|
||||
assert_eq!(
|
||||
String::from_utf8(result_2.stdout).unwrap(),
|
||||
expected_stdout
|
||||
);
|
||||
let cli_parquet_2 =
|
||||
fs::read(cli_out_2.join("macro/part.parquet")).expect("read second macro/part.parquet");
|
||||
assert_eq!(
|
||||
cli_parquet_2, cli_parquet,
|
||||
"repeat CLI run must publish byte-identical Parquet"
|
||||
);
|
||||
|
||||
// Verify exact 6-column schema, ascending order, PIT lag math, and zero forecast leakage.
|
||||
let reader = SerializedFileReader::new(File::open(&cli_parquet_path).unwrap()).unwrap();
|
||||
let rows: Vec<Row> = reader
|
||||
.get_row_iter(None)
|
||||
.unwrap()
|
||||
.map(Result::unwrap)
|
||||
.collect();
|
||||
assert_eq!(rows.len(), 4);
|
||||
|
||||
let expected_rows: [(&str, &str, i32, i32, f64); 4] = [
|
||||
("CA", "cpi_yoy", day(2024, 1, 31), MONTHLY_RELEASE_LAG_DAYS, 2.9),
|
||||
("CA", "cpi_yoy", day(2024, 2, 29), MONTHLY_RELEASE_LAG_DAYS, 2.8),
|
||||
("US", "policy_rate", day(2024, 1, 31), POLICY_RATE_LAG_DAYS, 5.25),
|
||||
("US", "policy_rate", day(2024, 3, 20), POLICY_RATE_LAG_DAYS, 5.5),
|
||||
];
|
||||
|
||||
for (row, &(country, indicator, period_date, lag_days, value)) in
|
||||
rows.iter().zip(expected_rows.iter())
|
||||
{
|
||||
assert_eq!(row.len(), 6, "expected 6 columns in macro/part.parquet");
|
||||
assert_eq!(col(row, "country_iso"), &Field::Str(country.to_string()));
|
||||
assert_eq!(col(row, "indicator"), &Field::Str(indicator.to_string()));
|
||||
assert_eq!(col(row, "period_date"), &Field::Date(period_date));
|
||||
let expected_known_at = i64::from(period_date + lag_days) * MICROS_PER_DAY;
|
||||
assert_eq!(
|
||||
col(row, "known_at"),
|
||||
&Field::TimestampMicros(expected_known_at)
|
||||
);
|
||||
assert_eq!(
|
||||
col(row, "known_at_source"),
|
||||
&Field::Str(MACRO_KNOWN_AT_SOURCE.to_string())
|
||||
);
|
||||
assert_eq!(col(row, "value"), &Field::Double(value));
|
||||
// Sentinel forecast values (999.25, 888.5, 777.0) must never appear.
|
||||
assert!(value < 100.0, "unexpected forecast sentinel value {value}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_runner_failures_fail_closed_without_creating_or_modifying_output() {
|
||||
let dir = TempDir::new("runner-failures");
|
||||
write_macro_fixture(&dir.0);
|
||||
|
||||
// Pre-seed a sentinel macro/part.parquet to prove failed runs never overwrite existing output.
|
||||
let seeded_out = dir.0.join("seeded_out");
|
||||
let seeded_parquet = seeded_out.join("macro/part.parquet");
|
||||
fs::create_dir_all(seeded_parquet.parent().unwrap()).unwrap();
|
||||
let sentinel_bytes = b"pre-existing-macro-parquet-sentinel".to_vec();
|
||||
fs::write(&seeded_parquet, &sentinel_bytes).unwrap();
|
||||
|
||||
// Case 1: missing --te-data file (fresh --out not created).
|
||||
let missing_te_out = dir.0.join("out_missing_te");
|
||||
let res_missing_te = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args([
|
||||
"--te-data",
|
||||
"does-not-exist.bson",
|
||||
"--series-map",
|
||||
"series-map.tsv",
|
||||
"--out",
|
||||
"out_missing_te",
|
||||
])
|
||||
.output()
|
||||
.expect("run curate-macro missing teData");
|
||||
assert_eq!(res_missing_te.status.code(), Some(1));
|
||||
assert!(res_missing_te.stdout.is_empty());
|
||||
let stderr_te = String::from_utf8(res_missing_te.stderr).unwrap();
|
||||
assert_eq!(stderr_te.lines().count(), 1, "{stderr_te}");
|
||||
assert!(stderr_te.starts_with("error: "), "{stderr_te}");
|
||||
assert!(stderr_te.contains("does-not-exist.bson"), "{stderr_te}");
|
||||
assert!(!stderr_te.contains("Usage:"), "{stderr_te}");
|
||||
assert!(!missing_te_out.exists(), "out dir must not be created");
|
||||
|
||||
// Case 2: missing --series-map file (pre-seeded output preserved).
|
||||
let res_missing_map = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args([
|
||||
"--te-data",
|
||||
"teData.bson",
|
||||
"--series-map",
|
||||
"missing-map.tsv",
|
||||
"--out",
|
||||
"seeded_out",
|
||||
])
|
||||
.output()
|
||||
.expect("run curate-macro missing series-map");
|
||||
assert_eq!(res_missing_map.status.code(), Some(1));
|
||||
assert!(res_missing_map.stdout.is_empty());
|
||||
let stderr_map = String::from_utf8(res_missing_map.stderr).unwrap();
|
||||
assert_eq!(stderr_map.lines().count(), 1, "{stderr_map}");
|
||||
assert!(stderr_map.starts_with("error: "), "{stderr_map}");
|
||||
assert!(stderr_map.contains("missing-map.tsv"), "{stderr_map}");
|
||||
assert!(!stderr_map.contains("Usage:"), "{stderr_map}");
|
||||
assert_eq!(
|
||||
fs::read(&seeded_parquet).unwrap(),
|
||||
sentinel_bytes,
|
||||
"pre-seeded macro/part.parquet must remain byte-identical"
|
||||
);
|
||||
|
||||
// Case 3: truncated/corrupt BSON (pre-seeded output preserved, fresh out not created).
|
||||
let corrupt_path = dir.0.join("corrupt.bson");
|
||||
fs::write(&corrupt_path, [0x10u8, 0x00, 0x00]).unwrap();
|
||||
let corrupt_out = dir.0.join("out_corrupt");
|
||||
let res_corrupt = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args([
|
||||
"--te-data",
|
||||
"corrupt.bson",
|
||||
"--series-map",
|
||||
"series-map.tsv",
|
||||
"--out",
|
||||
"out_corrupt",
|
||||
])
|
||||
.output()
|
||||
.expect("run curate-macro corrupt BSON");
|
||||
assert_eq!(res_corrupt.status.code(), Some(1));
|
||||
assert!(res_corrupt.stdout.is_empty());
|
||||
let stderr_corrupt = String::from_utf8(res_corrupt.stderr).unwrap();
|
||||
assert_eq!(stderr_corrupt.lines().count(), 1, "{stderr_corrupt}");
|
||||
assert!(stderr_corrupt.starts_with("error: "), "{stderr_corrupt}");
|
||||
assert!(!stderr_corrupt.contains("Usage:"), "{stderr_corrupt}");
|
||||
assert!(!corrupt_out.exists(), "out dir must not be created");
|
||||
|
||||
let res_corrupt_seeded = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args([
|
||||
"--te-data",
|
||||
"corrupt.bson",
|
||||
"--series-map",
|
||||
"series-map.tsv",
|
||||
"--out",
|
||||
"seeded_out",
|
||||
])
|
||||
.output()
|
||||
.expect("run curate-macro corrupt BSON against seeded out");
|
||||
assert_eq!(res_corrupt_seeded.status.code(), Some(1));
|
||||
assert!(res_corrupt_seeded.stdout.is_empty());
|
||||
assert_eq!(
|
||||
fs::read(&seeded_parquet).unwrap(),
|
||||
sentinel_bytes,
|
||||
"pre-seeded macro/part.parquet must remain byte-identical on corrupt BSON"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_invalid_flags_print_error_and_usage_without_touching_out() {
|
||||
let dir = TempDir::new("invalid-flags");
|
||||
write_macro_fixture(&dir.0);
|
||||
|
||||
let cases: [(&[&str], &str); 2] = [
|
||||
(
|
||||
&[
|
||||
"--from-mongo",
|
||||
"--te-data",
|
||||
"teData.bson",
|
||||
"--series-map",
|
||||
"series-map.tsv",
|
||||
"--out",
|
||||
"out_from_mongo",
|
||||
],
|
||||
"error: unknown flag '--from-mongo' for curate-macro",
|
||||
),
|
||||
(
|
||||
&[
|
||||
"--te-data",
|
||||
"teData.bson",
|
||||
"--series-map",
|
||||
"series-map.tsv",
|
||||
],
|
||||
"error: missing required flag '--out'",
|
||||
),
|
||||
];
|
||||
|
||||
for (idx, (argv, expected_error)) in cases.iter().enumerate() {
|
||||
let result = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args(*argv)
|
||||
.output()
|
||||
.expect("run curate-macro invalid flags");
|
||||
assert_eq!(result.status.code(), Some(1), "case {idx}");
|
||||
assert!(result.stdout.is_empty(), "case {idx}");
|
||||
let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr");
|
||||
let mut lines = stderr.lines();
|
||||
assert_eq!(lines.next(), Some(*expected_error), "{stderr}");
|
||||
assert_eq!(lines.next(), Some("Usage:"), "{stderr}");
|
||||
assert!(
|
||||
stderr.contains(
|
||||
"curate-macro --te-data <teData.bson> --series-map <series-map.tsv> --out <dir>"
|
||||
),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
assert!(
|
||||
!dir.0.join("out_from_mongo").exists(),
|
||||
"out_from_mongo must not be created"
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue