T-198: M2.2r — tools/curate-etl: curate-fundamentals CLI command (file mode) wiring the existing run_curate_fundamentals into cli.rs + main.rs with parser tests and a binary end-to-end test (no new crates, no bench changes, no live Mongo)

This commit is contained in:
Studio 2026-12-03 14:27:13 -05:00
parent 8fd525ce4e
commit 564f768c8e
4 changed files with 1363 additions and 0 deletions

View file

@ -1571,6 +1571,59 @@ Inputs, defaults, and output rules:
Both `--flag value` and `--flag=value` forms are accepted. Missing required flags, invalid `--timestamp-unit`, duplicate flags, unknown flags (including `--from-mongo`), positional arguments, blank field names or `--mapping-source`, and colliding field-name roles (checked after applying defaults) exit non-zero with usage on stderr. Both `--flag value` and `--flag=value` forms are accepted. Missing required flags, invalid `--timestamp-unit`, duplicate flags, unknown flags (including `--from-mongo`), positional arguments, blank field names or `--mapping-source`, and colliding field-name roles (checked after applying defaults) exit non-zero with usage on stderr.
## `curate-fundamentals` Command (`M2.2r`)
End-to-end file-to-Parquet CLI command (`src/run_curate_fundamentals.rs`, wired in `src/cli.rs` and `src/main.rs`) streaming concatenated raw BSON `qmFinancials` and `qmFilings` dumps alongside `provider_mapping.tsv` and `listing_venues.tsv` into atomically published `<out>/fundamentals_pit/year=YYYY/part.parquet` partitions with zero extra crates and no database connections (**file mode only** — `--from-mongo` and `--mongo-uri*` are not supported and are rejected as unknown flags).
### Invocation
```bash
curate-etl curate-fundamentals \
--qm-financials qmFinancials.bson \
--qm-filings qmFilings.bson \
--provider-mapping provider_mapping.tsv \
--listing-venues listing_venues.tsv \
--out ./out \
--currency-field currency \
--filings-form-type-field formType \
--k 4 \
--quarterly-tokens Q1,Q2,Q3,Q4 \
--annual-tokens FY \
--revenue-field IncomeStatement.revenue \
--net-income-field IncomeStatement.netIncome \
--operating-cash-flow-field CashFlow.operatingCashFlow \
--total-assets-field BalanceSheet.totalAssets \
--total-equity-field BalanceSheet.totalEquity \
--shares-outstanding-field BalanceSheet.sharesOutstanding
```
Inputs, explicit configuration, defaults, and output rules:
- **Required flags (no defaults, because live `qmFinancials`/`qmFilings` field names and token strings are unverified in the repository):**
- `--qm-financials <path>`: concatenated raw BSON (`mongodump` `qmFinancials.bson`).
- `--qm-filings <path>`: concatenated raw BSON (`mongodump` `qmFilings.bson`).
- `--provider-mapping <path>`: headerless 5-column TSV (`source<TAB>provider_key<TAB>effective_from<TAB>effective_to<TAB>listing_id`, same format as `curate-bars-1d`).
- `--listing-venues <path>`: headerless 2-column TSV (`listing_id<TAB>venue`, where `listing_id` is a strictly positive ASCII integer and `venue` is exact `us_tsx` or `tsxv_cse`).
- `--out <dir>`: dataset root where `<out>/fundamentals_pit/year=YYYY/part.parquet` is atomically published.
- `--currency-field <name>`: dotted BSON path to the reporting currency in `qmFinancials`.
- `--filings-form-type-field <name>`: BSON field name for periodic filing form type in `qmFilings`.
- `--k <N>`: strict positive integer (`>= 1`) snapshot period limit.
- **Fiscal-period mode (mutually exclusive; supply exactly one mode):**
- `--fiscal-period <quarterly|annual>` to assign a fixed period to every decoded document, **or**
- `--quarterly-tokens <a,b,..>` and/or `--annual-tokens <a,b,..>` (comma-separated exact tokens preserving spelling and whitespace; empty/blank or overlapping tokens fail closed).
- **Optional flags with verified defaults:**
- `--financials-key-field` (default `qmSearchCode`)
- `--period-end-field` (default `periodEndDate`)
- `--report-date-field` (default `reportDate`)
- `--report-period-field` (default `reportPeriod`)
- `--filings-key-field` (default `symbol`)
- `--filings-timefiled-field` (default `timefiled`)
- `--mapping-source` (default `qm`)
- **Optional flags defaulting to `None` (unconfigured metrics emit `NULL` in Parquet):**
- `--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-filing-id-field <name>`, `--filings-url-field <name>`
Both `--flag value` and `--flag=value` forms are accepted. Missing required flags, combining or omitting fiscal-period modes, invalid `--k` (`0`, signs, non-digits, overflow), duplicate flags, unknown flags (including `--from-mongo` and `--mongo-uri*`), positional arguments, malformed dotted paths, overlapping `qmFilings` field names, or blank/overlapping fiscal tokens fail closed before touching `--out`, exiting non-zero with a single-line diagnostic error and usage on stderr. On success, stdout prints `format_curate_fundamentals_report`.
## Read-Only MongoDB URI Safety Guard (`M1.2ak`) ## Read-Only MongoDB URI Safety Guard (`M1.2ak`)
Pure, offline, `std`-only MongoDB URI safety guard (`src/mongo_safety.rs`, zero new crates, no sockets, no DNS resolution, no subprocesses) that ports the QA MongoDB target-classification rules from `apps/stock/config/src/env-safety.ts` before any Rust code may open a MongoDB connection. Pure, offline, `std`-only MongoDB URI safety guard (`src/mongo_safety.rs`, zero new crates, no sockets, no DNS resolution, no subprocesses) that ports the QA MongoDB target-classification rules from `apps/stock/config/src/env-safety.ts` before any Rust code may open a MongoDB connection.

View file

@ -41,8 +41,13 @@ use crate::bson_qm_events::{
DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, DEFAULT_EARNINGS_KEY_FIELD, DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, DEFAULT_EARNINGS_KEY_FIELD,
DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD, DEFAULT_EARNINGS_REPORT_DATE_FIELD, 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::bson_stream::BsonStreamOptions;
use crate::curate_adj::AdjPointInTimeFence; use crate::curate_adj::AdjPointInTimeFence;
use crate::fundamentals::FiscalPeriod;
use crate::ilp::IlpWriterOptions; use crate::ilp::IlpWriterOptions;
use crate::ilp_send::SendIlpArgs; use crate::ilp_send::SendIlpArgs;
use crate::mongo_stream::{ use crate::mongo_stream::{
@ -56,6 +61,9 @@ use crate::run_curate_bars::{
use crate::run_curate_bars_1m::{CurateBars1mArgs, DEFAULT_BARS_1M_MAPPING_SOURCE}; use crate::run_curate_bars_1m::{CurateBars1mArgs, DEFAULT_BARS_1M_MAPPING_SOURCE};
use crate::run_curate_corporate_actions::CurateCorporateActionsArgs; use crate::run_curate_corporate_actions::CurateCorporateActionsArgs;
use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE}; use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE};
use crate::run_curate_fundamentals::{
CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE,
};
use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL}; use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL};
use crate::run_curate_fx_1m::CurateFx1mArgs; use crate::run_curate_fx_1m::CurateFx1mArgs;
use crate::run_curate_posts::{ use crate::run_curate_posts::{
@ -88,6 +96,7 @@ pub enum CliAction {
CurateBars1m(CurateBars1mArgs), CurateBars1m(CurateBars1mArgs),
CurateFx1m(CurateFx1mArgs), CurateFx1m(CurateFx1mArgs),
CuratePosts(CuratePostsArgs), CuratePosts(CuratePostsArgs),
CurateFundamentals(CurateFundamentalsArgs),
SendIlp(SendIlpArgs), SendIlp(SendIlpArgs),
BenchSplit(usize), BenchSplit(usize),
BenchAdj(usize), BenchAdj(usize),
@ -156,6 +165,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-<NN>.ilp\n\ Curate USD/CAD 1-minute FX bars from eodIntraday1M BSON into fx_1m.shard-<NN>.ilp\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-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\
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\ 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} send-ilp --dir <dir> --prefix <bars_1m|bars_1m_qm|fx_1m> --addr <host:port>\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\ 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\ {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\
@ -209,6 +220,7 @@ pub fn format_usage_stderr(name: &str) -> String {
{name} curate-bars-1m --eod-intraday <path> --qm-splits <path> --provider-mapping <path> --out <dir> --shards <N> --known-at-micros <i64> [--mapping-source <name>]\n\ {name} curate-bars-1m --eod-intraday <path> --qm-splits <path> --provider-mapping <path> --out <dir> --shards <N> --known-at-micros <i64> [--mapping-source <name>]\n\
{name} curate-fx-1m --eod-intraday <path> --out <dir> --shards <N>\n\ {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-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} send-ilp --dir <dir> --prefix <bars_1m|bars_1m_qm|fx_1m> --addr <host:port>\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-split [rows]\n\
{name} bench-adj [events]\n\ {name} bench-adj [events]\n\
@ -1295,6 +1307,325 @@ fn parse_curate_posts_args(args: &[&str]) -> Result<CliAction, String> {
Ok(CliAction::CuratePosts(parsed)) Ok(CliAction::CuratePosts(parsed))
} }
fn sanitize_single_line(s: &str) -> String {
s.replace('\r', "\\r").replace('\n', "\\n")
}
fn set_token_list(
slot: &mut Option<Vec<String>>,
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(raw.split(',').map(str::to_string).collect());
Ok(())
}
fn parse_curate_fundamentals_args(args: &[&str]) -> Result<CliAction, String> {
parse_curate_fundamentals_args_inner(args).map_err(|e| sanitize_single_line(&e))
}
fn parse_curate_fundamentals_args_inner(args: &[&str]) -> Result<CliAction, String> {
let mut qm_financials: Option<PathBuf> = None;
let mut qm_filings: Option<PathBuf> = None;
let mut provider_mapping: Option<PathBuf> = None;
let mut listing_venues: Option<PathBuf> = None;
let mut out_dir: Option<PathBuf> = None;
let mut currency_field: Option<String> = None;
let mut filings_form_type_field: Option<String> = None;
let mut k: Option<usize> = None;
let mut fiscal_period_fixed: Option<FiscalPeriod> = None;
let mut quarterly_tokens: Option<Vec<String>> = None;
let mut annual_tokens: Option<Vec<String>> = None;
let mut financials_key_field: Option<String> = None;
let mut period_end_field: Option<String> = None;
let mut report_date_field: Option<String> = None;
let mut report_period_field: Option<String> = None;
let mut filings_key_field: Option<String> = None;
let mut filings_timefiled_field: Option<String> = None;
let mut mapping_source: Option<String> = None;
let mut revenue_field: Option<String> = None;
let mut net_income_field: Option<String> = None;
let mut operating_cash_flow_field: Option<String> = None;
let mut total_assets_field: Option<String> = None;
let mut total_equity_field: Option<String> = None;
let mut shares_outstanding_field: Option<String> = None;
let mut filings_filing_id_field: Option<String> = None;
let mut filings_url_field: Option<String> = 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-fundamentals"
));
}
let flag_name = token.split_once('=').map_or(token, |(flag, _)| flag);
if !matches!(
flag_name,
"--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"
| "--filings-key-field"
| "--filings-timefiled-field"
| "--mapping-source"
| "--revenue-field"
| "--net-income-field"
| "--operating-cash-flow-field"
| "--total-assets-field"
| "--total-equity-field"
| "--shares-outstanding-field"
| "--filings-filing-id-field"
| "--filings-url-field"
) {
return Err(format!(
"unknown flag '{flag_name}' for curate-fundamentals"
));
}
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 {
"--qm-financials" => set_path(&mut qm_financials, "--qm-financials", value)?,
"--qm-filings" => set_path(&mut qm_filings, "--qm-filings", 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)?,
"--currency-field" => set_name(&mut currency_field, "--currency-field", value)?,
"--filings-form-type-field" => {
set_name(&mut filings_form_type_field, "--filings-form-type-field", value)?;
}
"--k" => {
if k.is_some() {
return Err("duplicate flag '--k'".to_string());
}
if value.is_empty() {
return Err("empty value for flag '--k'".to_string());
}
if !value.bytes().all(|b| b.is_ascii_digit()) {
return Err(format!(
"invalid --k '{value}' (expected a positive integer >= 1)"
));
}
let parsed = value.parse::<usize>().map_err(|_| {
format!("invalid --k '{value}' (expected a positive integer >= 1)")
})?;
if parsed == 0 {
return Err(format!(
"invalid --k '{value}' (expected a positive integer >= 1)"
));
}
k = Some(parsed);
}
"--fiscal-period" => {
if fiscal_period_fixed.is_some() {
return Err("duplicate flag '--fiscal-period'".to_string());
}
fiscal_period_fixed = Some(match value {
"quarterly" => FiscalPeriod::Quarterly,
"annual" => FiscalPeriod::Annual,
_ => {
return Err(format!(
"invalid --fiscal-period '{value}' (expected 'quarterly' or 'annual')"
));
}
});
}
"--quarterly-tokens" => {
set_token_list(&mut quarterly_tokens, "--quarterly-tokens", value)?;
}
"--annual-tokens" => set_token_list(&mut annual_tokens, "--annual-tokens", value)?,
"--financials-key-field" => {
set_name(&mut financials_key_field, "--financials-key-field", value)?;
}
"--period-end-field" => set_name(&mut period_end_field, "--period-end-field", value)?,
"--report-date-field" => {
set_name(&mut report_date_field, "--report-date-field", value)?;
}
"--report-period-field" => {
set_name(&mut report_period_field, "--report-period-field", value)?;
}
"--filings-key-field" => {
set_name(&mut filings_key_field, "--filings-key-field", value)?;
}
"--filings-timefiled-field" => {
set_name(
&mut filings_timefiled_field,
"--filings-timefiled-field",
value,
)?;
}
"--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?,
"--revenue-field" => set_name(&mut revenue_field, "--revenue-field", value)?,
"--net-income-field" => set_name(&mut net_income_field, "--net-income-field", value)?,
"--operating-cash-flow-field" => {
set_name(
&mut operating_cash_flow_field,
"--operating-cash-flow-field",
value,
)?;
}
"--total-assets-field" => {
set_name(&mut total_assets_field, "--total-assets-field", value)?;
}
"--total-equity-field" => {
set_name(&mut total_equity_field, "--total-equity-field", value)?;
}
"--shares-outstanding-field" => {
set_name(
&mut shares_outstanding_field,
"--shares-outstanding-field",
value,
)?;
}
"--filings-filing-id-field" => {
set_name(
&mut filings_filing_id_field,
"--filings-filing-id-field",
value,
)?;
}
"--filings-url-field" => {
set_name(&mut filings_url_field, "--filings-url-field", value)?;
}
other => return Err(format!("unknown flag '{other}' for curate-fundamentals")),
}
}
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 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())?;
let filings_form_type_field = filings_form_type_field
.ok_or_else(|| "missing required flag '--filings-form-type-field'".to_string())?;
let k = k.ok_or_else(|| "missing required flag '--k'".to_string())?;
let fiscal_period = match (fiscal_period_fixed, quarterly_tokens, annual_tokens) {
(Some(_), Some(_), _) | (Some(_), _, Some(_)) => {
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 <quarterly|annual>' or '--quarterly-tokens' / '--annual-tokens'"
.to_string(),
);
}
};
let mut parsed = CurateFundamentalsArgs::with_verified_defaults(
qm_financials,
qm_filings,
provider_mapping,
listing_venues,
out_dir,
currency_field,
revenue_field,
net_income_field,
operating_cash_flow_field,
total_assets_field,
total_equity_field,
shares_outstanding_field,
fiscal_period,
filings_form_type_field,
k,
);
if let Some(v) = financials_key_field {
parsed.financials_key_field = v;
}
if let Some(v) = period_end_field {
parsed.financials_period_end_field = v;
}
if let Some(v) = report_date_field {
parsed.financials_report_date_field = v;
}
if let Some(v) = report_period_field {
parsed.financials_report_period_field = v;
}
if let Some(v) = filings_key_field {
parsed.filings_key_field = v;
}
if let Some(v) = filings_timefiled_field {
parsed.filings_timefiled_field = v;
}
if let Some(v) = filings_filing_id_field {
parsed.filings_filing_id_field = Some(v);
}
if let Some(v) = filings_url_field {
parsed.filings_url_field = Some(v);
}
if let Some(v) = mapping_source {
parsed.mapping_source = v;
}
parsed
.financials_field_names()
.validate()
.map_err(|e| e.to_string())?;
parsed
.filings_field_names()
.validate()
.map_err(|e| e.to_string())?;
parsed
.fiscal_period
.with_borrowed(|period| period.validate())
.map_err(|e| e.to_string())?;
Ok(CliAction::CurateFundamentals(parsed))
}
fn parse_curate_events_args(args: &[&str]) -> Result<CliAction, String> { fn parse_curate_events_args(args: &[&str]) -> Result<CliAction, String> {
let mut mongo = MongoFlagState::default(); let mut mongo = MongoFlagState::default();
let mut qm_filings: Option<PathBuf> = None; let mut qm_filings: Option<PathBuf> = None;
@ -1915,6 +2246,7 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
["curate-bars-1m", rest @ ..] => parse_curate_bars_1m_args(rest), ["curate-bars-1m", rest @ ..] => parse_curate_bars_1m_args(rest),
["curate-fx-1m", rest @ ..] => parse_curate_fx_1m_args(rest), ["curate-fx-1m", rest @ ..] => parse_curate_fx_1m_args(rest),
["curate-posts", rest @ ..] => parse_curate_posts_args(rest), ["curate-posts", rest @ ..] => parse_curate_posts_args(rest),
["curate-fundamentals", rest @ ..] => parse_curate_fundamentals_args(rest),
["send-ilp", rest @ ..] => parse_send_ilp_args(rest), ["send-ilp", rest @ ..] => parse_send_ilp_args(rest),
["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)),
["bench-split", raw] => match raw.parse::<usize>() { ["bench-split", raw] => match raw.parse::<usize>() {
@ -4895,6 +5227,466 @@ mod tests {
assert!(err.contains("cannot share BSON field 'shared'"), "{err}"); assert!(err.contains("cannot share BSON field 'shared'"), "{err}");
} }
#[test]
fn curate_fundamentals_parsing_validation_and_usage() {
let usage = format_usage("curate-etl", "0.1.0");
let stderr_usage = format_usage_stderr("curate-etl");
for text in [&usage, &stderr_usage] {
assert!(text.contains("curate-fundamentals --qm-financials"), "{text}");
assert!(text.contains("--fiscal-period <quarterly|annual>"), "{text}");
assert!(text.contains("--quarterly-tokens"), "{text}");
assert!(text.contains("--annual-tokens"), "{text}");
}
// Minimal valid invocation with --fiscal-period quarterly fills all verified defaults and None metrics
assert_eq!(
parse_args(&to_args(&[
"curate-fundamentals",
"--qm-financials",
"fin.bson",
"--qm-filings",
"fil.bson",
"--provider-mapping",
"map.tsv",
"--listing-venues",
"venues.tsv",
"--out",
"fund_out",
"--currency-field",
"currency",
"--filings-form-type-field",
"formType",
"--k",
"4",
"--fiscal-period",
"quarterly",
])),
Ok(CliAction::CurateFundamentals(CurateFundamentalsArgs {
qm_financials: PathBuf::from("fin.bson"),
qm_filings: PathBuf::from("fil.bson"),
provider_mapping: PathBuf::from("map.tsv"),
listing_venues: PathBuf::from("venues.tsv"),
out_dir: PathBuf::from("fund_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,
}))
);
// Fixed annual mode
assert_eq!(
parse_args(&to_args(&[
"curate-fundamentals",
"--qm-financials=fin.bson",
"--qm-filings=fil.bson",
"--provider-mapping=map.tsv",
"--listing-venues=venues.tsv",
"--out=fund_out",
"--currency-field=currency",
"--filings-form-type-field=formType",
"--k=2",
"--fiscal-period=annual",
])),
Ok(CliAction::CurateFundamentals(
CurateFundamentalsArgs::with_verified_defaults(
PathBuf::from("fin.bson"),
PathBuf::from("fil.bson"),
PathBuf::from("map.tsv"),
PathBuf::from("venues.tsv"),
PathBuf::from("fund_out"),
"currency",
None,
None,
None,
None,
None,
None,
CurateFundamentalsFiscalPeriod::Fixed(FiscalPeriod::Annual),
"formType",
2,
)
))
);
// All optional flags overridden with --flag=value and paired token lists (preserving token whitespace)
assert_eq!(
parse_args(&to_args(&[
"curate-fundamentals",
"--qm-financials=fin2.bson",
"--qm-filings=fil2.bson",
"--provider-mapping=map2.tsv",
"--listing-venues=venues2.tsv",
"--out=out2",
"--currency-field=meta.ccy",
"--filings-form-type-field=filingForm",
"--k=8",
"--quarterly-tokens=Q1,Q2, Q3 ,Q4",
"--annual-tokens=FY,Annual",
"--financials-key-field=secId",
"--period-end-field=periodEnd",
"--report-date-field=reportedAt",
"--report-period-field=periodCode",
"--revenue-field=IncomeStatement.revenue",
"--net-income-field=IncomeStatement.netIncome",
"--operating-cash-flow-field=CashFlow.operatingCashFlow",
"--total-assets-field=BalanceSheet.totalAssets",
"--total-equity-field=BalanceSheet.totalEquity",
"--shares-outstanding-field=BalanceSheet.sharesOutstanding",
"--filings-key-field=qmId",
"--filings-timefiled-field=filedAt",
"--filings-filing-id-field=filingId",
"--filings-url-field=filingUrl",
"--mapping-source=qm_alt",
])),
Ok(CliAction::CurateFundamentals(CurateFundamentalsArgs {
qm_financials: PathBuf::from("fin2.bson"),
qm_filings: PathBuf::from("fil2.bson"),
provider_mapping: PathBuf::from("map2.tsv"),
listing_venues: PathBuf::from("venues2.tsv"),
out_dir: PathBuf::from("out2"),
financials_key_field: "secId".to_string(),
financials_period_end_field: "periodEnd".to_string(),
financials_report_date_field: "reportedAt".to_string(),
financials_report_period_field: "periodCode".to_string(),
financials_currency_field: "meta.ccy".to_string(),
financials_revenue_field: Some("IncomeStatement.revenue".to_string()),
financials_net_income_field: Some("IncomeStatement.netIncome".to_string()),
financials_operating_cash_flow_field: Some(
"CashFlow.operatingCashFlow".to_string()
),
financials_total_assets_field: Some("BalanceSheet.totalAssets".to_string()),
financials_total_equity_field: Some("BalanceSheet.totalEquity".to_string()),
financials_shares_outstanding_field: Some(
"BalanceSheet.sharesOutstanding".to_string()
),
fiscal_period: CurateFundamentalsFiscalPeriod::ByTokens {
quarterly: vec![
"Q1".to_string(),
"Q2".to_string(),
" Q3 ".to_string(),
"Q4".to_string(),
],
annual: vec!["FY".to_string(), "Annual".to_string()],
},
filings_key_field: "qmId".to_string(),
filings_timefiled_field: "filedAt".to_string(),
filings_form_type_field: "filingForm".to_string(),
filings_filing_id_field: Some("filingId".to_string()),
filings_url_field: Some("filingUrl".to_string()),
mapping_source: "qm_alt".to_string(),
k: 8,
}))
);
// Single token-list modes (quarterly-only and annual-only)
let q_only = parse_args(&to_args(&[
"curate-fundamentals",
"--qm-financials",
"fin.bson",
"--qm-filings",
"fil.bson",
"--provider-mapping",
"map.tsv",
"--listing-venues",
"venues.tsv",
"--out",
"out",
"--currency-field",
"currency",
"--filings-form-type-field",
"formType",
"--k",
"1",
"--quarterly-tokens",
"Q1,Q2",
]))
.expect("quarterly-only token list");
assert!(matches!(
q_only,
CliAction::CurateFundamentals(CurateFundamentalsArgs {
fiscal_period: CurateFundamentalsFiscalPeriod::ByTokens {
ref quarterly,
ref annual,
},
..
}) if quarterly == &["Q1", "Q2"] && annual.is_empty()
));
let a_only = parse_args(&to_args(&[
"curate-fundamentals",
"--qm-financials",
"fin.bson",
"--qm-filings",
"fil.bson",
"--provider-mapping",
"map.tsv",
"--listing-venues",
"venues.tsv",
"--out",
"out",
"--currency-field",
"currency",
"--filings-form-type-field",
"formType",
"--k",
"1",
"--annual-tokens",
"FY",
]))
.expect("annual-only token list");
assert!(matches!(
a_only,
CliAction::CurateFundamentals(CurateFundamentalsArgs {
fiscal_period: CurateFundamentalsFiscalPeriod::ByTokens {
ref quarterly,
ref annual,
},
..
}) if quarterly.is_empty() && annual == &["FY"]
));
// Each omitted required flag errors
let required: [(&str, &str); 8] = [
("--qm-financials", "fin.bson"),
("--qm-filings", "fil.bson"),
("--provider-mapping", "map.tsv"),
("--listing-venues", "venues.tsv"),
("--out", "out"),
("--currency-field", "currency"),
("--filings-form-type-field", "formType"),
("--k", "4"),
];
for omit in 0..required.len() {
let mut argv = vec!["curate-fundamentals", "--fiscal-period", "quarterly"];
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 {missing_flag}, got: {err}"
);
}
// Neither fiscal mode supplied
let mut base_no_fiscal = vec!["curate-fundamentals"];
for &(flag, val) in &required {
base_no_fiscal.push(flag);
base_no_fiscal.push(val);
}
let err = parse_args(&to_args(&base_no_fiscal)).unwrap_err();
assert!(err.contains("missing required fiscal-period mode"), "{err}");
// Both fiscal modes supplied
for extra in [
&["--fiscal-period", "quarterly", "--quarterly-tokens", "Q1"][..],
&["--fiscal-period", "annual", "--annual-tokens", "FY"][..],
&[
"--fiscal-period",
"quarterly",
"--quarterly-tokens",
"Q1",
"--annual-tokens",
"FY",
][..],
] {
let mut argv = base_no_fiscal.clone();
argv.extend_from_slice(extra);
let err = parse_args(&to_args(&argv)).unwrap_err();
assert!(err.contains("cannot combine '--fiscal-period'"), "{err}");
}
// Invalid fixed --fiscal-period
for bad in ["", " ", "q", "QUARTERLY", "ANNUAL", "semi-annual"] {
let mut argv = base_no_fiscal.clone();
argv.extend_from_slice(&["--fiscal-period", bad]);
let err = parse_args(&to_args(&argv)).unwrap_err();
assert!(err.contains("invalid --fiscal-period"), "{bad}: {err}");
}
// Empty / blank tokens and token in both lists
for (flag, bad_tokens) in [
("--quarterly-tokens", ""),
("--annual-tokens", ""),
("--quarterly-tokens", " "),
("--quarterly-tokens", "Q1,,Q2"),
("--quarterly-tokens", ",Q1"),
("--quarterly-tokens", "Q1,"),
("--annual-tokens", "FY, ,Annual"),
] {
let mut argv = base_no_fiscal.clone();
let tok = format!("{flag}={bad_tokens}");
argv.push(&tok);
let err = parse_args(&to_args(&argv)).unwrap_err();
assert!(
err.contains("empty value for flag") || err.contains("must not be empty or blank"),
"{flag}={bad_tokens:?}: {err}"
);
}
let mut overlap = base_no_fiscal.clone();
overlap.extend_from_slice(&["--quarterly-tokens", "Q1,FY", "--annual-tokens", "FY"]);
let err = parse_args(&to_args(&overlap)).unwrap_err();
assert!(
err.contains("cannot appear in both quarterly and annual lists"),
"{err}"
);
// Malformed financials dotted path and overlapping filings fields
for bad_path in ["Income..revenue", ".revenue", "revenue.", "Income. .rev"] {
let mut argv = base_no_fiscal.clone();
argv.extend_from_slice(&["--fiscal-period", "quarterly", "--revenue-field", bad_path]);
let err = parse_args(&to_args(&argv)).unwrap_err();
assert!(
err.contains("empty or blank segment"),
"{bad_path}: {err}"
);
}
let mut filings_collision = base_no_fiscal.clone();
filings_collision.extend_from_slice(&[
"--fiscal-period",
"quarterly",
"--filings-filing-id-field",
"timefiled",
]);
let err = parse_args(&to_args(&filings_collision)).unwrap_err();
assert!(err.contains("cannot share BSON field 'timefiled'"), "{err}");
// Invalid --k values: 0, -1, +1, abc, overflow, empty
for bad_k in [
"0",
"-1",
"+1",
"abc",
"999999999999999999999999999999",
"",
] {
let mut argv = vec![
"curate-fundamentals",
"--qm-financials",
"fin.bson",
"--qm-filings",
"fil.bson",
"--provider-mapping",
"map.tsv",
"--listing-venues",
"venues.tsv",
"--out",
"out",
"--currency-field",
"currency",
"--filings-form-type-field",
"formType",
"--fiscal-period",
"quarterly",
];
let k_tok = format!("--k={bad_k}");
argv.push(&k_tok);
let err = parse_args(&to_args(&argv)).unwrap_err();
assert!(
err.contains("invalid --k") || err.contains("empty value for flag '--k'"),
"k={bad_k:?}: {err}"
);
}
// Duplicate flags
for (dup_flag, extra) in [
("--qm-financials", &["--qm-financials=other.bson"][..]),
("--k", &["--k=2"][..]),
("--fiscal-period", &["--fiscal-period=annual"][..]),
("--revenue-field", &["--revenue-field=a", "--revenue-field=b"][..]),
] {
let mut argv = base_no_fiscal.clone();
argv.extend_from_slice(&["--fiscal-period", "quarterly"]);
argv.extend_from_slice(extra);
let err = parse_args(&to_args(&argv)).unwrap_err();
assert!(
err.contains(&format!("duplicate flag '{dup_flag}'")),
"{dup_flag}: {err}"
);
}
let mut dup_tok = base_no_fiscal.clone();
dup_tok.extend_from_slice(&["--quarterly-tokens=Q1", "--quarterly-tokens=Q2"]);
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")
);
}
// Positional argument rejected
let err = parse_args(&to_args(&["curate-fundamentals", "extra"])).unwrap_err();
assert_eq!(
err,
"unexpected positional argument 'extra' for curate-fundamentals"
);
// Missing value at end or before another flag
let err = parse_args(&to_args(&["curate-fundamentals", "--qm-financials"])).unwrap_err();
assert_eq!(err, "missing value for flag '--qm-financials'");
let err = parse_args(&to_args(&[
"curate-fundamentals",
"--k",
"--out",
"o",
]))
.unwrap_err();
assert_eq!(err, "missing value for flag '--k'");
// Multiline arguments are sanitized to a single diagnostic line
let err = parse_args(&to_args(&["curate-fundamentals", "bad\nline\rarg"])).unwrap_err();
assert!(!err.contains('\n') && !err.contains('\r'), "{err:?}");
assert!(err.contains("bad\\nline\\rarg"), "{err:?}");
}
#[test] #[test]
fn parse_send_ilp_valid_space_and_equals_forms_and_all_allowed_prefixes() { fn parse_send_ilp_valid_space_and_equals_forms_and_all_allowed_prefixes() {
for prefix in ["bars_1m", "bars_1m_qm", "fx_1m"] { for prefix in ["bars_1m", "bars_1m_qm", "fx_1m"] {

View file

@ -29,6 +29,9 @@ use curate_etl::run_curate_corporate_actions::{
format_curate_corporate_actions_report, run_curate_corporate_actions, format_curate_corporate_actions_report, run_curate_corporate_actions,
}; };
use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events}; use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events};
use curate_etl::run_curate_fundamentals::{
format_curate_fundamentals_report, run_curate_fundamentals,
};
use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d}; 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_fx_1m::{format_curate_fx_1m_report, run_curate_fx_1m};
use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts}; use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts};
@ -231,6 +234,18 @@ fn main() -> ExitCode {
ExitCode::FAILURE ExitCode::FAILURE
} }
}, },
Ok(CliAction::CurateFundamentals(curate_args)) => {
match run_curate_fundamentals(&curate_args) {
Ok(report) => {
println!("{}", format_curate_fundamentals_report(&report));
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("error: {err}");
ExitCode::FAILURE
}
}
}
Ok(CliAction::SendIlp(send_args)) => match run_send_ilp(&send_args) { Ok(CliAction::SendIlp(send_args)) => match run_send_ilp(&send_args) {
Ok(report) => { Ok(report) => {
println!("{}", format_ilp_send_report(&report)); println!("{}", format_ilp_send_report(&report));

View file

@ -0,0 +1,503 @@
//! End-to-end tests for the file-mode `curate-fundamentals` CLI.
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use bson::raw::{cstr, RawDocumentBuf};
use curate_etl::fundamentals::FundamentalsFields;
use curate_etl::run_curate_fundamentals::{
format_curate_fundamentals_report, run_curate_fundamentals, CurateFundamentalsArgs,
CurateFundamentalsFiscalPeriod,
};
use curate_etl::shorts::et_to_utc_micros;
use curate_etl::split::ymd_to_epoch_days;
use parquet::file::reader::{FileReader, SerializedFileReader};
use parquet::record::{Field, Row};
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-fundamentals-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-fundamentals");
command
}
fn make_financials_doc(
key: &str,
period_end: &str,
report_date: &str,
report_period: &str,
currency: &str,
fields: FundamentalsFields,
) -> Vec<u8> {
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"), currency);
let mut income = RawDocumentBuf::new();
if let Some(v) = fields.revenue {
income.append(cstr!("revenue"), v);
}
if let Some(v) = fields.net_income {
income.append(cstr!("netIncome"), v);
}
doc.append(cstr!("IncomeStatement"), income);
let mut cashflow = RawDocumentBuf::new();
if let Some(v) = fields.operating_cash_flow {
cashflow.append(cstr!("operatingCashFlow"), v);
}
doc.append(cstr!("CashFlow"), cashflow);
let mut balance = RawDocumentBuf::new();
if let Some(v) = fields.total_assets {
balance.append(cstr!("totalAssets"), v);
}
if let Some(v) = fields.total_equity {
balance.append(cstr!("totalEquity"), v);
}
if let Some(v) = fields.shares_outstanding {
balance.append(cstr!("sharesOutstanding"), v);
}
doc.append(cstr!("BalanceSheet"), balance);
doc.into_bytes()
}
fn make_filing_doc(key: &str, timefiled: &str, form_type: &str, filing_id: &str) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), key);
doc.append(cstr!("timefiled"), timefiled);
doc.append(cstr!("formType"), form_type);
doc.append(cstr!("filingId"), filing_id);
doc.into_bytes()
}
fn read_parquet_partitions(out_dir: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
let dataset_root = out_dir.join("fundamentals_pit");
let mut files = BTreeMap::new();
for entry in fs::read_dir(&dataset_root).expect("read fundamentals_pit dir") {
let entry = entry.expect("dir entry");
let name = entry.file_name();
let part_path = entry.path().join("part.parquet");
assert!(
part_path.is_file(),
"expected part.parquet in {}",
entry.path().display()
);
let rel = PathBuf::from(&name).join("part.parquet");
files.insert(rel, fs::read(&part_path).expect("read parquet bytes"));
}
files
}
fn write_restatement_fixture(dir: &Path) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
let fin_path = dir.join("qmFinancials.bson");
let fil_path = dir.join("qmFilings.bson");
let map_path = dir.join("provider_mapping.tsv");
let venues_path = dir.join("listing_venues.tsv");
fs::write(&map_path, "qm\tACME\t2020-01-01\t\t301\n").unwrap();
fs::write(&venues_path, "301\tus_tsx\n").unwrap();
// Specimen dates and field shapes from `run_curate_fundamentals_tests`:
// four contiguous quarters (Q3 2023 .. Q2 2024) plus a late Q1 2024 restatement (10-Q/A on
// 2024-09-15) and an unmapped observation.
let mut fin_bytes = Vec::new();
for (key, pe, rd, rp, rev, ni, ocf, ta, te, sh) in [
(
"ACME",
"2023-09-30",
"2023-11-05",
"Q3",
90.0,
8.0,
10.0,
460.0,
275.0,
20.0,
),
(
"ACME",
"2023-12-31",
"2024-02-20",
"Q4",
110.0,
11.0,
14.0,
480.0,
288.0,
20.0,
),
(
"ACME",
"2024-03-31",
"2024-05-05",
"Q1",
100.0,
10.0,
12.0,
500.0,
300.0,
20.0,
),
(
"ACME",
"2024-06-30",
"2024-08-05",
"Q2",
250.0,
30.0,
35.0,
550.0,
330.0,
20.0,
),
(
"ACME",
"2024-03-31",
"2024-09-15",
"Q1",
88.0,
4.0,
9.0,
490.0,
294.0,
20.0,
),
(
"UNMAPPED",
"2024-06-30",
"2024-08-05",
"Q2",
50.0,
5.0,
6.0,
100.0,
60.0,
10.0,
),
] {
fin_bytes.extend_from_slice(&make_financials_doc(
key,
pe,
rd,
rp,
"USD",
FundamentalsFields {
revenue: Some(rev),
net_income: Some(ni),
operating_cash_flow: Some(ocf),
total_assets: Some(ta),
total_equity: Some(te),
shares_outstanding: Some(sh),
},
));
}
fs::write(&fin_path, fin_bytes).unwrap();
let mut fil_bytes = Vec::new();
for (key, ts, form, id) in [
("ACME", "2023-11-05T16:10:00 EST", "10-Q", "q3-2023-1"),
("ACME", "2024-02-20T16:10:00 EST", "10-Q", "q4-2023-1"),
("ACME", "2024-05-05T16:10:00 EDT", "10-Q", "q1-2024-1"),
("ACME", "2024-08-05T16:15:00 EDT", "10-Q", "q2-2024-1"),
("ACME", "2024-09-15T16:20:00 EDT", "10-Q/A", "q1-2024-a"),
] {
fil_bytes.extend_from_slice(&make_filing_doc(key, ts, form, id));
}
fs::write(&fil_path, fil_bytes).unwrap();
(fin_path, fil_path, map_path, venues_path)
}
#[test]
fn cli_publishes_runner_equivalent_fundamentals_and_preserves_pit_restatement() {
let dir = TempDir::new("e2e");
let (fin_path, fil_path, map_path, venues_path) = write_restatement_fixture(&dir.0);
let baseline_dir = dir.0.join("baseline");
let mut baseline_args = CurateFundamentalsArgs::with_verified_defaults(
fin_path.clone(),
fil_path.clone(),
map_path.clone(),
venues_path.clone(),
baseline_dir.clone(),
"currency",
Some("IncomeStatement.revenue".to_string()),
Some("IncomeStatement.netIncome".to_string()),
Some("CashFlow.operatingCashFlow".to_string()),
Some("BalanceSheet.totalAssets".to_string()),
Some("BalanceSheet.totalEquity".to_string()),
Some("BalanceSheet.sharesOutstanding".to_string()),
CurateFundamentalsFiscalPeriod::ByTokens {
quarterly: vec![
"Q1".to_string(),
"Q2".to_string(),
"Q3".to_string(),
"Q4".to_string(),
],
annual: vec!["FY".to_string()],
},
"formType",
4,
);
baseline_args.filings_filing_id_field = Some("filingId".to_string());
let baseline_report = run_curate_fundamentals(&baseline_args).expect("run library baseline");
let expected_report = format_curate_fundamentals_report(&baseline_report);
let baseline_partitions = read_parquet_partitions(&baseline_dir);
assert!(
baseline_partitions.contains_key(Path::new("year=2024/part.parquet")),
"expected nonempty 2024 partition"
);
let cli_out = dir.0.join("cli_out");
let result = cli()
.current_dir(&dir.0)
.args([
"--qm-financials",
"qmFinancials.bson",
"--qm-filings=qmFilings.bson",
"--provider-mapping",
"provider_mapping.tsv",
"--listing-venues=listing_venues.tsv",
"--out",
"cli_out",
"--currency-field=currency",
"--filings-form-type-field",
"formType",
"--filings-filing-id-field=filingId",
"--k",
"4",
"--quarterly-tokens=Q1,Q2,Q3,Q4",
"--annual-tokens",
"FY",
"--revenue-field",
"IncomeStatement.revenue",
"--net-income-field=IncomeStatement.netIncome",
"--operating-cash-flow-field",
"CashFlow.operatingCashFlow",
"--total-assets-field=BalanceSheet.totalAssets",
"--total-equity-field",
"BalanceSheet.totalEquity",
"--shares-outstanding-field=BalanceSheet.sharesOutstanding",
])
.output()
.expect("run curate-fundamentals");
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");
let actual_lines: Vec<&str> = stdout.lines().collect();
let expected_lines: Vec<&str> = expected_report.lines().collect();
assert_eq!(actual_lines.len(), expected_lines.len(), "{stdout}");
assert_eq!(
&actual_lines[..actual_lines.len() - 1],
&expected_lines[..expected_lines.len() - 1],
"deterministic report lines must match library baseline"
);
let timing_line = *actual_lines.last().unwrap();
let elapsed_str = timing_line
.strip_prefix(" timing: elapsed_secs=")
.unwrap_or_else(|| panic!("unexpected timing line: {timing_line:?}"));
let elapsed: f64 = elapsed_str.parse().expect("valid elapsed_secs float");
assert!(elapsed.is_finite() && elapsed >= 0.0, "{timing_line}");
let cli_partitions = read_parquet_partitions(&cli_out);
assert_eq!(
cli_partitions.keys().collect::<Vec<_>>(),
baseline_partitions.keys().collect::<Vec<_>>(),
"partition paths must match baseline"
);
for (rel, expected_bytes) in &baseline_partitions {
assert_eq!(
cli_partitions.get(rel).unwrap(),
expected_bytes,
"Parquet bytes differ for {}",
rel.display()
);
}
// Read the 2024 partition and verify listing, currency, metric value, filing-derived known_at,
// and PIT restatement isolation (Q1 restatement only visible at 2024-09-15).
let part_2024 = cli_out.join("fundamentals_pit/year=2024/part.parquet");
let reader = SerializedFileReader::new(File::open(&part_2024).unwrap()).unwrap();
let rows: Vec<_> = reader
.get_row_iter(None)
.unwrap()
.map(Result::unwrap)
.collect();
assert_eq!(rows.len(), 4, "expected Q4-23, Q1-24, Q2-24, and Q1-24/A snapshots in 2024");
let q2_filed_micros =
et_to_utc_micros(ymd_to_epoch_days(2024, 8, 5).unwrap(), 16, 15, 0).unwrap();
let restate_filed_micros =
et_to_utc_micros(ymd_to_epoch_days(2024, 9, 15).unwrap(), 16, 20, 0).unwrap();
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
}
let q2_row = &rows[2];
assert_eq!(col(q2_row, "listing_id"), &Field::Int(301));
assert_eq!(
col(q2_row, "effective_known_at"),
&Field::TimestampMicros(q2_filed_micros)
);
assert_eq!(
col(q2_row, "known_at_source"),
&Field::Str("filing_timestamp".to_string())
);
assert_eq!(
col(q2_row, "period_end"),
&Field::Date(ymd_to_epoch_days(2024, 6, 30).unwrap())
);
assert_eq!(col(q2_row, "currency"), &Field::Str("USD".to_string()));
assert_eq!(col(q2_row, "revenue"), &Field::Double(250.0));
assert_eq!(col(q2_row, "ttm_revenue"), &Field::Double(550.0));
let restated_row = &rows[3];
assert_eq!(col(restated_row, "listing_id"), &Field::Int(301));
assert_eq!(
col(restated_row, "effective_known_at"),
&Field::TimestampMicros(restate_filed_micros)
);
assert_eq!(
col(restated_row, "known_at_source"),
&Field::Str("filing_timestamp".to_string())
);
// Latest period remains Q2 2024 (250.0 revenue) while TTM revenue reflects the -12.0 Q1 restatement.
assert_eq!(
col(restated_row, "period_end"),
&Field::Date(ymd_to_epoch_days(2024, 6, 30).unwrap())
);
assert_eq!(
col(restated_row, "currency"),
&Field::Str("USD".to_string())
);
assert_eq!(col(restated_row, "revenue"), &Field::Double(250.0));
assert_eq!(col(restated_row, "ttm_revenue"), &Field::Double(538.0));
}
#[test]
fn cli_fails_closed_without_creating_out_dir_on_invalid_flags() {
let dir = TempDir::new("fail-closed");
let (_fin_path, _fil_path, _map_path, _venues_path) = write_restatement_fixture(&dir.0);
let out_missing_k = dir.0.join("out_missing_k");
let res_missing_k = cli()
.current_dir(&dir.0)
.args([
"--qm-financials",
"qmFinancials.bson",
"--qm-filings",
"qmFilings.bson",
"--provider-mapping",
"provider_mapping.tsv",
"--listing-venues",
"listing_venues.tsv",
"--out",
"out_missing_k",
"--currency-field",
"currency",
"--filings-form-type-field",
"formType",
"--fiscal-period",
"quarterly",
])
.output()
.expect("run curate-fundamentals missing --k");
assert_eq!(res_missing_k.status.code(), Some(1));
assert!(res_missing_k.stdout.is_empty());
let stderr_k = String::from_utf8(res_missing_k.stderr).unwrap();
let mut lines_k = stderr_k.lines();
assert_eq!(lines_k.next(), Some("error: missing required flag '--k'"));
assert_eq!(lines_k.next(), Some("Usage:"));
assert!(
stderr_k.contains("curate-fundamentals --qm-financials"),
"{stderr_k}"
);
assert!(!out_missing_k.exists(), "out_missing_k must not be created");
let out_from_mongo = dir.0.join("out_from_mongo");
let res_mongo = cli()
.current_dir(&dir.0)
.args([
"--from-mongo",
"--qm-financials",
"qmFinancials.bson",
"--qm-filings",
"qmFilings.bson",
"--provider-mapping",
"provider_mapping.tsv",
"--listing-venues",
"listing_venues.tsv",
"--out",
"out_from_mongo",
"--currency-field",
"currency",
"--filings-form-type-field",
"formType",
"--k",
"4",
"--fiscal-period",
"quarterly",
])
.output()
.expect("run curate-fundamentals with --from-mongo");
assert_eq!(res_mongo.status.code(), Some(1));
assert!(res_mongo.stdout.is_empty());
let stderr_mongo = String::from_utf8(res_mongo.stderr).unwrap();
let mut lines_mongo = stderr_mongo.lines();
assert_eq!(
lines_mongo.next(),
Some("error: unknown flag '--from-mongo' for curate-fundamentals")
);
assert_eq!(lines_mongo.next(), Some("Usage:"));
assert!(
stderr_mongo.contains("curate-fundamentals --qm-financials"),
"{stderr_mongo}"
);
assert!(
!out_from_mongo.exists(),
"out_from_mongo must not be created"
);
}