From d116bbf7a2c0ddc61384e7880a253ca6505e8e7e Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 12:08:23 -0500 Subject: [PATCH] =?UTF-8?q?T-168:=20M2.2k=20=E2=80=94=20`tools/curate-etl`?= =?UTF-8?q?:=20zero-copy=20raw=20BSON=20decoder=20for=20MongoDB=20`qmFinan?= =?UTF-8?q?cials`=20(`bson=5Fqm=5Ffinancials.rs`=20=E2=86=92=20`FinancialO?= =?UTF-8?q?bservation<&str>`,=20caller-supplied=20dotted=20field=20paths,?= =?UTF-8?q?=20fail-closed=20fiscal-period/date=20handling)=20with=20tests?= =?UTF-8?q?=20(no=20new=20crates,=20no=20CLI/bench/stream=20changes,=20no?= =?UTF-8?q?=20live=20Mongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 2 +- tools/curate-etl/src/bson_qm_financials.rs | 30 ++++++--- .../src/bson_qm_financials_tests.rs | 62 +++++++++++-------- 3 files changed, 56 insertions(+), 38 deletions(-) diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 8b289958..6dae9ec1 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1654,6 +1654,6 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m `src/bson_qm_financials.rs` (tested in `src/bson_qm_financials_tests.rs`) decodes raw `qmFinancials` / `qmFinancials-old` MongoDB BSON documents without allocating a `bson::Document`, emitting `FinancialObservation<&str>` rows (key borrowed verbatim from the input BSON slice; owned `currency` allocated only on emission) through `decode_qm_financials_doc`, `decode_qm_financials_bytes`, and `decode_qm_financials_buffer`: -- **Unverified live schema (explicit caller configuration):** Only the four repo-evidenced top-level field names have defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`, available via `QmFinancialsFieldNames::with_verified_defaults`). Live inner field names under `BalanceSheet`, `CashFlow`, and `IncomeStatement`, the currency path, `reportPeriod` token strings, and date BSON types are **unverified against a live dump**, so callers must supply the dotted `currency` path, explicit `Option<&str>` dotted paths for the six `FundamentalsFields` metrics, and `QmFinancialsFiscalPeriod` (`ByTokens { quarterly, annual }` or `Fixed(FiscalPeriod)`). Empty paths, empty/blank dotted segments, blank tokens, and overlapping token lists fail closed before decoding. +- **Unverified live schema (explicit caller configuration):** Only the four repo-evidenced top-level field names have defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`). Live inner field names under `BalanceSheet`, `CashFlow`, and `IncomeStatement`, the currency path, `reportPeriod` token strings, and date BSON types are **unverified against a live dump**, so `QmFinancialsFieldNames::with_verified_defaults(currency, revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding)` requires callers to explicitly supply the dotted `currency` path and an `Option<&str>` choice (`Some(path)` or intentional `None` opt-out) for all six `FundamentalsFields` metrics, alongside `QmFinancialsFiscalPeriod` (`ByTokens { quarterly, annual }` or `Fixed(FiscalPeriod)`). Empty paths, empty/blank dotted segments, blank tokens, and overlapping token lists fail closed before decoding. - **Fail-closed dates, periods & BSON framing:** Every document is structurally validated (nested documents/arrays/JS-with-scope up to depth `128`) before semantic skips run so corrupt BSON always returns `Err(BsonQmFinancialsError::CorruptBson)` with the failing byte offset (in buffer mode, callbacks may have already fired for earlier valid documents). `periodEndDate` (required) and `reportDate` (optional) accept BSON `DateTime` (UTC epoch day) or strict `YYYY-MM-DD` strings within `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE`; only an absent or BSON `Null` `reportDate` emits `None` (present-but-invalid vintage dates skip the document rather than silently dropping the vintage). Numeric paths accept `Double`, `Int32`, `Int64`, and trimmed numeric strings (`f64`), counting missing paths, wrong types, unparsable strings, and non-finite values on emitted rows while leaving unconfigured (`None`) paths and BSON `Null` leaves uncounted. - **Accounting invariant & ownership boundary:** `BsonQmFinancialsDecodeStats` satisfies `docs_in == rows_out + skipped_total()`. QuoteMedia owns the source statement inputs; `build_fundamentals_rows` owns filing linkage and `known_at` derivation, while this decoder preserves the supplied `report_date` vintage and `currency`. Chunked streaming (`bson_stream`), file-to-file runner, and CLI wiring are deferred to follow-up tasks. diff --git a/tools/curate-etl/src/bson_qm_financials.rs b/tools/curate-etl/src/bson_qm_financials.rs index adcb041a..8627c843 100644 --- a/tools/curate-etl/src/bson_qm_financials.rs +++ b/tools/curate-etl/src/bson_qm_financials.rs @@ -90,7 +90,8 @@ pub const DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD: &str = "reportPeriod"; /// Intentionally has no `Default`: live inner field names under `BalanceSheet`, `CashFlow`, and /// `IncomeStatement` and the currency path are unverified against a live dump. Use /// [`Self::with_verified_defaults`] to populate only the four repo-evidenced top-level defaults -/// while explicitly supplying `currency` and any desired numeric value paths. +/// while explicitly supplying `currency` and an `Option<&str>` choice for each of the six numeric +/// value paths. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct QmFinancialsFieldNames<'a> { pub key: &'a str, @@ -108,22 +109,31 @@ pub struct QmFinancialsFieldNames<'a> { impl<'a> QmFinancialsFieldNames<'a> { /// Constructs a configuration pre-populated with the four repo-evidenced defaults - /// (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the caller-supplied - /// `currency` path, and all six numeric value paths left unconfigured (`None`). + /// (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`) while requiring the caller + /// to explicitly supply the `currency` path and an `Option<&str>` choice (`Some(path)` or + /// intentional `None` opt-out) for each of the six numeric value fields. #[inline] - pub const fn with_verified_defaults(currency: &'a str) -> Self { + pub const fn with_verified_defaults( + currency: &'a str, + revenue: Option<&'a str>, + net_income: Option<&'a str>, + operating_cash_flow: Option<&'a str>, + total_assets: Option<&'a str>, + total_equity: Option<&'a str>, + shares_outstanding: Option<&'a str>, + ) -> Self { Self { key: DEFAULT_QM_FINANCIALS_KEY_FIELD, period_end: DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD, report_date: DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD, report_period: DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD, currency, - revenue: None, - net_income: None, - operating_cash_flow: None, - total_assets: None, - total_equity: None, - shares_outstanding: None, + revenue, + net_income, + operating_cash_flow, + total_assets, + total_equity, + shares_outstanding, } } diff --git a/tools/curate-etl/src/bson_qm_financials_tests.rs b/tools/curate-etl/src/bson_qm_financials_tests.rs index 8cedd317..ed2ba301 100644 --- a/tools/curate-etl/src/bson_qm_financials_tests.rs +++ b/tools/curate-etl/src/bson_qm_financials_tests.rs @@ -4,7 +4,7 @@ use bson::raw::{cstr, RawArrayBuf, RawBson, RawDocument, RawDocumentBuf}; use bson::DateTime as BsonDateTime; use super::*; -use crate::events::{parse_filing_timefiled, QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP}; +use crate::events::{QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP}; use crate::fundamentals::{build_fundamentals_rows, StatutoryLagVenue}; use crate::shorts::epoch_days_to_ymd; use crate::split::ymd_to_epoch_days; @@ -18,15 +18,15 @@ fn assert_conservation(stats: &BsonQmFinancialsDecodeStats) { } fn full_test_fields() -> QmFinancialsFieldNames<'static> { - QmFinancialsFieldNames { - revenue: Some("IncomeStatement.totalRevenue"), - net_income: Some("IncomeStatement.netIncome"), - operating_cash_flow: Some("CashFlow.operatingCashFlow"), - total_assets: Some("BalanceSheet.totalAssets"), - total_equity: Some("BalanceSheet.totalEquity"), - shares_outstanding: Some("BalanceSheet.commonSharesOutstanding"), - ..QmFinancialsFieldNames::with_verified_defaults("currency") - } + QmFinancialsFieldNames::with_verified_defaults( + "currency", + Some("IncomeStatement.totalRevenue"), + Some("IncomeStatement.netIncome"), + Some("CashFlow.operatingCashFlow"), + Some("BalanceSheet.totalAssets"), + Some("BalanceSheet.totalEquity"), + Some("BalanceSheet.commonSharesOutstanding"), + ) } const QUARTERLY_TOKENS: &[&str] = &["Q", "Q1", "Q2", "Q3", "Q4"]; @@ -499,7 +499,8 @@ fn covers_each_skip_counter_and_inclusive_date_bounds() { max_bound_null_rd.append(cstr!("reportDate"), RawBson::Null); max_bound_null_rd.append(cstr!("currency"), "USD"); - let minimal_fields = QmFinancialsFieldNames::with_verified_defaults("currency"); + let minimal_fields = + QmFinancialsFieldNames::with_verified_defaults("currency", None, None, None, None, None, None); let mut emitted = Vec::new(); let mut buf = Vec::new(); buf.extend_from_slice(min_bound_absent_rd.as_bytes()); @@ -518,7 +519,8 @@ fn covers_each_skip_counter_and_inclusive_date_bounds() { #[test] fn fixed_fiscal_period_override_ignores_report_period_field() { - let fields = QmFinancialsFieldNames::with_verified_defaults("currency"); + let fields = + QmFinancialsFieldNames::with_verified_defaults("currency", None, None, None, None, None, None); let mut doc = RawDocumentBuf::new(); doc.append(cstr!("qmSearchCode"), "MSFT:US"); @@ -542,16 +544,16 @@ fn fixed_fiscal_period_override_ignores_report_period_field() { #[test] fn numeric_null_counters_and_unconfigured_paths() { - // Configure 5 of 6 paths; leave `shares_outstanding` unconfigured (`None`). - let fields = QmFinancialsFieldNames { - revenue: Some("IncomeStatement.totalRevenue"), // missing sub-document - net_income: Some("BalanceSheet.netIncome"), // wrong type (boolean) - operating_cash_flow: Some("CashFlow.ocf"), // unparsable string - total_assets: Some("BalanceSheet.assets"), // non-finite double (NaN) - total_equity: Some("BalanceSheet.equity"), // non-finite string ("inf") - shares_outstanding: None, // unconfigured -> no null counter - ..QmFinancialsFieldNames::with_verified_defaults("meta.currency") - }; + // Configure 5 of 6 paths; leave `shares_outstanding` explicitly unconfigured (`None`). + let fields = QmFinancialsFieldNames::with_verified_defaults( + "meta.currency", + Some("IncomeStatement.totalRevenue"), // missing sub-document + Some("BalanceSheet.netIncome"), // wrong type (boolean) + Some("CashFlow.ocf"), // unparsable string + Some("BalanceSheet.assets"), // non-finite double (NaN) + Some("BalanceSheet.equity"), // non-finite string ("inf") + None, // unconfigured -> no null counter + ); let mut meta = RawDocumentBuf::new(); meta.append(cstr!("currency"), "CAD"); @@ -597,10 +599,15 @@ fn numeric_null_counters_and_unconfigured_paths() { doc_null.append(cstr!("currency"), "CAD"); doc_null.append(cstr!("IncomeStatement"), income_null); - let single_field = QmFinancialsFieldNames { - revenue: Some("IncomeStatement.totalRevenue"), - ..QmFinancialsFieldNames::with_verified_defaults("currency") - }; + let single_field = QmFinancialsFieldNames::with_verified_defaults( + "currency", + Some("IncomeStatement.totalRevenue"), + None, + None, + None, + None, + None, + ); let mut rows_null = Vec::new(); let stats_null = decode_qm_financials_doc(doc_null.as_ref(), &single_field, token_period_cfg(), |obs| { @@ -769,7 +776,8 @@ fn decoded_observation_feeds_build_fundamentals_rows_with_filing_timestamp() { assert_eq!(observations.len(), 1); let timefiled = "2024-08-02T16:30:15 EDT"; - let expected_micros = parse_filing_timefiled(timefiled).unwrap().utc_micros; + // 2024-08-02T16:30:15 EDT == 2024-08-02T20:30:15Z (1,722,630,615 seconds since Unix epoch). + let expected_micros: i64 = 1_722_630_615_000_000; let filings = vec![QmFiling { key: "AAPL:US",