From 74ac9dce8ddba8deeb29cc57d651149bca0ea1bd Mon Sep 17 00:00:00 2001 From: Studio Date: Wed, 2 Dec 2026 14:05:45 -0500 Subject: [PATCH] =?UTF-8?q?T-171:=20M2.2m=20=E2=80=94=20`tools/curate-etl`?= =?UTF-8?q?:=20file-to-file=20`fundamentals=5Fpit`=20runner=20(`decode=5Fq?= =?UTF-8?q?m=5Ffinancials=5Fchunks`=20in=20`bson=5Fstream.rs`=20+=20`run?= =?UTF-8?q?=5Fcurate=5Ffundamentals.rs`:=20raw=20`qmFinancials`=20+=20`qmF?= =?UTF-8?q?ilings`=20BSON=20dumps=20+=20`provider=5Fmapping.tsv`=20+=20lis?= =?UTF-8?q?ting-venue=20TSV=20=E2=86=92=20`curate=5Fand=5Fwrite=5Ffundamen?= =?UTF-8?q?tals`=20=E2=86=92=20`fundamentals=5Fpit`=20Zstd=20Parquet)=20wi?= =?UTF-8?q?th=20tests=20(no=20new=20crates,=20no=20CLI/bench=20changes,=20?= =?UTF-8?q?no=20live=20Mongo)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 8 + tools/curate-etl/src/bson_stream.rs | 117 + tools/curate-etl/src/bson_stream_tests.rs | 372 ++- tools/curate-etl/src/lib.rs | 20 +- .../curate-etl/src/run_curate_fundamentals.rs | 1119 +++++++++ .../src/run_curate_fundamentals_tests.rs | 2146 +++++++++++++++++ 6 files changed, 3774 insertions(+), 8 deletions(-) create mode 100644 tools/curate-etl/src/run_curate_fundamentals.rs create mode 100644 tools/curate-etl/src/run_curate_fundamentals_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 6dae9ec1..9330232b 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1657,3 +1657,11 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m - **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. + +## `run_curate_fundamentals` File-to-File Runner (`M2.2m`) + +`run_curate_fundamentals` / `run_curate_fundamentals_with_readers` (`src/run_curate_fundamentals.rs`) connects concatenated raw BSON `qmFinancials` and `qmFilings` dump files, a headerless 5-column `provider_mapping.tsv`, and a headerless 2-column `listing_venues.tsv` through `decode_qm_financials_chunks` / `decode_qm_filings_chunks` (`src/bson_stream.rs`) and `curate_and_write_fundamentals` into `/fundamentals_pit/year=YYYY/part.parquet` (Zstd Parquet): + +- **Explicit field paths & fiscal policy (no unverified defaults):** `CurateFundamentalsArgs::with_verified_defaults(...)` populates only the four verified `qmFinancials` defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the two verified `qmFilings` defaults (`symbol`, `timefiled`), and `mapping_source = "qm"`. Callers must explicitly supply the `currency` path, all six numeric metric `Option` paths, `CurateFundamentalsFiscalPeriod` (`Fixed(FiscalPeriod)` or `ByTokens { quarterly, annual }`), `filings_form_type_field`, and snapshot period limit `k >= 1`. +- **`listing_venues.tsv` format (`load_listing_venues_tsv`):** strict headerless 2-column tab-separated file `listing_idvenue`, where `listing_id` is a strictly positive ASCII base-10 integer and `venue` is exact `us_tsx` (`StatutoryLagVenue::UsTsx`) or `tsxv_cse` (`StatutoryLagVenue::TsxvCse`). Wrong column counts, non-integer/non-positive IDs, unknown venues, duplicate IDs, and interior blank lines fail closed with a single-line error naming the path and 1-based line number. +- **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `/fundamentals_pit` or modifying pre-existing partitions. CLI wiring (`curate-fundamentals`) is a separate follow-up. diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs index 270dd83d..f797bf80 100644 --- a/tools/curate-etl/src/bson_stream.rs +++ b/tools/curate-etl/src/bson_stream.rs @@ -44,6 +44,10 @@ use crate::bson_qm_events::{ BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, QmFilingsFieldNames, RawQmEarning, RawQmFiling, }; +use crate::bson_qm_financials::{ + decode_qm_financials_buffer, BsonQmFinancialsDecodeStats, BsonQmFinancialsError, + QmFinancialsFieldNames, QmFinancialsFiscalPeriod, +}; use crate::bson_qm_intraday::{ decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, RawQmIntradayBar, }; @@ -53,6 +57,7 @@ use crate::bson_qm_prices::{ use crate::bson_te_market_data::{ decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError, }; +use crate::fundamentals::FinancialObservation; use crate::fx::FxDailyBar; use crate::posts::CeoPost; use crate::shorts::CeoShortReport; @@ -1333,6 +1338,118 @@ where decode_qm_earnings_chunks(&mut chunk_reader, fields, on_row) } +/// Terminal error returned by [`decode_qm_financials_chunks`] and [`decode_qm_financials_stream`]. +#[derive(Debug)] +pub enum BsonQmFinancialsStreamError { + Stream(BsonStreamError), + Decode(BsonQmFinancialsError), +} + +impl fmt::Display for BsonQmFinancialsStreamError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Stream(err) => write!(f, "{err}"), + Self::Decode(err) => write!(f, "{err}"), + } + } +} + +impl Error for BsonQmFinancialsStreamError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Stream(err) => Some(err), + Self::Decode(err) => Some(err), + } + } +} + +impl From for BsonQmFinancialsStreamError { + fn from(err: BsonStreamError) -> Self { + Self::Stream(err) + } +} + +impl From for BsonQmFinancialsStreamError { + fn from(err: BsonQmFinancialsError) -> Self { + Self::Decode(err) + } +} + +#[inline] +fn rebase_qm_financials_error(base: u64, err: BsonQmFinancialsError) -> BsonQmFinancialsError { + match err { + BsonQmFinancialsError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonQmFinancialsError::TruncatedDocument { + offset: base.saturating_add(offset), + remaining, + declared_len, + }, + BsonQmFinancialsError::CorruptDocumentLength { + offset, + declared_len, + } => BsonQmFinancialsError::CorruptDocumentLength { + offset: base.saturating_add(offset), + declared_len, + }, + BsonQmFinancialsError::CorruptBson { offset, detail } => { + BsonQmFinancialsError::CorruptBson { + offset: base.saturating_add(offset), + detail, + } + } + other => other, + } +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_financials_buffer`], +/// accumulating [`BsonQmFinancialsDecodeStats`] and rebasing structural BSON error offsets to +/// absolute stream byte offsets. +pub fn decode_qm_financials_chunks( + reader: &mut RawBsonChunkReader, + fields: &QmFinancialsFieldNames<'_>, + fiscal_period: QmFinancialsFiscalPeriod<'_>, + mut on_row: F, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(FinancialObservation<&'a str>), +{ + fields.validate()?; + fiscal_period.validate()?; + let mut total = BsonQmFinancialsDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = + decode_qm_financials_buffer(chunk.bytes, fields, fiscal_period, &mut on_row).map_err( + |err| BsonQmFinancialsStreamError::Decode(rebase_qm_financials_error(base, err)), + )?; + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `qmFinancials` [`std::io::Read`] source through +/// [`decode_qm_financials_buffer`] with bounded memory. +pub fn decode_qm_financials_stream( + reader: R, + options: BsonStreamOptions, + fields: &QmFinancialsFieldNames<'_>, + fiscal_period: QmFinancialsFiscalPeriod<'_>, + on_row: F, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(FinancialObservation<&'a str>), +{ + fields.validate()?; + fiscal_period.validate()?; + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_qm_financials_chunks(&mut chunk_reader, fields, fiscal_period, on_row) +} + #[cfg(test)] #[path = "bson_stream_tests.rs"] mod tests; diff --git a/tools/curate-etl/src/bson_stream_tests.rs b/tools/curate-etl/src/bson_stream_tests.rs index 72ccad08..12c563fa 100644 --- a/tools/curate-etl/src/bson_stream_tests.rs +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -13,16 +13,22 @@ use crate::bson_eod_prices::{ use crate::bson_qm_actions::{ decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, }; +use crate::bson_qm_financials::{ + decode_qm_financials_buffer, BsonQmFinancialsDecodeStats, BsonQmFinancialsError, + QmFinancialsFieldNames, QmFinancialsFiscalPeriod, +}; use crate::bson_qm_intraday::{ decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, }; use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError}; use crate::bson_stream::{ decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_stream, - decode_qm_dividend_stream, decode_qm_intraday_chunks, decode_qm_intraday_stream, - decode_qm_price_stream, decode_qm_split_stream, BsonStreamError, BsonStreamOptions, + decode_qm_dividend_stream, decode_qm_financials_chunks, decode_qm_financials_stream, + decode_qm_intraday_chunks, decode_qm_intraday_stream, decode_qm_price_stream, + decode_qm_split_stream, BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, }; +use crate::fundamentals::FinancialObservation; #[derive(Debug, Clone, Copy)] struct SplitMix64(u64); @@ -2724,3 +2730,365 @@ fn decode_qm_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() { } if offset == trunc_offset )); } + +#[allow(clippy::too_many_arguments)] +fn make_qm_financials_doc( + key: Option<&str>, + period_end: &str, + report_date: Option<&str>, + report_period: &str, + currency: &str, + revenue: Option, + net_income_str: Option<&str>, + total_assets: Option, +) -> Vec { + let mut doc = RawDocumentBuf::new(); + if let Some(k) = key { + doc.append(cstr!("qmSearchCode"), k); + } + doc.append(cstr!("periodEndDate"), period_end); + if let Some(rd) = report_date { + doc.append(cstr!("reportDate"), rd); + } + doc.append(cstr!("reportPeriod"), report_period); + doc.append(cstr!("currency"), currency); + + let mut income = RawDocumentBuf::new(); + if let Some(rev) = revenue { + income.append(cstr!("revenue"), rev); + } + if let Some(ni) = net_income_str { + income.append(cstr!("netIncome"), ni); + } + doc.append(cstr!("IncomeStatement"), income); + + let mut balance = RawDocumentBuf::new(); + if let Some(assets) = total_assets { + balance.append(cstr!("totalAssets"), assets); + } + doc.append(cstr!("BalanceSheet"), balance); + + doc.into_bytes() +} + +fn sample_qm_financials_fields() -> QmFinancialsFieldNames<'static> { + QmFinancialsFieldNames::with_verified_defaults( + "currency", + Some("IncomeStatement.revenue"), + Some("IncomeStatement.netIncome"), + None, + Some("BalanceSheet.totalAssets"), + None, + None, + ) +} + +fn owned_financial_obs(obs: FinancialObservation<&str>) -> FinancialObservation { + FinancialObservation { + key: obs.key.to_owned(), + period_end: obs.period_end, + fiscal_period: obs.fiscal_period, + currency: obs.currency, + report_date: obs.report_date, + fields: obs.fields, + } +} + +#[test] +fn qm_financials_chunks_match_buffer_across_small_chunks() { + let fields = sample_qm_financials_fields(); + let fiscal = QmFinancialsFiscalPeriod::ByTokens { + quarterly: &["Q1", "Q2", "Q3", "Q4"], + annual: &["FY"], + }; + + // Empty input returns zeroed stats and zero rows. + { + let mut empty_rows = 0usize; + let stats = decode_qm_financials_stream( + Cursor::new(Vec::::new()), + BsonStreamOptions::default(), + &fields, + fiscal, + |_| empty_rows += 1, + ) + .unwrap(); + assert_eq!(stats, BsonQmFinancialsDecodeStats::default()); + assert_eq!(empty_rows, 0); + } + + let mut fixture = Vec::new(); + // 1. Valid quarterly row with all configured metrics present. + fixture.extend_from_slice(&make_qm_financials_doc( + Some("NVDA"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + Some(100.0), + Some("25.5"), + Some(500.0), + )); + // 2. Semantic skip: missing key. + fixture.extend_from_slice(&make_qm_financials_doc( + None, + "2024-06-30", + Some("2024-08-01"), + "Q2", + "USD", + Some(120.0), + Some("30.0"), + Some(520.0), + )); + // 3. Valid annual row with nullable metric (unparsable netIncome + missing totalAssets). + fixture.extend_from_slice(&make_qm_financials_doc( + Some("SHOP:CA"), + "2024-12-31", + None, + "FY", + "CAD", + Some(450.0), + Some("not-a-number"), + None, + )); + // 4. Semantic skip: unmapped report_period token. + fixture.extend_from_slice(&make_qm_financials_doc( + Some("NVDA"), + "2024-09-30", + Some("2024-11-01"), + "SEMIANNUAL", + "USD", + Some(130.0), + Some("32.0"), + Some(540.0), + )); + // 5. Valid quarterly row. + fixture.extend_from_slice(&make_qm_financials_doc( + Some("NVDA"), + "2024-06-30", + Some("2024-08-02"), + "Q2", + "USD", + Some(140.0), + Some("35.0"), + Some(560.0), + )); + + let mut expected_rows = Vec::new(); + let expected_stats = decode_qm_financials_buffer(&fixture, &fields, fiscal, |obs| { + expected_rows.push(owned_financial_obs(obs)); + }) + .unwrap(); + assert_eq!(expected_stats.docs_in, 5); + assert_eq!(expected_stats.rows_out, 3); + assert_eq!(expected_stats.skipped_missing_key, 1); + assert_eq!(expected_stats.skipped_unmapped_report_period, 1); + assert_eq!(expected_stats.nulled_unparsable_string, 1); + assert_eq!(expected_stats.nulled_missing_path, 1); + + // Force multiple chunks via small chunk_capacity_bytes and short reads. + for (cap, step) in [(1, 1), (3, 2), (32, 7), (128, 17), (256, 29)] { + let opts = BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes: 4096, + }; + let mut got_rows = Vec::new(); + let got_stats = decode_qm_financials_stream( + FixedStepReader::new(&fixture, step), + opts, + &fields, + fiscal, + |obs| got_rows.push(owned_financial_obs(obs)), + ) + .unwrap(); + assert_eq!(got_stats, expected_stats); + assert_eq!(got_rows, expected_rows); + } + + // Exercise decode_qm_financials_chunks directly with random read sizes and EINTR interrupts. + let mut chunk_reader = RawBsonChunkReader::with_options( + RandomInterruptReader::new(&fixture, 0xF1A7, true), + BsonStreamOptions { + chunk_capacity_bytes: 64, + max_doc_bytes: 4096, + }, + ) + .unwrap(); + let mut chunk_rows = Vec::new(); + let chunk_stats = + decode_qm_financials_chunks(&mut chunk_reader, &fields, fiscal, |obs| { + chunk_rows.push(owned_financial_obs(obs)); + }) + .unwrap(); + assert_eq!(chunk_stats, expected_stats); + assert_eq!(chunk_rows, expected_rows); + assert_eq!(chunk_reader.docs_framed(), 5); + assert_eq!(chunk_reader.bytes_read(), fixture.len() as u64); +} + +#[test] +fn qm_financials_stream_rebases_later_chunk_corruption() { + let fields = sample_qm_financials_fields(); + let fiscal = QmFinancialsFiscalPeriod::ByTokens { + quarterly: &["Q1", "Q2"], + annual: &["FY"], + }; + + let doc1 = make_qm_financials_doc( + Some("NVDA"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + Some(100.0), + Some("20.0"), + Some(400.0), + ); + let doc2 = make_qm_financials_doc( + Some("NVDA"), + "2024-06-30", + Some("2024-08-01"), + "Q2", + "USD", + Some(110.0), + Some("22.0"), + Some(420.0), + ); + let mut corrupt_doc3 = make_qm_financials_doc( + Some("NVDA"), + "2024-09-30", + Some("2024-11-01"), + "Q3", + "USD", + Some(120.0), + Some("24.0"), + Some(440.0), + ); + // Corrupt an element type byte while preserving the 4-byte length prefix and trailing 0x00. + // Byte 4 is the type tag of the first element ("qmSearchCode"); 0x7E is an invalid BSON type. + corrupt_doc3[4] = 0x7E; + + let mut fixture = Vec::new(); + fixture.extend_from_slice(&doc1); + fixture.extend_from_slice(&doc2); + let corrupt_offset = fixture.len() as u64; + fixture.extend_from_slice(&corrupt_doc3); + + // Small chunk capacity guarantees corrupt_doc3 lands in a later chunk (start_offset > 0). + let opts = BsonStreamOptions { + chunk_capacity_bytes: doc1.len(), + max_doc_bytes: 4096, + }; + let mut seen_rows = Vec::new(); + let err = decode_qm_financials_stream( + FixedStepReader::new(&fixture, 11), + opts, + &fields, + fiscal, + |obs| seen_rows.push(owned_financial_obs(obs)), + ) + .unwrap_err(); + + assert_eq!(seen_rows.len(), 2); + assert!( + matches!( + err, + BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::CorruptBson { offset, .. }) + if offset == corrupt_offset + ), + "expected rebased CorruptBson at offset {corrupt_offset}, got: {err}" + ); + assert!(err.source().is_some()); +} + +#[test] +fn qm_financials_stream_rejects_invalid_config_before_read() { + struct PanicOnRead; + impl Read for PanicOnRead { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + panic!("reader must not be read when config validation fails"); + } + } + + let valid_fields = sample_qm_financials_fields(); + let valid_fiscal = QmFinancialsFiscalPeriod::ByTokens { + quarterly: &["Q1"], + annual: &["FY"], + }; + + // 1. Invalid dotted path (consecutive dot / empty segment). + let bad_fields = QmFinancialsFieldNames::with_verified_defaults( + "currency", + Some("IncomeStatement..revenue"), + None, + None, + None, + None, + None, + ); + let err = decode_qm_financials_stream( + PanicOnRead, + BsonStreamOptions::default(), + &bad_fields, + valid_fiscal, + |_| {}, + ) + .unwrap_err(); + assert!(matches!( + err, + BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFieldNames { .. }) + )); + + let mut chunk_reader = RawBsonChunkReader::new(PanicOnRead); + let err = decode_qm_financials_chunks(&mut chunk_reader, &bad_fields, valid_fiscal, |_| {}) + .unwrap_err(); + assert!(matches!( + err, + BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFieldNames { .. }) + )); + + // 2. Blank token in ByTokens. + let blank_token_fiscal = QmFinancialsFiscalPeriod::ByTokens { + quarterly: &["Q1", " "], + annual: &["FY"], + }; + let err = decode_qm_financials_stream( + PanicOnRead, + BsonStreamOptions::default(), + &valid_fields, + blank_token_fiscal, + |_| {}, + ) + .unwrap_err(); + assert!(matches!( + err, + BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) + )); + + // 3. Overlapping token between quarterly and annual. + let overlap_fiscal = QmFinancialsFiscalPeriod::ByTokens { + quarterly: &["Q1", "FY"], + annual: &["FY"], + }; + let err = decode_qm_financials_stream( + PanicOnRead, + BsonStreamOptions::default(), + &valid_fields, + overlap_fiscal, + |_| {}, + ) + .unwrap_err(); + assert!(matches!( + err, + BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) + )); + + let mut chunk_reader = RawBsonChunkReader::new(PanicOnRead); + let err = + decode_qm_financials_chunks(&mut chunk_reader, &valid_fields, overlap_fiscal, |_| {}) + .unwrap_err(); + assert!(matches!( + err, + BsonQmFinancialsStreamError::Decode(BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. }) + )); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index a7b49d35..381779b9 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -99,12 +99,13 @@ pub use bson_stream::{ decode_ceo_shorts_stream, decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream, decode_qm_earnings_chunks, decode_qm_earnings_stream, - decode_qm_filings_chunks, decode_qm_filings_stream, decode_qm_intraday_chunks, - decode_qm_intraday_stream, decode_qm_price_chunks, decode_qm_price_stream, - decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks, - decode_te_market_data_stream, BsonCeoPostsStreamError, BsonCeoShortsStreamError, - BsonQmEventsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, - DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, + decode_qm_filings_chunks, decode_qm_filings_stream, decode_qm_financials_chunks, + decode_qm_financials_stream, decode_qm_intraday_chunks, decode_qm_intraday_stream, + decode_qm_price_chunks, decode_qm_price_stream, decode_qm_split_chunks, + decode_qm_split_stream, decode_te_market_data_chunks, decode_te_market_data_stream, + BsonCeoPostsStreamError, BsonCeoShortsStreamError, BsonQmEventsStreamError, + BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, + RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, }; pub use bson_te_market_data::{ decode_te_market_data_buffer, decode_te_market_data_bytes, decode_te_market_data_doc, @@ -330,6 +331,13 @@ pub use run_curate_posts::{ CuratePostsRunReport, RunCuratePostsError, }; +pub mod run_curate_fundamentals; +pub use run_curate_fundamentals::{ + format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals, + run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, + CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, +}; + pub mod run_curate_shorts; pub use run_curate_shorts::{ format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader, diff --git a/tools/curate-etl/src/run_curate_fundamentals.rs b/tools/curate-etl/src/run_curate_fundamentals.rs new file mode 100644 index 00000000..104d1463 --- /dev/null +++ b/tools/curate-etl/src/run_curate_fundamentals.rs @@ -0,0 +1,1119 @@ +//! File-to-file `curate-fundamentals` runner (`M2.2m`). +//! +//! Streams concatenated raw BSON `qmFinancials` and `qmFilings` dump files alongside +//! `provider_mapping.tsv` and `listing_venues.tsv` into atomically published +//! `/fundamentals_pit/year=YYYY/part.parquet` partitions via +//! [`curate_and_write_fundamentals`]. +//! +//! # Contract & Point-in-Time Rules +//! - `qmFinancials` field defaults are restricted strictly to repo-evidenced top-level names +//! (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`). The `currency` path, all six +//! numeric metric paths (`Option`), and [`CurateFundamentalsFiscalPeriod`] have **no +//! defaults** and must be supplied explicitly. +//! - `qmFilings` field defaults match `run_curate_events` (`symbol`, `timefiled`), while +//! `form_type` has no default and `filing_id` / `url` are optional. +//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from +//! [`crate::run_curate_bars::load_provider_mapping_tsv`]. +//! - `listing_venues.tsv` uses a strict headerless 2-column TSV format `listing_idvenue` +//! where `venue` is exactly `us_tsx` or `tsxv_cse` ([`load_listing_venues_tsv`]). +//! - Decoded provider keys are preserved verbatim (no trimming or suffix rewriting) and resolved +//! to permanent `listing_id`s inside [`curate_and_write_fundamentals`]. +//! - **In-memory accumulation:** [`RawBsonChunkReader`] bounds only the raw BSON framing buffer +//! (`*_peak_chunk_bytes`); decoded observations and filings accumulate in memory before +//! [`curate_and_write_fundamentals`] runs. +//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_and_write_fundamentals`], +//! returning `Ok` with `rows_written == 0` and `files_written == 0` without creating +//! `/fundamentals_pit` or modifying any pre-existing partitions. +//! - **Fail-closed safety:** invalid field/fiscal config, blank `mapping_source`, `k == 0`, +//! unreadable inputs, malformed/overlapping `provider_mapping.tsv`, malformed/duplicate +//! `listing_venues.tsv`, truncated/corrupt BSON, `out_dir` or `/fundamentals_pit` +//! occupied by a regular file, or any input path resolving to `out_dir`, `/fundamentals_pit`, +//! or an existing `year=YYYY` partition target all return a typed [`RunCurateFundamentalsError`] +//! before anything is created or modified under `out_dir`. +//! +//! # Counter Conservation Invariants +//! Every successful [`CurateFundamentalsRunReport`] satisfies: +//! - `financials_docs_framed as usize == financials_decode.docs_in == financials_decode.rows_out + financials_decode.skipped_total()` +//! - `filings_docs_framed as usize == filings_decode.docs_in == filings_decode.rows_out + filings_decode.skipped_total()` +//! - `financials_decode.rows_out == curate_stats.observations_in` +//! - `filings_decode.rows_out == curate_stats.filings_in` +//! - `write_stats.rows_written == curate_stats.rows_out` + +use std::collections::{BTreeMap, HashSet}; +use std::error::Error; +use std::fmt::{self, Write as _}; +use std::fs::{self, File}; +use std::io; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use std::time::Instant; + +use crate::bson_qm_events::{ + BsonQmEventsError, BsonQmFilingsDecodeStats, QmFilingsFieldNames, DEFAULT_FILINGS_KEY_FIELD, + DEFAULT_FILINGS_TIMEFILED_FIELD, +}; +use crate::bson_qm_financials::{ + BsonQmFinancialsDecodeStats, BsonQmFinancialsError, QmFinancialsFieldNames, + QmFinancialsFiscalPeriod, 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::{ + decode_qm_filings_chunks, decode_qm_financials_chunks, BsonQmEventsStreamError, + BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, +}; +use crate::curate_fundamentals::{ + curate_and_write_fundamentals, CurateFundamentalsStats, CurateFundamentalsWriteError, +}; +use crate::events::QmFiling; +use crate::fundamentals::{FinancialObservation, FiscalPeriod, StatutoryLagVenue}; +use crate::parquet_fundamentals::{FundamentalsPitWriteOptions, FundamentalsPitWriteStats}; +use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; +use crate::run_curate_bars::{ + load_provider_mapping_tsv, parse_strict_positive_i32, read_tsv_lines, RunCurateBarsError, +}; + +/// Default `mapping_source` passed to `provider_mapping` lookups for `qmFinancials` / `qmFilings`. +pub const DEFAULT_FUNDAMENTALS_MAPPING_SOURCE: &str = "qm"; + +/// Owned fiscal-period resolution policy for [`CurateFundamentalsArgs`]. +/// +/// Mirrors [`QmFinancialsFiscalPeriod`] without borrowing lifetimes so arguments can be stored +/// and passed cleanly to [`run_curate_fundamentals`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CurateFundamentalsFiscalPeriod { + /// Assign a fixed [`FiscalPeriod`] to every decoded `qmFinancials` document. + Fixed(FiscalPeriod), + /// Match exact `report_period` BSON string values against explicit quarterly and annual lists. + ByTokens { + quarterly: Vec, + annual: Vec, + }, +} + +impl CurateFundamentalsFiscalPeriod { + /// Borrows this policy as [`QmFinancialsFiscalPeriod`] for validation or decoding. + pub fn with_borrowed(&self, f: impl FnOnce(QmFinancialsFiscalPeriod<'_>) -> R) -> R { + match self { + Self::Fixed(period) => f(QmFinancialsFiscalPeriod::Fixed(*period)), + Self::ByTokens { quarterly, annual } => { + let q_refs: Vec<&str> = quarterly.iter().map(String::as_str).collect(); + let a_refs: Vec<&str> = annual.iter().map(String::as_str).collect(); + f(QmFinancialsFiscalPeriod::ByTokens { + quarterly: &q_refs, + annual: &a_refs, + }) + } + } + } +} + +/// Arguments for [`run_curate_fundamentals`] and [`run_curate_fundamentals_with_readers`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateFundamentalsArgs { + pub qm_financials: PathBuf, + pub qm_filings: PathBuf, + pub provider_mapping: PathBuf, + pub listing_venues: PathBuf, + pub out_dir: PathBuf, + pub financials_key_field: String, + pub financials_period_end_field: String, + pub financials_report_date_field: String, + pub financials_report_period_field: String, + pub financials_currency_field: String, + pub financials_revenue_field: Option, + pub financials_net_income_field: Option, + pub financials_operating_cash_flow_field: Option, + pub financials_total_assets_field: Option, + pub financials_total_equity_field: Option, + pub financials_shares_outstanding_field: Option, + pub fiscal_period: CurateFundamentalsFiscalPeriod, + pub filings_key_field: String, + pub filings_timefiled_field: String, + pub filings_form_type_field: String, + pub filings_filing_id_field: Option, + pub filings_url_field: Option, + pub mapping_source: String, + pub k: usize, +} + +impl CurateFundamentalsArgs { + /// Constructs arguments pre-populated with the four repo-evidenced `qmFinancials` defaults + /// (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the two verified + /// `qmFilings` defaults (`symbol`, `timefiled`), and `mapping_source = "qm"`. + /// + /// Unverified fields (`financials_currency_field`, all six numeric `Option` paths, + /// `fiscal_period`, `filings_form_type_field`, and snapshot period limit `k`) must be supplied + /// explicitly. `filings_filing_id_field` and `filings_url_field` default to `None`. + #[allow(clippy::too_many_arguments)] + pub fn with_verified_defaults( + qm_financials: PathBuf, + qm_filings: PathBuf, + provider_mapping: PathBuf, + listing_venues: PathBuf, + out_dir: PathBuf, + financials_currency_field: impl Into, + financials_revenue_field: Option, + financials_net_income_field: Option, + financials_operating_cash_flow_field: Option, + financials_total_assets_field: Option, + financials_total_equity_field: Option, + financials_shares_outstanding_field: Option, + fiscal_period: CurateFundamentalsFiscalPeriod, + filings_form_type_field: impl Into, + k: usize, + ) -> Self { + Self { + qm_financials, + qm_filings, + provider_mapping, + listing_venues, + out_dir, + 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: financials_currency_field.into(), + financials_revenue_field, + financials_net_income_field, + financials_operating_cash_flow_field, + financials_total_assets_field, + financials_total_equity_field, + financials_shares_outstanding_field, + fiscal_period, + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: filings_form_type_field.into(), + filings_filing_id_field: None, + filings_url_field: None, + mapping_source: DEFAULT_FUNDAMENTALS_MAPPING_SOURCE.to_string(), + k, + } + } + + /// Borrows the configured `qmFinancials` BSON field paths as [`QmFinancialsFieldNames`]. + #[inline] + pub fn financials_field_names(&self) -> QmFinancialsFieldNames<'_> { + QmFinancialsFieldNames { + key: self.financials_key_field.as_str(), + period_end: self.financials_period_end_field.as_str(), + report_date: self.financials_report_date_field.as_str(), + report_period: self.financials_report_period_field.as_str(), + currency: self.financials_currency_field.as_str(), + revenue: self.financials_revenue_field.as_deref(), + net_income: self.financials_net_income_field.as_deref(), + operating_cash_flow: self.financials_operating_cash_flow_field.as_deref(), + total_assets: self.financials_total_assets_field.as_deref(), + total_equity: self.financials_total_equity_field.as_deref(), + shares_outstanding: self.financials_shares_outstanding_field.as_deref(), + } + } + + /// Borrows the configured `qmFilings` BSON field names as [`QmFilingsFieldNames`]. + #[inline] + pub fn filings_field_names(&self) -> QmFilingsFieldNames<'_> { + QmFilingsFieldNames { + key: self.filings_key_field.as_str(), + timefiled: self.filings_timefiled_field.as_str(), + form_type: self.filings_form_type_field.as_str(), + filing_id: self.filings_filing_id_field.as_deref(), + url: self.filings_url_field.as_deref(), + } + } +} + +/// Full run report produced by [`run_curate_fundamentals`] and +/// [`run_curate_fundamentals_with_readers`]. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateFundamentalsRunReport { + pub financials_docs_framed: u64, + pub financials_bytes_read: u64, + pub financials_peak_chunk_bytes: usize, + pub financials_decode: BsonQmFinancialsDecodeStats, + pub filings_docs_framed: u64, + pub filings_bytes_read: u64, + pub filings_peak_chunk_bytes: usize, + pub filings_decode: BsonQmFilingsDecodeStats, + pub curate_stats: CurateFundamentalsStats, + pub write_stats: FundamentalsPitWriteStats, + pub elapsed_secs: f64, +} + +/// Typed errors returned by [`load_listing_venues_tsv`], [`run_curate_fundamentals`], and +/// [`run_curate_fundamentals_with_readers`]. +/// +/// Every variant's `Display` output is a single line naming the offending path (and line number or +/// byte offset where applicable). +#[derive(Debug)] +pub enum RunCurateFundamentalsError { + InvalidOutDir { + path: PathBuf, + detail: String, + }, + InspectOutDir { + path: PathBuf, + source: io::Error, + }, + InvalidFinancialsConfig { + source: BsonQmFinancialsError, + }, + InvalidFilingsFieldNames { + source: BsonQmEventsError, + }, + EmptyMappingSource, + InvalidPeriodLimit { + k: usize, + }, + OpenInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + ReadInput { + label: &'static str, + path: PathBuf, + source: io::Error, + }, + TsvParse { + path: PathBuf, + line: usize, + detail: String, + }, + ProviderMapping { + path: PathBuf, + source: ProviderMappingError, + }, + BsonStream { + label: &'static str, + path: PathBuf, + source: BsonStreamError, + }, + CorruptFinancialsBson { + path: PathBuf, + offset: u64, + source: BsonQmFinancialsError, + }, + CorruptFilingsBson { + path: PathBuf, + offset: u64, + source: BsonQmEventsError, + }, + CurateWrite { + out_dir: PathBuf, + source: CurateFundamentalsWriteError, + }, +} + +struct SingleLineWriter<'a, 'b> { + f: &'a mut fmt::Formatter<'b>, +} + +impl fmt::Write for SingleLineWriter<'_, '_> { + fn write_str(&mut self, s: &str) -> fmt::Result { + let mut rest = s; + while let Some(idx) = rest.find(['\n', '\r']) { + let (head, tail) = rest.split_at(idx); + if !head.is_empty() { + self.f.write_str(head)?; + } + let mut chars = tail.chars(); + match chars.next() { + Some('\n') => self.f.write_str("\\n")?, + Some('\r') => self.f.write_str("\\r")?, + _ => unreachable!(), + } + rest = chars.as_str(); + } + if !rest.is_empty() { + self.f.write_str(rest)?; + } + Ok(()) + } +} + +impl fmt::Display for RunCurateFundamentalsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut w = SingleLineWriter { f }; + match self { + Self::InvalidOutDir { path, detail } => { + write!(w, "invalid --out '{}': {detail}", path.display()) + } + Self::InspectOutDir { path, source } => { + write!( + w, + "failed to inspect output path '{}': {source}", + path.display() + ) + } + Self::InvalidFinancialsConfig { source } => write!(w, "{source}"), + Self::InvalidFilingsFieldNames { source } => write!(w, "{source}"), + Self::EmptyMappingSource => { + write!(w, "invalid --mapping-source: must not be empty or blank") + } + Self::InvalidPeriodLimit { k } => { + write!(w, "invalid snapshot period limit k={k}: must be >= 1") + } + Self::OpenInput { + label, + path, + source, + } => write!(w, "failed to open {label} '{}': {source}", path.display()), + Self::ReadInput { + label, + path, + source, + } => write!(w, "failed to read {label} '{}': {source}", path.display()), + Self::TsvParse { path, line, detail } => { + write!(w, "{}:{line}: {detail}", path.display()) + } + Self::ProviderMapping { path, source } => { + write!(w, "invalid provider_mapping '{}': {source}", path.display()) + } + Self::BsonStream { + label, + path, + source, + } => write!(w, "failed reading {label} '{}': {source}", path.display()), + Self::CorruptFinancialsBson { + path, + offset, + source, + } => write!( + w, + "corrupt qm-financials BSON '{}' at byte offset {offset}: {source}", + path.display() + ), + Self::CorruptFilingsBson { + path, + offset, + source, + } => write!( + w, + "corrupt qm-filings BSON '{}' at byte offset {offset}: {source}", + path.display() + ), + Self::CurateWrite { out_dir, source } => { + write!(w, "curate/write to '{}' failed: {source}", out_dir.display()) + } + } + } +} + +impl Error for RunCurateFundamentalsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::InspectOutDir { source, .. } => Some(source), + Self::InvalidFinancialsConfig { source } => Some(source), + Self::InvalidFilingsFieldNames { source } => Some(source), + Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), + Self::ProviderMapping { source, .. } => Some(source), + Self::BsonStream { source, .. } => Some(source), + Self::CorruptFinancialsBson { source, .. } => Some(source), + Self::CorruptFilingsBson { source, .. } => Some(source), + Self::CurateWrite { source, .. } => Some(source), + Self::InvalidOutDir { .. } + | Self::EmptyMappingSource + | Self::InvalidPeriodLimit { .. } + | Self::TsvParse { .. } => None, + } + } +} + +fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCurateFundamentalsError { + match err { + RunCurateBarsError::OpenInput { + label, + path, + source, + } => RunCurateFundamentalsError::OpenInput { + label, + path, + source, + }, + RunCurateBarsError::ReadInput { + label, + path, + source, + } => RunCurateFundamentalsError::ReadInput { + label, + path, + source, + }, + RunCurateBarsError::TsvParse { path, line, detail } => { + RunCurateFundamentalsError::TsvParse { path, line, detail } + } + RunCurateBarsError::ProviderMapping { path, source } => { + RunCurateFundamentalsError::ProviderMapping { path, source } + } + other => RunCurateFundamentalsError::TsvParse { + path: path.to_path_buf(), + line: 0, + detail: other.to_string(), + }, + } +} + +/// Loads `listing_venues.tsv` into an ordered `listing_id -> StatutoryLagVenue` map. +/// +/// Format (no header, 2 `\t`-separated columns): +/// `listing_id \t venue` +/// +/// `listing_id` must be a strictly positive ASCII base-10 `i32` (no sign or surrounding +/// whitespace). `venue` must be exact `"us_tsx"` or `"tsxv_cse"`. Duplicate `listing_id`s, +/// wrong column counts, unknown venues, and interior blank lines fail closed with a typed +/// single-line error naming `path` and the 1-based line number. +pub fn load_listing_venues_tsv( + path: &Path, +) -> Result, RunCurateFundamentalsError> { + let mut venues = BTreeMap::new(); + read_tsv_lines(path, "listing-venues", |_line_no, line| { + let mut cols = line.split('\t'); + let id_str = cols + .next() + .ok_or_else(|| "expected 2 tab-separated columns (listing_id, venue)".to_string())?; + let venue_str = cols.next().ok_or_else(|| { + "expected 2 tab-separated columns (listing_id, venue), got 1".to_string() + })?; + if cols.next().is_some() { + let count = line.split('\t').count(); + return Err(format!( + "expected 2 tab-separated columns (listing_id, venue), got {count}" + )); + } + + let listing_id = parse_strict_positive_i32(id_str).ok_or_else(|| { + format!("invalid listing_id '{id_str}': expected strictly positive integer") + })?; + + let venue = match venue_str { + "us_tsx" => StatutoryLagVenue::UsTsx, + "tsxv_cse" => StatutoryLagVenue::TsxvCse, + other => { + return Err(format!( + "unknown venue '{other}': expected 'us_tsx' or 'tsxv_cse'" + )); + } + }; + + if venues.insert(listing_id, venue).is_some() { + return Err(format!("duplicate listing_id {listing_id}")); + } + + Ok(()) + }) + .map_err(|err| map_tsv_error(path, err))?; + + Ok(venues) +} + +/// Resolves `path` to an absolute normalized path while preserving OS symlink-before-`..` +/// semantics: if `path` exists it is canonicalized directly; otherwise components are walked +/// left-to-right, canonicalizing each existing prefix before resolving `..`, and only lexically +/// normalizing `..` within any non-existent suffix. +fn resolve_normalized_path(path: &Path) -> PathBuf { + if let Ok(canon) = path.canonicalize() { + return canon; + } + + let abs = if path.is_absolute() { + path.to_path_buf() + } else if let Ok(cwd) = std::env::current_dir() { + cwd.join(path) + } else { + path.to_path_buf() + }; + + if let Ok(canon) = abs.canonicalize() { + return canon; + } + + let mut resolved = PathBuf::new(); + for comp in abs.components() { + match comp { + Component::Prefix(prefix) => resolved.push(prefix.as_os_str()), + Component::RootDir => resolved.push(Component::RootDir.as_os_str()), + Component::CurDir => {} + Component::Normal(seg) => { + resolved.push(seg); + if let Ok(canon) = resolved.canonicalize() { + resolved = canon; + } + } + Component::ParentDir => { + resolved.push(Component::ParentDir.as_os_str()); + if let Ok(canon) = resolved.canonicalize() { + resolved = canon; + } else { + resolved.pop(); + if matches!(resolved.components().next_back(), Some(Component::Normal(_))) { + resolved.pop(); + } + } + } + } + } + + resolved +} + +fn validate_out_dir_and_inputs( + args: &CurateFundamentalsArgs, +) -> Result<(), RunCurateFundamentalsError> { + if args.out_dir.as_os_str().is_empty() { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: args.out_dir.clone(), + detail: "output directory path must not be empty".to_string(), + }); + } + + match fs::metadata(&args.out_dir) { + Ok(meta) if !meta.is_dir() => { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: args.out_dir.clone(), + detail: "path exists and is not a directory".to_string(), + }); + } + Ok(_) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => {} + Err(source) => { + return Err(RunCurateFundamentalsError::InspectOutDir { + path: args.out_dir.clone(), + source, + }); + } + } + + let fundamentals_dir = args.out_dir.join("fundamentals_pit"); + let fundamentals_dir_exists = match fs::metadata(&fundamentals_dir) { + Ok(meta) if !meta.is_dir() => { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: fundamentals_dir, + detail: "fundamentals_pit output path exists and is not a directory".to_string(), + }); + } + Ok(_) => true, + Err(err) if err.kind() == io::ErrorKind::NotFound => false, + Err(source) => { + return Err(RunCurateFundamentalsError::InspectOutDir { + path: fundamentals_dir, + source, + }); + } + }; + + let resolved_out = resolve_normalized_path(&args.out_dir); + let resolved_fundamentals = resolve_normalized_path(&fundamentals_dir); + + let resolved_inputs = [ + ( + "qm-financials", + &args.qm_financials, + resolve_normalized_path(&args.qm_financials), + ), + ( + "qm-filings", + &args.qm_filings, + resolve_normalized_path(&args.qm_filings), + ), + ( + "provider-mapping", + &args.provider_mapping, + resolve_normalized_path(&args.provider_mapping), + ), + ( + "listing-venues", + &args.listing_venues, + resolve_normalized_path(&args.listing_venues), + ), + ]; + + for (label, input_path, resolved_in) in &resolved_inputs { + if *resolved_in == resolved_out + || *resolved_in == resolved_fundamentals + || resolved_in.starts_with(&resolved_fundamentals) + { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: args.out_dir.clone(), + detail: format!( + "output directory would overlap {label} input '{}'", + input_path.display() + ), + }); + } + } + + // Check existing `year=YYYY` partition directories and their `part.parquet` targets for + // aliases to any input path, catching symlinked year directories whose resolved targets live + // outside `/fundamentals_pit`. + if fundamentals_dir_exists { + let entries = fs::read_dir(&fundamentals_dir).map_err(|source| { + RunCurateFundamentalsError::InspectOutDir { + path: fundamentals_dir.clone(), + source, + } + })?; + for entry_res in entries { + let entry = entry_res.map_err(|source| RunCurateFundamentalsError::InspectOutDir { + path: fundamentals_dir.clone(), + source, + })?; + let name = entry.file_name(); + if !name.to_string_lossy().starts_with("year=") { + continue; + } + let year_dir = entry.path(); + let resolved_year_dir = resolve_normalized_path(&year_dir); + let resolved_part_via_dir = resolved_year_dir.join("part.parquet"); + let resolved_part = resolve_normalized_path(&year_dir.join("part.parquet")); + + for (label, input_path, resolved_in) in &resolved_inputs { + if *resolved_in == resolved_year_dir + || *resolved_in == resolved_part_via_dir + || *resolved_in == resolved_part + || resolved_in.starts_with(&resolved_year_dir) + { + return Err(RunCurateFundamentalsError::InvalidOutDir { + path: year_dir, + detail: format!( + "partition output '{}' would overlap {label} input '{}'", + resolved_part_via_dir.display(), + input_path.display() + ), + }); + } + } + } + } + + Ok(()) +} + +fn financials_bson_error_offset(err: &BsonQmFinancialsError) -> u64 { + match err { + BsonQmFinancialsError::TruncatedDocument { offset, .. } + | BsonQmFinancialsError::CorruptDocumentLength { offset, .. } + | BsonQmFinancialsError::CorruptBson { offset, .. } => *offset, + BsonQmFinancialsError::InvalidFieldNames { .. } + | BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. } => 0, + } +} + +fn filings_bson_error_offset(err: &BsonQmEventsError) -> u64 { + match err { + BsonQmEventsError::TruncatedDocument { offset, .. } + | BsonQmEventsError::CorruptDocumentLength { offset, .. } + | BsonQmEventsError::CorruptBson { offset, .. } => *offset, + BsonQmEventsError::InvalidFieldNames { .. } => 0, + } +} + +fn map_financials_stream_error( + path: &Path, + err: BsonQmFinancialsStreamError, +) -> RunCurateFundamentalsError { + match err { + BsonQmFinancialsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream { + label: "qm-financials", + path: path.to_path_buf(), + source, + }, + BsonQmFinancialsStreamError::Decode(source) => match &source { + BsonQmFinancialsError::InvalidFieldNames { .. } + | BsonQmFinancialsError::InvalidFiscalPeriodConfig { .. } => { + RunCurateFundamentalsError::InvalidFinancialsConfig { source } + } + _ => { + let offset = financials_bson_error_offset(&source); + RunCurateFundamentalsError::CorruptFinancialsBson { + path: path.to_path_buf(), + offset, + source, + } + } + }, + } +} + +fn map_filings_stream_error( + path: &Path, + err: BsonQmEventsStreamError, +) -> RunCurateFundamentalsError { + match err { + BsonQmEventsStreamError::Stream(source) => RunCurateFundamentalsError::BsonStream { + label: "qm-filings", + path: path.to_path_buf(), + source, + }, + BsonQmEventsStreamError::Decode(source) => match &source { + BsonQmEventsError::InvalidFieldNames { .. } => { + RunCurateFundamentalsError::InvalidFilingsFieldNames { source } + } + _ => { + let offset = filings_bson_error_offset(&source); + RunCurateFundamentalsError::CorruptFilingsBson { + path: path.to_path_buf(), + offset, + source, + } + } + }, + } +} + +#[inline] +fn intern_key(interner: &mut HashSet>, key: &str) -> Arc { + if let Some(existing) = interner.get(key) { + Arc::clone(existing) + } else { + let arc: Arc = Arc::from(key); + interner.insert(Arc::clone(&arc)); + arc + } +} + +struct DecodedFundamentalsInputs { + mapping: ProviderMappingTable, + venues: BTreeMap, + observations: Vec>>, + filings: Vec>>, + financials_docs_framed: u64, + financials_bytes_read: u64, + financials_peak_chunk_bytes: usize, + financials_decode: BsonQmFinancialsDecodeStats, + filings_docs_framed: u64, + filings_bytes_read: u64, + filings_peak_chunk_bytes: usize, + filings_decode: BsonQmFilingsDecodeStats, +} + +fn decode_inputs_from_openers( + args: &CurateFundamentalsArgs, + open_financials: FF, + open_filings: FL, +) -> Result +where + RF: io::Read, + FF: FnOnce() -> Result, + RL: io::Read, + FL: FnOnce() -> Result, +{ + let financials_fields = args.financials_field_names(); + financials_fields + .validate() + .map_err(|source| RunCurateFundamentalsError::InvalidFinancialsConfig { source })?; + + args.fiscal_period + .with_borrowed(|fp| fp.validate()) + .map_err(|source| RunCurateFundamentalsError::InvalidFinancialsConfig { source })?; + + let filings_fields = args.filings_field_names(); + filings_fields + .validate() + .map_err(|source| RunCurateFundamentalsError::InvalidFilingsFieldNames { source })?; + + if args.mapping_source.trim().is_empty() { + return Err(RunCurateFundamentalsError::EmptyMappingSource); + } + + if args.k == 0 { + return Err(RunCurateFundamentalsError::InvalidPeriodLimit { k: args.k }); + } + + let mapping_rows = load_provider_mapping_tsv(&args.provider_mapping) + .map_err(|err| map_tsv_error(&args.provider_mapping, err))?; + let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| { + RunCurateFundamentalsError::ProviderMapping { + path: args.provider_mapping.clone(), + source, + } + })?; + + let venues = load_listing_venues_tsv(&args.listing_venues)?; + + let mut key_interner: HashSet> = HashSet::new(); + + // Stream and decode qmFinancials, releasing the chunk reader immediately afterward. + let ( + observations, + financials_docs_framed, + financials_bytes_read, + financials_peak_chunk_bytes, + financials_decode, + ) = { + let financials_stream = open_financials()?; + let mut financials_reader = + RawBsonChunkReader::with_options(financials_stream, BsonStreamOptions::default()) + .map_err(|source| RunCurateFundamentalsError::BsonStream { + label: "qm-financials", + path: args.qm_financials.clone(), + source, + })?; + + let mut observations: Vec>> = Vec::new(); + let decode = args.fiscal_period.with_borrowed(|fp| { + decode_qm_financials_chunks(&mut financials_reader, &financials_fields, fp, |obs| { + let key = intern_key(&mut key_interner, obs.key); + observations.push(FinancialObservation { + key, + period_end: obs.period_end, + fiscal_period: obs.fiscal_period, + currency: obs.currency, + report_date: obs.report_date, + fields: obs.fields, + }); + }) + }) + .map_err(|err| map_financials_stream_error(&args.qm_financials, err))?; + + ( + observations, + financials_reader.docs_framed(), + financials_reader.bytes_read(), + financials_reader.buffer_capacity(), + decode, + ) + }; + + // Stream and decode qmFilings, reusing the same key interner and releasing the chunk reader. + let (filings, filings_docs_framed, filings_bytes_read, filings_peak_chunk_bytes, filings_decode) = { + let filings_stream = open_filings()?; + let mut filings_reader = + RawBsonChunkReader::with_options(filings_stream, BsonStreamOptions::default()) + .map_err(|source| RunCurateFundamentalsError::BsonStream { + label: "qm-filings", + path: args.qm_filings.clone(), + source, + })?; + + let mut filings: Vec>> = Vec::new(); + let decode = decode_qm_filings_chunks(&mut filings_reader, &filings_fields, |raw| { + let key = intern_key(&mut key_interner, raw.key); + filings.push(raw.to_qm_filing(key)); + }) + .map_err(|err| map_filings_stream_error(&args.qm_filings, err))?; + + ( + filings, + filings_reader.docs_framed(), + filings_reader.bytes_read(), + filings_reader.buffer_capacity(), + decode, + ) + }; + + Ok(DecodedFundamentalsInputs { + mapping, + venues, + observations, + filings, + financials_docs_framed, + financials_bytes_read, + financials_peak_chunk_bytes, + financials_decode, + filings_docs_framed, + filings_bytes_read, + filings_peak_chunk_bytes, + filings_decode, + }) +} + +fn run_curate_fundamentals_from_openers( + args: &CurateFundamentalsArgs, + open_financials: FF, + open_filings: FL, +) -> Result +where + RF: io::Read, + FF: FnOnce() -> Result, + RL: io::Read, + FL: FnOnce() -> Result, +{ + let start = Instant::now(); + validate_out_dir_and_inputs(args)?; + + let decoded = decode_inputs_from_openers(args, open_financials, open_filings)?; + + let write_report = curate_and_write_fundamentals( + &args.out_dir, + decoded.observations, + decoded.filings, + &args.mapping_source, + &decoded.mapping, + &decoded.venues, + args.k, + FundamentalsPitWriteOptions::default(), + ) + .map_err(|source| RunCurateFundamentalsError::CurateWrite { + out_dir: args.out_dir.clone(), + source, + })?; + + Ok(CurateFundamentalsRunReport { + financials_docs_framed: decoded.financials_docs_framed, + financials_bytes_read: decoded.financials_bytes_read, + financials_peak_chunk_bytes: decoded.financials_peak_chunk_bytes, + financials_decode: decoded.financials_decode, + filings_docs_framed: decoded.filings_docs_framed, + filings_bytes_read: decoded.filings_bytes_read, + filings_peak_chunk_bytes: decoded.filings_peak_chunk_bytes, + filings_decode: decoded.filings_decode, + curate_stats: write_report.curate_stats, + write_stats: write_report.write_stats, + elapsed_secs: start.elapsed().as_secs_f64(), + }) +} + +/// Runs the end-to-end `curate-fundamentals` file-to-Parquet pipeline via +/// [`curate_and_write_fundamentals`]. +/// +/// Any validation, path-alias, I/O, TSV, mapping, BSON framing/corruption, or curation error +/// returns before touching `args.out_dir`, leaving any pre-existing +/// `/fundamentals_pit/` partitions byte-identical. +pub fn run_curate_fundamentals( + args: &CurateFundamentalsArgs, +) -> Result { + run_curate_fundamentals_from_openers( + args, + || { + File::open(&args.qm_financials).map_err(|source| { + RunCurateFundamentalsError::OpenInput { + label: "qm-financials", + path: args.qm_financials.clone(), + source, + } + }) + }, + || { + File::open(&args.qm_filings).map_err(|source| RunCurateFundamentalsError::OpenInput { + label: "qm-filings", + path: args.qm_filings.clone(), + source, + }) + }, + ) +} + +/// Runs `curate-fundamentals` from arbitrary raw-BSON [`io::Read`] streams while still running +/// full preflight validation (including output/input path safety against the diagnostic paths in +/// `args`) and loading `provider_mapping.tsv` / `listing_venues.tsv` from disk. +pub fn run_curate_fundamentals_with_readers( + args: &CurateFundamentalsArgs, + financials_reader: RF, + filings_reader: RL, +) -> Result { + run_curate_fundamentals_from_openers(args, || Ok(financials_reader), || Ok(filings_reader)) +} + +/// Formats [`CurateFundamentalsRunReport`] into a deterministic machine-readable `key=value` +/// summary. +/// +/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). +pub fn format_curate_fundamentals_report(report: &CurateFundamentalsRunReport) -> String { + let fin = &report.financials_decode; + let fil = &report.filings_decode; + let b = &report.curate_stats.build; + let c = &report.curate_stats; + let w = &report.write_stats; + + let mut years = String::new(); + for (idx, (year, count)) in w.rows_by_year.iter().enumerate() { + if idx > 0 { + years.push(' '); + } + let _ = write!(years, "{year:04}={count}"); + } + if years.is_empty() { + years.push_str("none"); + } + + format!( + "curate-etl curate-fundamentals\n\ + \x20 financials_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_period_end={} wrong_period_end_type={} invalid_period_end={} period_end_oor={} missing_report_period={} wrong_report_period_type={} unmapped_report_period={} wrong_report_date_type={} invalid_report_date={} report_date_oor={} missing_currency={} wrong_currency_type={} empty_currency={}) nulled=(missing_path={} wrong_type={} unparsable_string={} non_finite={})\n\ + \x20 filings_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_timefiled={} wrong_timefiled_type={} empty_timefiled={} missing_form_type={} wrong_form_type_type={} empty_form_type={}) nulled_wrong_type=(filing_id={} url={})\n\ + \x20 builder: observations_in={} rows_out={} keys_out={} linked={} statutory_lag={} dropped=(unknown_key={} non_finite={} date_oor={} report_date_not_after_period_end={} unanchored_vintage={} stale_estimate={}) dup_collapsed={} dup_conflict={} filings_in={} filings_eligible={} filings_dropped=(unknown_key={} non_periodic={} invalid_ts={} date_oor={} before_period_end={})\n\ + \x20 curate: observations_in={} obs_unmapped={} filings_in={} filings_unmapped={} filings_invalid_ts={} rows_out={} listings_out={}\n\ + \x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\ + \x20 years: {}\n\ + \x20 timing: elapsed_secs={:.6}", + report.financials_docs_framed, + report.financials_bytes_read, + report.financials_peak_chunk_bytes, + fin.docs_in, + fin.rows_out, + fin.skipped_total(), + fin.skipped_missing_key, + fin.skipped_wrong_key_type, + fin.skipped_empty_key, + fin.skipped_missing_period_end, + fin.skipped_wrong_period_end_type, + fin.skipped_invalid_period_end, + fin.skipped_period_end_out_of_range, + fin.skipped_missing_report_period, + fin.skipped_wrong_report_period_type, + fin.skipped_unmapped_report_period, + fin.skipped_wrong_report_date_type, + fin.skipped_invalid_report_date, + fin.skipped_report_date_out_of_range, + fin.skipped_missing_currency, + fin.skipped_wrong_currency_type, + fin.skipped_empty_currency, + fin.nulled_missing_path, + fin.nulled_wrong_type, + fin.nulled_unparsable_string, + fin.nulled_non_finite, + report.filings_docs_framed, + report.filings_bytes_read, + report.filings_peak_chunk_bytes, + fil.docs_in, + fil.rows_out, + fil.skipped_total(), + fil.skipped_missing_key, + fil.skipped_wrong_key_type, + fil.skipped_empty_key, + fil.skipped_missing_timefiled, + fil.skipped_wrong_timefiled_type, + fil.skipped_empty_timefiled, + fil.skipped_missing_form_type, + fil.skipped_wrong_form_type_type, + fil.skipped_empty_form_type, + fil.nulled_wrong_type_filing_id, + fil.nulled_wrong_type_url, + b.observations_in, + b.rows_out, + b.keys_out, + b.rows_linked_to_filing, + b.rows_statutory_lag_estimate, + b.observations_dropped_unknown_key, + b.observations_dropped_non_finite, + b.observations_dropped_date_out_of_range, + b.observations_dropped_report_date_not_after_period_end, + b.observations_dropped_unanchored_vintage, + b.observations_dropped_stale_estimate, + b.duplicate_collapsed, + b.duplicate_conflict_dropped, + b.filings_in, + b.filings_eligible, + b.filings_dropped_unknown_key, + b.filings_ignored_non_periodic, + b.filings_dropped_invalid_timestamp, + b.filings_dropped_date_out_of_range, + b.filings_dropped_before_period_end, + c.observations_in, + c.observations_dropped_unmapped, + c.filings_in, + c.filings_dropped_unmapped, + c.filings_dropped_invalid_timestamp, + c.rows_out, + c.listings_out, + w.files_written, + w.row_groups_written, + w.rows_written, + w.bytes_written, + years, + report.elapsed_secs, + ) +} + +#[cfg(test)] +#[path = "run_curate_fundamentals_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_curate_fundamentals_tests.rs b/tools/curate-etl/src/run_curate_fundamentals_tests.rs new file mode 100644 index 00000000..2964b549 --- /dev/null +++ b/tools/curate-etl/src/run_curate_fundamentals_tests.rs @@ -0,0 +1,2146 @@ +//! End-to-end fixture, PIT restatement, venue-lag, conservation, fail-closed, alias-safety, +//! empty-input, and TSV parser tests for `run_curate_fundamentals`. + +use std::collections::{BTreeMap, HashMap}; +use std::error::Error as _; +use std::fs::{self, File}; +use std::io::{self, Cursor, Read}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + +use bson::raw::{cstr, RawDocumentBuf}; +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::{ + format_curate_fundamentals_report, load_listing_venues_tsv, run_curate_fundamentals, + run_curate_fundamentals_with_readers, CurateFundamentalsArgs, CurateFundamentalsFiscalPeriod, + CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, +}; +use crate::bson_qm_events::decode_qm_filing_buffer; +use crate::bson_qm_financials::decode_qm_financials_buffer; +use crate::bson_stream::BsonStreamError; +use crate::curate_fundamentals::curate_fundamentals; +use crate::events::{ + partition_year_utc, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::fundamentals::{ + FinancialObservation, FundamentalsFields, FUNDAMENTALS_FALLBACK_HOUR_ET, + FUNDAMENTALS_FALLBACK_MINUTE_ET, STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, + STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, STATUTORY_LAG_US_TSX_ANNUAL_DAYS, + STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, +}; +use crate::parquet_fundamentals::FundamentalsPitParquetRow; +use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; +use crate::run_curate_bars::load_provider_mapping_tsv; +use crate::shorts::et_to_utc_micros; +use crate::split::ymd_to_epoch_days; + +static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDirGuard { + path: PathBuf, +} + +impl TempDirGuard { + fn new(label: &str) -> Self { + let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let pid = std::process::id(); + let path = std::env::temp_dir().join(format!( + "curate-etl-run-curate-fundamentals-{label}-{pid}-{seq}" + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum TreeEntry { + Dir, + File(Vec), + Symlink(PathBuf), +} + +fn snapshot_tree(root: &Path) -> BTreeMap { + let mut out = BTreeMap::new(); + if !root.exists() && fs::symlink_metadata(root).is_err() { + return out; + } + fn walk(base: &Path, cur: &Path, out: &mut BTreeMap) { + let meta = fs::symlink_metadata(cur).expect("symlink_metadata"); + let rel = cur.strip_prefix(base).unwrap_or(cur).to_path_buf(); + if meta.file_type().is_symlink() { + let target = fs::read_link(cur).expect("read_link"); + out.insert(rel, TreeEntry::Symlink(target)); + } else if meta.is_dir() { + out.insert(rel, TreeEntry::Dir); + let mut children: Vec = fs::read_dir(cur) + .expect("read_dir") + .map(|e| e.expect("dir entry").path()) + .collect(); + children.sort(); + for child in children { + walk(base, &child, out); + } + } else { + let bytes = fs::read(cur).expect("read file"); + out.insert(rel, TreeEntry::File(bytes)); + } + } + walk(root, root, &mut out); + out +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid test date") +} + +fn make_financials_doc( + key: Option<&str>, + period_end: &str, + report_date: Option<&str>, + report_period: &str, + currency: &str, + fields: FundamentalsFields, +) -> Vec { + let mut doc = RawDocumentBuf::new(); + if let Some(k) = key { + doc.append(cstr!("qmSearchCode"), k); + } + doc.append(cstr!("periodEndDate"), period_end); + if let Some(rd) = report_date { + doc.append(cstr!("reportDate"), rd); + } + 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: Option<&str>, + timefiled: &str, + form_type: &str, + filing_id: Option<&str>, + url: Option<&str>, +) -> Vec { + let mut doc = RawDocumentBuf::new(); + if let Some(k) = key { + doc.append(cstr!("symbol"), k); + } + doc.append(cstr!("timefiled"), timefiled); + doc.append(cstr!("formType"), form_type); + if let Some(id) = filing_id { + doc.append(cstr!("filingId"), id); + } + if let Some(u) = url { + doc.append(cstr!("url"), u); + } + doc.into_bytes() +} + +fn default_test_args( + qm_financials: PathBuf, + qm_filings: PathBuf, + provider_mapping: PathBuf, + listing_venues: PathBuf, + out_dir: PathBuf, +) -> CurateFundamentalsArgs { + let mut args = CurateFundamentalsArgs::with_verified_defaults( + qm_financials, + qm_filings, + provider_mapping, + listing_venues, + out_dir, + "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, + ); + args.filings_filing_id_field = Some("filingId".to_string()); + args.filings_url_field = Some("url".to_string()); + args +} + +#[derive(Debug, Clone, PartialEq)] +struct DecodedParquetRow { + listing_id: i32, + effective_known_at: i64, + known_at_source: String, + has_estimated_lag: bool, + period_end: i32, + fiscal_period: String, + currency: String, + period_known_at: i64, + revenue: Option, + net_income: Option, + operating_cash_flow: Option, + total_assets: Option, + total_equity: Option, + shares_outstanding: Option, + ttm_period_end: Option, + ttm_currency: Option, + ttm_revenue: Option, + ttm_net_income: Option, + ttm_operating_cash_flow: Option, + ttm_has_estimated_lag: Option, +} + +fn from_stage_row(row: &FundamentalsPitParquetRow) -> DecodedParquetRow { + let lp = row.latest_period().expect("latest_period"); + DecodedParquetRow { + listing_id: row.listing_id, + effective_known_at: row.effective_known_at_micros, + known_at_source: row.known_at_source.as_ref().to_string(), + has_estimated_lag: row.has_estimated_lag, + period_end: lp.period_end, + fiscal_period: lp.fiscal_period.as_ref().to_string(), + currency: lp.currency.clone(), + period_known_at: lp.period_known_at_micros, + revenue: lp.fields.revenue, + net_income: lp.fields.net_income, + operating_cash_flow: lp.fields.operating_cash_flow, + total_assets: lp.fields.total_assets, + total_equity: lp.fields.total_equity, + shares_outstanding: lp.fields.shares_outstanding, + ttm_period_end: row.ttm.as_ref().map(|t| t.ending_period_end), + ttm_currency: row.ttm.as_ref().map(|t| t.currency.clone()), + ttm_revenue: row.ttm.as_ref().and_then(|t| t.flows.revenue), + ttm_net_income: row.ttm.as_ref().and_then(|t| t.flows.net_income), + ttm_operating_cash_flow: row.ttm.as_ref().and_then(|t| t.flows.operating_cash_flow), + ttm_has_estimated_lag: row.ttm.as_ref().map(|t| t.has_estimated_lag), + } +} + +fn read_parquet_rows_by_name(path: &Path) -> Vec { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let meta = reader.metadata(); + let schema_descr = meta.file_metadata().schema_descr(); + + let mut col_idx_by_name: HashMap<&str, usize> = HashMap::new(); + for (idx, col) in schema_descr.columns().iter().enumerate() { + col_idx_by_name.insert(col.name(), idx); + } + let col_idx = |name: &str| -> usize { + *col_idx_by_name + .get(name) + .unwrap_or_else(|| panic!("missing expected Parquet column '{name}'")) + }; + + let mut out = Vec::new(); + for rg_idx in 0..meta.num_row_groups() { + let rg_meta = meta.row_group(rg_idx); + for c in 0..rg_meta.num_columns() { + assert_eq!( + rg_meta.column(c).compression(), + Compression::ZSTD(Default::default()), + "expected Zstd compression on column {c}" + ); + } + + let rg_rows = rg_meta.num_rows() as usize; + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + + let read_req_i32 = |name: &str| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 for '{name}'"), + } + vals + }; + + let read_opt_i32 = |name: &str| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::Int32ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT32 for '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_i64 = |name: &str| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::Int64ColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected INT64 for '{name}'"), + } + vals + }; + + let read_req_bool = |name: &str| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN for '{name}'"), + } + vals + }; + + let read_opt_bool = |name: &str| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::BoolColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BOOLEAN for '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_opt_f64 = |name: &str| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::DoubleColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected DOUBLE for '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = vals[vi]; + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let read_req_str = |name: &str| -> Vec { + let mut vals = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, None, None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY for '{name}'"), + } + vals.into_iter() + .map(|ba| String::from_utf8(ba.data().to_vec()).unwrap()) + .collect() + }; + + let read_opt_str = |name: &str| -> Vec> { + let mut vals = Vec::with_capacity(rg_rows); + let mut defs = Vec::with_capacity(rg_rows); + match rg_reader.get_column_reader(col_idx(name)).unwrap() { + ColumnReader::ByteArrayColumnReader(mut typed) => { + let mut read = 0usize; + while read < rg_rows { + let (n, _, _) = typed + .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) + .unwrap(); + assert!(n > 0); + read += n; + } + } + _ => panic!("expected BYTE_ARRAY for '{name}'"), + } + let mut vi = 0usize; + defs.into_iter() + .map(|d| { + if d == 1 { + let v = String::from_utf8(vals[vi].data().to_vec()).unwrap(); + vi += 1; + Some(v) + } else { + assert_eq!(d, 0); + None + } + }) + .collect() + }; + + let listing_id = read_req_i32("listing_id"); + let effective_known_at = read_req_i64("effective_known_at"); + let known_at_source = read_req_str("known_at_source"); + let has_estimated_lag = read_req_bool("has_estimated_lag"); + let period_end = read_req_i32("period_end"); + let fiscal_period = read_req_str("fiscal_period"); + let currency = read_req_str("currency"); + let period_known_at = read_req_i64("period_known_at"); + let revenue = read_opt_f64("revenue"); + let net_income = read_opt_f64("net_income"); + let operating_cash_flow = read_opt_f64("operating_cash_flow"); + let total_assets = read_opt_f64("total_assets"); + let total_equity = read_opt_f64("total_equity"); + let shares_outstanding = read_opt_f64("shares_outstanding"); + let ttm_period_end = read_opt_i32("ttm_period_end"); + let ttm_currency = read_opt_str("ttm_currency"); + let ttm_revenue = read_opt_f64("ttm_revenue"); + let ttm_net_income = read_opt_f64("ttm_net_income"); + let ttm_operating_cash_flow = read_opt_f64("ttm_operating_cash_flow"); + let ttm_has_estimated_lag = read_opt_bool("ttm_has_estimated_lag"); + + for i in 0..rg_rows { + out.push(DecodedParquetRow { + listing_id: listing_id[i], + effective_known_at: effective_known_at[i], + known_at_source: known_at_source[i].clone(), + has_estimated_lag: has_estimated_lag[i], + period_end: period_end[i], + fiscal_period: fiscal_period[i].clone(), + currency: currency[i].clone(), + period_known_at: period_known_at[i], + revenue: revenue[i], + net_income: net_income[i], + operating_cash_flow: operating_cash_flow[i], + total_assets: total_assets[i], + total_equity: total_equity[i], + shares_outstanding: shares_outstanding[i], + ttm_period_end: ttm_period_end[i], + ttm_currency: ttm_currency[i].clone(), + ttm_revenue: ttm_revenue[i], + ttm_net_income: ttm_net_income[i], + ttm_operating_cash_flow: ttm_operating_cash_flow[i], + ttm_has_estimated_lag: ttm_has_estimated_lag[i], + }); + } + } + out +} + +fn read_dataset_by_year(out_dir: &Path) -> BTreeMap> { + let dataset_dir = out_dir.join("fundamentals_pit"); + let mut by_year = BTreeMap::new(); + if !dataset_dir.exists() { + return by_year; + } + for entry in fs::read_dir(&dataset_dir).expect("read dataset dir") { + let entry = entry.expect("dir entry"); + let name = entry.file_name().to_string_lossy().to_string(); + if let Some(year_str) = name.strip_prefix("year=") { + let year: i32 = year_str.parse().expect("valid year dir"); + let part = entry.path().join("part.parquet"); + assert!(part.is_file(), "expected part.parquet in {}", entry.path().display()); + by_year.insert(year, read_parquet_rows_by_name(&part)); + } + } + by_year +} + +fn assert_single_line(msg: &str) { + assert!( + !msg.contains('\n') && !msg.contains('\r'), + "error Display must be single-line, got: {msg:?}" + ); +} + +fn assert_reports_eq_ignoring_timing( + a: &CurateFundamentalsRunReport, + b: &CurateFundamentalsRunReport, +) { + assert_eq!(a.financials_docs_framed, b.financials_docs_framed); + assert_eq!(a.financials_bytes_read, b.financials_bytes_read); + assert_eq!(a.financials_peak_chunk_bytes, b.financials_peak_chunk_bytes); + assert_eq!(a.financials_decode, b.financials_decode); + assert_eq!(a.filings_docs_framed, b.filings_docs_framed); + assert_eq!(a.filings_bytes_read, b.filings_bytes_read); + assert_eq!(a.filings_peak_chunk_bytes, b.filings_peak_chunk_bytes); + assert_eq!(a.filings_decode, b.filings_decode); + assert_eq!(a.curate_stats, b.curate_stats); + assert_eq!(a.write_stats, b.write_stats); +} + +fn assert_conservation(report: &CurateFundamentalsRunReport) { + assert_eq!( + report.financials_docs_framed as usize, + report.financials_decode.docs_in + ); + assert_eq!( + report.financials_decode.docs_in, + report.financials_decode.rows_out + report.financials_decode.skipped_total() + ); + assert_eq!( + report.filings_docs_framed as usize, + report.filings_decode.docs_in + ); + assert_eq!( + report.filings_decode.docs_in, + report.filings_decode.rows_out + report.filings_decode.skipped_total() + ); + assert_eq!( + report.financials_decode.rows_out, + report.curate_stats.observations_in + ); + assert_eq!( + report.filings_decode.rows_out, + report.curate_stats.filings_in + ); + assert_eq!( + report.write_stats.rows_written, + report.curate_stats.rows_out + ); +} + +#[test] +fn fundamentals_two_listing_parquet_matches_stage() { + let tmp = TempDirGuard::new("two-listing"); + let fin_path = tmp.path().join("qmFinancials.bson"); + let fil_path = tmp.path().join("qmFilings.bson"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let venues_path = tmp.path().join("listing_venues.tsv"); + let out_file_api = tmp.path().join("out_file"); + let out_reader_api = tmp.path().join("out_reader"); + + // 2 listings: 101 (NVDA, us_tsx, USD) with 4 consecutive quarters spanning 2023-2024 so TTM + // is populated, plus 202 (MINE:V, tsxv_cse, CAD) with a nullable stock metric and unlinked FY. + fs::write( + &map_path, + "qm\tNVDA\t2020-01-01\t\t101\nqm\tMINE:V\t2020-01-01\t\t202\n", + ) + .unwrap(); + // Include both LF and CRLF line endings in the valid venue fixture. + fs::write(&venues_path, "101\tus_tsx\r\n202\ttsxv_cse\n").unwrap(); + + let mut fin_bytes = Vec::new(); + // 4 consecutive quarters for NVDA (Q1 2023 .. Q4 2023), filed across 2023 and 2024. + fin_bytes.extend_from_slice(&make_financials_doc( + Some("NVDA"), + "2023-03-31", + Some("2023-05-02"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(100.0), + net_income: Some(20.0), + operating_cash_flow: Some(25.0), + total_assets: Some(1000.0), + total_equity: Some(600.0), + shares_outstanding: Some(50.0), + }, + )); + fin_bytes.extend_from_slice(&make_financials_doc( + Some("NVDA"), + "2023-06-30", + Some("2023-08-03"), + "Q2", + "USD", + FundamentalsFields { + revenue: Some(110.0), + net_income: Some(22.0), + operating_cash_flow: Some(28.0), + total_assets: Some(1050.0), + total_equity: Some(620.0), + shares_outstanding: Some(50.0), + }, + )); + fin_bytes.extend_from_slice(&make_financials_doc( + Some("NVDA"), + "2023-09-30", + Some("2023-11-04"), + "Q3", + "USD", + FundamentalsFields { + revenue: Some(120.0), + net_income: Some(24.0), + operating_cash_flow: Some(30.0), + total_assets: Some(1100.0), + total_equity: Some(640.0), + shares_outstanding: Some(51.0), + }, + )); + fin_bytes.extend_from_slice(&make_financials_doc( + Some("NVDA"), + "2023-12-31", + Some("2024-02-10"), + "Q4", + "USD", + FundamentalsFields { + revenue: Some(130.0), + net_income: Some(26.0), + operating_cash_flow: Some(32.0), + total_assets: Some(1150.0), + total_equity: Some(660.0), + shares_outstanding: Some(51.0), + }, + )); + // Listing 202 (MINE:V): Q1 2024 linked to SEDAR interim filing, with nullable total_equity. + fin_bytes.extend_from_slice(&make_financials_doc( + Some("MINE:V"), + "2024-03-31", + Some("2024-05-20"), + "Q1", + "CAD", + FundamentalsFields { + revenue: Some(5.5), + net_income: Some(-1.2), + operating_cash_flow: None, + total_assets: Some(40.0), + total_equity: None, + shares_outstanding: Some(120.0), + }, + )); + fs::write(&fin_path, &fin_bytes).unwrap(); + + let mut fil_bytes = Vec::new(); + fil_bytes.extend_from_slice(&make_filing_doc( + Some("NVDA"), + "2023-05-02T16:15:00 EDT", + "10-Q", + Some("f-q1"), + Some("https://example.test/q1"), + )); + fil_bytes.extend_from_slice(&make_filing_doc( + Some("NVDA"), + "2023-08-03T16:20:00 EDT", + "10-Q", + Some("f-q2"), + None, + )); + fil_bytes.extend_from_slice(&make_filing_doc( + Some("NVDA"), + "2023-11-04T16:30:00 EDT", + "10-Q", + Some("f-q3"), + None, + )); + fil_bytes.extend_from_slice(&make_filing_doc( + Some("NVDA"), + "2024-02-10T16:05:00 EST", + "10-Q", + Some("f-q4"), + None, + )); + fil_bytes.extend_from_slice(&make_filing_doc( + Some("MINE:V"), + "2024-05-20T09:00:00 EDT", + "Interim financial statements/report - English", + Some("f-mine-q1"), + None, + )); + fs::write(&fil_path, &fil_bytes).unwrap(); + + // Run via public file API. + let file_args = default_test_args( + fin_path.clone(), + fil_path.clone(), + map_path.clone(), + venues_path.clone(), + out_file_api.clone(), + ); + let file_report = run_curate_fundamentals(&file_args).expect("file API run"); + assert_conservation(&file_report); + assert_eq!(file_report.curate_stats.listings_out, 2); + assert_eq!(file_report.write_stats.rows_written, 5); + + // Build expected rows directly via curate_fundamentals on the same decoded inputs. + let mut direct_obs = Vec::new(); + file_args.fiscal_period.with_borrowed(|fp| { + decode_qm_financials_buffer(&fin_bytes, &file_args.financials_field_names(), fp, |o| { + direct_obs.push(FinancialObservation { + key: o.key.to_owned(), + period_end: o.period_end, + fiscal_period: o.fiscal_period, + currency: o.currency, + report_date: o.report_date, + fields: o.fields, + }); + }) + .unwrap(); + }); + let mut direct_filings = Vec::new(); + decode_qm_filing_buffer(&fil_bytes, &file_args.filings_field_names(), |raw| { + direct_filings.push(raw.to_qm_filing(raw.key.to_owned())); + }) + .unwrap(); + let mapping = ProviderMappingTable::from_rows(load_provider_mapping_tsv(&map_path).unwrap()) + .unwrap(); + let venues = load_listing_venues_tsv(&venues_path).unwrap(); + let stage_out = curate_fundamentals( + direct_obs, + direct_filings, + DEFAULT_FUNDAMENTALS_MAPPING_SOURCE, + &mapping, + &venues, + file_args.k, + ) + .unwrap(); + + let mut expected_by_year: BTreeMap> = BTreeMap::new(); + for row in &stage_out.rows { + let year = partition_year_utc(row.effective_known_at_micros); + expected_by_year + .entry(year) + .or_default() + .push(from_stage_row(row)); + } + + let got_by_year = read_dataset_by_year(&out_file_api); + assert_eq!(got_by_year.keys().copied().collect::>(), vec![2023, 2024]); + assert_eq!(got_by_year, expected_by_year); + + // Verify 4-quarter TTM is populated on the 2024 NVDA Q4 row and nulls are preserved on MINE:V. + let rows_2024 = &got_by_year[&2024]; + let nvda_q4 = rows_2024 + .iter() + .find(|r| r.listing_id == 101) + .expect("NVDA 2024 row"); + assert_eq!(nvda_q4.currency, "USD"); + assert_eq!(nvda_q4.ttm_period_end, Some(day(2023, 12, 31))); + assert_eq!(nvda_q4.ttm_currency.as_deref(), Some("USD")); + assert_eq!(nvda_q4.ttm_revenue, Some(460.0)); + assert_eq!(nvda_q4.ttm_net_income, Some(92.0)); + assert_eq!(nvda_q4.ttm_operating_cash_flow, Some(115.0)); + assert_eq!(nvda_q4.ttm_has_estimated_lag, Some(false)); + assert_eq!(nvda_q4.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + + let mine_q1 = rows_2024 + .iter() + .find(|r| r.listing_id == 202) + .expect("MINE:V 2024 row"); + assert_eq!(mine_q1.currency, "CAD"); + assert_eq!(mine_q1.operating_cash_flow, None); + assert_eq!(mine_q1.total_equity, None); + assert_eq!(mine_q1.ttm_period_end, None); + + // Run the exact same pinned fixture through the injected-reader entry point. + let reader_args = default_test_args( + fin_path, + fil_path, + map_path, + venues_path, + out_reader_api.clone(), + ); + let reader_report = run_curate_fundamentals_with_readers( + &reader_args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .expect("reader API run"); + assert_reports_eq_ignoring_timing(&file_report, &reader_report); + assert_eq!(read_dataset_by_year(&out_reader_api), got_by_year); +} + +#[test] +fn fundamentals_late_q1_restatement_preserves_q2() { + let tmp = TempDirGuard::new("restatement"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let venues_path = tmp.path().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(); + + let q1_orig = make_financials_doc( + Some("ACME"), + "2024-03-31", + Some("2024-05-05"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(100.0), + net_income: Some(10.0), + operating_cash_flow: Some(12.0), + total_assets: Some(500.0), + total_equity: Some(300.0), + shares_outstanding: Some(20.0), + }, + ); + let q2_orig = make_financials_doc( + Some("ACME"), + "2024-06-30", + Some("2024-08-05"), + "Q2", + "USD", + FundamentalsFields { + revenue: Some(250.0), + net_income: Some(30.0), + operating_cash_flow: Some(35.0), + total_assets: Some(550.0), + total_equity: Some(330.0), + shares_outstanding: Some(20.0), + }, + ); + let q1_restated = make_financials_doc( + Some("ACME"), + "2024-03-31", + Some("2024-09-15"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(88.0), + net_income: Some(4.0), + operating_cash_flow: Some(9.0), + total_assets: Some(490.0), + total_equity: Some(294.0), + shares_outstanding: Some(20.0), + }, + ); + + let f_q1 = make_filing_doc( + Some("ACME"), + "2024-05-05T16:10:00 EDT", + "10-Q", + Some("q1-1"), + None, + ); + let f_q2 = make_filing_doc( + Some("ACME"), + "2024-08-05T16:15:00 EDT", + "10-Q", + Some("q2-1"), + None, + ); + let f_q1_amend = make_filing_doc( + Some("ACME"), + "2024-09-15T17:00:00 EDT", + "10-Q/A", + Some("q1-2"), + None, + ); + + // Run 1: Q1 + Q2 only. + let fin_before = tmp.path().join("fin_before.bson"); + let fil_before = tmp.path().join("fil_before.bson"); + let out_before = tmp.path().join("out_before"); + fs::write(&fin_before, [&q1_orig[..], &q2_orig[..]].concat()).unwrap(); + fs::write(&fil_before, [&f_q1[..], &f_q2[..]].concat()).unwrap(); + let args_before = default_test_args( + fin_before, + fil_before, + map_path.clone(), + venues_path.clone(), + out_before.clone(), + ); + let rep_before = run_curate_fundamentals(&args_before).unwrap(); + assert_eq!(rep_before.write_stats.rows_written, 2); + let rows_before = read_dataset_by_year(&out_before) + .remove(&2024) + .expect("2024 partition"); + assert_eq!(rows_before.len(), 2); + + // Run 2: Q1 + Q2 + late Q1 restatement (known_at > Q2's known_at). + let fin_after = tmp.path().join("fin_after.bson"); + let fil_after = tmp.path().join("fil_after.bson"); + let out_after = tmp.path().join("out_after"); + fs::write( + &fin_after, + [&q1_orig[..], &q2_orig[..], &q1_restated[..]].concat(), + ) + .unwrap(); + fs::write( + &fil_after, + [&f_q1[..], &f_q2[..], &f_q1_amend[..]].concat(), + ) + .unwrap(); + let args_after = default_test_args( + fin_after, + fil_after, + map_path, + venues_path, + out_after.clone(), + ); + let rep_after = run_curate_fundamentals(&args_after).unwrap(); + assert_eq!(rep_after.write_stats.rows_written, 3); + let rows_after = read_dataset_by_year(&out_after) + .remove(&2024) + .expect("2024 partition"); + assert_eq!(rows_after.len(), 3); + + // Entire pre-amendment prefix is byte/value-identical (zero look-ahead leakage). + assert_eq!(&rows_after[..2], &rows_before[..]); + + // Third snapshot is at the amendment's UTC known_at (2024-09-15 17:00 EDT = 21:00 UTC), + // and Q2 remains the latest period (period_end, values, and period_known_at unchanged). + let amend_row = &rows_after[2]; + let q2_row = &rows_before[1]; + let expected_amend_utc = et_to_utc_micros(day(2024, 9, 15), 17, 0, 0).unwrap(); + assert_eq!(amend_row.effective_known_at, expected_amend_utc); + assert!(amend_row.effective_known_at > q2_row.effective_known_at); + assert_eq!(amend_row.period_end, day(2024, 6, 30)); + assert_eq!(amend_row.period_end, q2_row.period_end); + assert_eq!(amend_row.period_known_at, q2_row.period_known_at); + assert_eq!(amend_row.revenue, q2_row.revenue); + assert_eq!(amend_row.net_income, q2_row.net_income); + assert_eq!(amend_row.operating_cash_flow, q2_row.operating_cash_flow); + assert_eq!(amend_row.total_assets, q2_row.total_assets); + assert_eq!(amend_row.total_equity, q2_row.total_equity); + assert_eq!(amend_row.shares_outstanding, q2_row.shares_outstanding); +} + +#[test] +fn fundamentals_unlinked_uses_venue_lag() { + let tmp = TempDirGuard::new("venue-lag"); + let fin_path = tmp.path().join("qmFinancials.bson"); + let fil_path = tmp.path().join("qmFilings.bson"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let venues_path = tmp.path().join("listing_venues.tsv"); + let out_dir = tmp.path().join("out"); + + fs::write( + &map_path, + "qm\tUSCO\t2020-01-01\t\t10\nqm\tVNCO:V\t2020-01-01\t\t20\n", + ) + .unwrap(); + fs::write(&venues_path, "10\tus_tsx\n20\ttsxv_cse\n").unwrap(); + + let q_end = day(2024, 3, 31); + let fy_end = day(2024, 12, 31); + let mut fin_bytes = Vec::new(); + for (sym, ccy) in [("USCO", "USD"), ("VNCO:V", "CAD")] { + fin_bytes.extend_from_slice(&make_financials_doc( + Some(sym), + "2024-03-31", + None, + "Q1", + ccy, + FundamentalsFields { + revenue: Some(50.0), + ..Default::default() + }, + )); + fin_bytes.extend_from_slice(&make_financials_doc( + Some(sym), + "2024-12-31", + None, + "FY", + ccy, + FundamentalsFields { + revenue: Some(200.0), + ..Default::default() + }, + )); + } + fs::write(&fin_path, &fin_bytes).unwrap(); + // Empty filings dump -> all 4 observations must use statutory_lag_estimate. + fs::write(&fil_path, []).unwrap(); + + let args = default_test_args(fin_path, fil_path, map_path, venues_path, out_dir.clone()); + let report = run_curate_fundamentals(&args).unwrap(); + assert_conservation(&report); + assert_eq!(report.curate_stats.build.rows_linked_to_filing, 0); + assert_eq!(report.curate_stats.build.rows_statutory_lag_estimate, 4); + + let by_year = read_dataset_by_year(&out_dir); + let rows_2024 = &by_year[&2024]; + let rows_2025 = &by_year[&2025]; + + let expected_us_q = et_to_utc_micros( + q_end + STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, + FUNDAMENTALS_FALLBACK_HOUR_ET, + FUNDAMENTALS_FALLBACK_MINUTE_ET, + 0, + ) + .unwrap(); + let expected_tsxv_q = et_to_utc_micros( + q_end + STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, + FUNDAMENTALS_FALLBACK_HOUR_ET, + FUNDAMENTALS_FALLBACK_MINUTE_ET, + 0, + ) + .unwrap(); + let expected_us_fy = et_to_utc_micros( + fy_end + STATUTORY_LAG_US_TSX_ANNUAL_DAYS, + FUNDAMENTALS_FALLBACK_HOUR_ET, + FUNDAMENTALS_FALLBACK_MINUTE_ET, + 0, + ) + .unwrap(); + let expected_tsxv_fy = et_to_utc_micros( + fy_end + STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, + FUNDAMENTALS_FALLBACK_HOUR_ET, + FUNDAMENTALS_FALLBACK_MINUTE_ET, + 0, + ) + .unwrap(); + + assert_ne!(expected_us_q, expected_tsxv_q); + assert_ne!(expected_us_fy, expected_tsxv_fy); + + let us_q = rows_2024.iter().find(|r| r.listing_id == 10).unwrap(); + let tsxv_q = rows_2024.iter().find(|r| r.listing_id == 20).unwrap(); + let us_fy = rows_2025.iter().find(|r| r.listing_id == 10).unwrap(); + let tsxv_fy = rows_2025.iter().find(|r| r.listing_id == 20).unwrap(); + + for (row, expected_ts) in [ + (us_q, expected_us_q), + (tsxv_q, expected_tsxv_q), + (us_fy, expected_us_fy), + (tsxv_fy, expected_tsxv_fy), + ] { + assert_eq!(row.effective_known_at, expected_ts); + assert_eq!(row.period_known_at, expected_ts); + assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(row.has_estimated_lag); + } +} + +#[test] +fn fundamentals_report_conserves_counters() { + let tmp = TempDirGuard::new("conservation"); + let fin_path = tmp.path().join("qmFinancials.bson"); + let fil_path = tmp.path().join("qmFilings.bson"); + let map_path = tmp.path().join("provider_mapping.tsv"); + let venues_path = tmp.path().join("listing_venues.tsv"); + let out_dir = tmp.path().join("out"); + + fs::write(&map_path, "qm\tKNOWN\t2020-01-01\t\t401\n").unwrap(); + fs::write(&venues_path, "401\tus_tsx\n").unwrap(); + + let mut fin_bytes = Vec::new(); + // 1. Emitted & mapped + fin_bytes.extend_from_slice(&make_financials_doc( + Some("KNOWN"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(10.0), + ..Default::default() + }, + )); + // 2. Skipped at BSON decode (missing key) + fin_bytes.extend_from_slice(&make_financials_doc( + None, + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields::default(), + )); + // 3. Emitted at BSON decode, dropped unmapped at stage + fin_bytes.extend_from_slice(&make_financials_doc( + Some("UNMAPPED"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(20.0), + ..Default::default() + }, + )); + fs::write(&fin_path, &fin_bytes).unwrap(); + + let mut fil_bytes = Vec::new(); + // 1. Emitted & mapped + fil_bytes.extend_from_slice(&make_filing_doc( + Some("KNOWN"), + "2024-05-01T16:10:00 EDT", + "10-Q", + Some("f1"), + None, + )); + // 2. Skipped at BSON decode (missing key) + fil_bytes.extend_from_slice(&make_filing_doc( + None, + "2024-05-01T16:10:00 EDT", + "10-Q", + None, + None, + )); + // 3. Emitted at BSON decode, dropped unmapped at stage + fil_bytes.extend_from_slice(&make_filing_doc( + Some("UNMAPPED"), + "2024-05-01T16:10:00 EDT", + "10-Q", + None, + None, + )); + // 4. Emitted at BSON decode, dropped invalid timestamp at stage + fil_bytes.extend_from_slice(&make_filing_doc( + Some("KNOWN"), + "not-a-timestamp", + "10-Q", + None, + None, + )); + fs::write(&fil_path, &fil_bytes).unwrap(); + + let args = default_test_args(fin_path, fil_path, map_path, venues_path, out_dir); + let report = run_curate_fundamentals(&args).unwrap(); + + assert_conservation(&report); + assert_eq!(report.financials_docs_framed, 3); + assert_eq!(report.financials_bytes_read, fin_bytes.len() as u64); + assert_eq!(report.financials_decode.rows_out, 2); + assert_eq!(report.financials_decode.skipped_missing_key, 1); + assert_eq!(report.curate_stats.observations_in, 2); + assert_eq!(report.curate_stats.observations_dropped_unmapped, 1); + + assert_eq!(report.filings_docs_framed, 4); + assert_eq!(report.filings_bytes_read, fil_bytes.len() as u64); + assert_eq!(report.filings_decode.rows_out, 3); + assert_eq!(report.filings_decode.skipped_missing_key, 1); + assert_eq!(report.curate_stats.filings_in, 3); + assert_eq!(report.curate_stats.filings_dropped_unmapped, 1); + assert_eq!(report.curate_stats.filings_dropped_invalid_timestamp, 1); + + assert_eq!(report.curate_stats.rows_out, 1); + assert_eq!(report.write_stats.rows_written, 1); + + let formatted = format_curate_fundamentals_report(&report); + for section in [ + "curate-etl curate-fundamentals", + "financials_bson:", + "filings_bson:", + "builder:", + "curate:", + "write:", + "years:", + "timing:", + "2024=1", + ] { + assert!( + formatted.contains(section), + "formatted report missing '{section}':\n{formatted}" + ); + } +} + +#[test] +fn fundamentals_failures_preserve_output_tree() { + let tmp = TempDirGuard::new("fail-closed"); + let valid_fin = tmp.path().join("valid_fin.bson"); + let valid_fil = tmp.path().join("valid_fil.bson"); + let valid_map = tmp.path().join("valid_map.tsv"); + let valid_venues = tmp.path().join("valid_venues.tsv"); + + fs::write(&valid_map, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); + fs::write(&valid_venues, "101\tus_tsx\n").unwrap(); + let fin_doc = make_financials_doc( + Some("NVDA"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(100.0), + ..Default::default() + }, + ); + let fil_doc = make_filing_doc( + Some("NVDA"), + "2024-05-01T16:10:00 EDT", + "10-Q", + Some("f1"), + None, + ); + fs::write(&valid_fin, &fin_doc).unwrap(); + fs::write(&valid_fil, &fil_doc).unwrap(); + + // Seed a pre-existing partition in out_existing so we verify byte-for-byte preservation. + let out_existing = tmp.path().join("out_existing"); + let seed_args = default_test_args( + valid_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + out_existing.clone(), + ); + run_curate_fundamentals(&seed_args).expect("seed existing output"); + let existing_before = snapshot_tree(&out_existing); + assert!(existing_before.len() >= 3); + + // Also test against a missing output directory that must remain absent. + let out_missing = tmp.path().join("out_missing"); + assert!(!out_missing.exists()); + + let assert_preserved = |out_dir: &Path, expected: &BTreeMap| { + assert_eq!( + &snapshot_tree(out_dir), + expected, + "output tree {} was mutated on failure", + out_dir.display() + ); + }; + + for (out_dir, before) in [ + (out_existing.as_path(), existing_before.clone()), + (out_missing.as_path(), BTreeMap::new()), + ] { + let base = || { + default_test_args( + valid_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + out_dir.to_path_buf(), + ) + }; + + // 1. Invalid financials field path + let mut a = base(); + a.financials_revenue_field = Some("IncomeStatement..revenue".to_string()); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::InvalidFinancialsConfig { .. } + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 2. Invalid filings field name + let mut a = base(); + a.filings_form_type_field = " ".to_string(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::InvalidFilingsFieldNames { .. } + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 3. Invalid fiscal policy (blank token & overlapping tokens) + let mut a = base(); + a.fiscal_period = CurateFundamentalsFiscalPeriod::ByTokens { + quarterly: vec!["Q1".to_string(), " ".to_string()], + annual: vec!["FY".to_string()], + }; + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::InvalidFinancialsConfig { .. } + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let mut a = base(); + a.fiscal_period = CurateFundamentalsFiscalPeriod::ByTokens { + quarterly: vec!["FY".to_string()], + annual: vec!["FY".to_string()], + }; + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::InvalidFinancialsConfig { .. } + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 4. Blank mapping source + let mut a = base(); + a.mapping_source = " \t ".to_string(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::EmptyMappingSource + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 5. Zero k + let mut a = base(); + a.k = 0; + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::InvalidPeriodLimit { k: 0 } + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 6. Unreadable / missing files for all four inputs + let missing_fin = tmp.path().join("no_such_fin.bson"); + let mut a = base(); + a.qm_financials = missing_fin.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::OpenInput { + label: "qm-financials", + ref path, + .. + } if path == &missing_fin + )); + assert!(err.to_string().contains(&missing_fin.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let missing_fil = tmp.path().join("no_such_fil.bson"); + let mut a = base(); + a.qm_filings = missing_fil.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::OpenInput { + label: "qm-filings", + ref path, + .. + } if path == &missing_fil + )); + assert!(err.to_string().contains(&missing_fil.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let missing_map = tmp.path().join("no_such_map.tsv"); + let mut a = base(); + a.provider_mapping = missing_map.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::OpenInput { ref path, .. } if path == &missing_map + )); + assert!(err.to_string().contains(&missing_map.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let missing_venues = tmp.path().join("no_such_venues.tsv"); + let mut a = base(); + a.listing_venues = missing_venues.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::OpenInput { + label: "listing-venues", + ref path, + .. + } if path == &missing_venues + )); + assert!(err.to_string().contains(&missing_venues.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 7. Injected BSON read failures for both readers + struct FailingReader; + impl Read for FailingReader { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + Err(io::Error::new(io::ErrorKind::BrokenPipe, "synthetic read failure")) + } + } + let a = base(); + let err = run_curate_fundamentals_with_readers( + &a, + FailingReader, + Cursor::new(fil_doc.as_slice()), + ) + .unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::BsonStream { + label: "qm-financials", + ref path, + source: BsonStreamError::Io { offset: 0, .. }, + } if path == &valid_fin + )); + assert!(err.source().is_some()); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let err = run_curate_fundamentals_with_readers( + &a, + Cursor::new(fin_doc.as_slice()), + FailingReader, + ) + .unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::BsonStream { + label: "qm-filings", + ref path, + source: BsonStreamError::Io { offset: 0, .. }, + } if path == &valid_fil + )); + assert!(err.source().is_some()); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 8. Malformed mapping TSV + let bad_map = tmp.path().join("bad_map.tsv"); + fs::write(&bad_map, "qm\tNVDA\t2020-01-01\t\t101\nbad_line_only_one_col\n").unwrap(); + let mut a = base(); + a.provider_mapping = bad_map.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + ref path, + line: 2, + .. + } if path == &bad_map + )); + assert!(err.to_string().contains(&format!("{}:2:", bad_map.display()))); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 9. Malformed venue TSV + let bad_venues = tmp.path().join("bad_venues.tsv"); + fs::write(&bad_venues, "101\tus_tsx\n202\tunknown_exchange\n").unwrap(); + let mut a = base(); + a.listing_venues = bad_venues.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + ref path, + line: 2, + .. + } if path == &bad_venues + )); + assert!(err.to_string().contains(&format!("{}:2:", bad_venues.display()))); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 10. Mapping range conflict + let conflict_map = tmp.path().join("conflict_map.tsv"); + fs::write( + &conflict_map, + "qm\tNVDA\t2020-01-01\t2024-06-01\t101\nqm\tNVDA\t2024-06-01\t\t102\n", + ) + .unwrap(); + let mut a = base(); + a.provider_mapping = conflict_map.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::ProviderMapping { + ref path, + source: ProviderMappingError::OverlappingRanges { .. }, + } if path == &conflict_map + )); + assert!(err.to_string().contains(&conflict_map.display().to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 11. Truncated BSON in financials and filings + let trunc_fin = tmp.path().join("trunc_fin.bson"); + let mut trunc_fin_bytes = fin_doc.clone(); + trunc_fin_bytes.extend_from_slice(&fin_doc[..10]); + fs::write(&trunc_fin, &trunc_fin_bytes).unwrap(); + let mut a = base(); + a.qm_financials = trunc_fin.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::BsonStream { + label: "qm-financials", + ref path, + source: BsonStreamError::TruncatedDocument { offset, .. }, + } if path == &trunc_fin && offset == fin_doc.len() as u64 + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let trunc_fil = tmp.path().join("trunc_fil.bson"); + let mut trunc_fil_bytes = fil_doc.clone(); + trunc_fil_bytes.extend_from_slice(&fil_doc[..7]); + fs::write(&trunc_fil, &trunc_fil_bytes).unwrap(); + let mut a = base(); + a.qm_filings = trunc_fil.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::BsonStream { + label: "qm-filings", + ref path, + source: BsonStreamError::TruncatedDocument { offset, .. }, + } if path == &trunc_fil && offset == fil_doc.len() as u64 + )); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + // 12. Corrupt BSON in financials and filings (valid framing, invalid element tag) + let corrupt_fin = tmp.path().join("corrupt_fin.bson"); + let mut bad_fin_doc = fin_doc.clone(); + bad_fin_doc[4] = 0x7E; + let mut corrupt_fin_bytes = fin_doc.clone(); + let expected_fin_off = corrupt_fin_bytes.len() as u64; + corrupt_fin_bytes.extend_from_slice(&bad_fin_doc); + fs::write(&corrupt_fin, &corrupt_fin_bytes).unwrap(); + let mut a = base(); + a.qm_financials = corrupt_fin.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::CorruptFinancialsBson { + ref path, + offset, + .. + } if path == &corrupt_fin && offset == expected_fin_off + )); + assert!(err.to_string().contains(&expected_fin_off.to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + + let corrupt_fil = tmp.path().join("corrupt_fil.bson"); + let mut bad_fil_doc = fil_doc.clone(); + bad_fil_doc[4] = 0x7E; + let mut corrupt_fil_bytes = fil_doc.clone(); + let expected_fil_off = corrupt_fil_bytes.len() as u64; + corrupt_fil_bytes.extend_from_slice(&bad_fil_doc); + fs::write(&corrupt_fil, &corrupt_fil_bytes).unwrap(); + let mut a = base(); + a.qm_filings = corrupt_fil.clone(); + let err = run_curate_fundamentals(&a).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::CorruptFilingsBson { + ref path, + offset, + .. + } if path == &corrupt_fil && offset == expected_fil_off + )); + assert!(err.to_string().contains(&expected_fil_off.to_string())); + assert_single_line(&err.to_string()); + assert_preserved(out_dir, &before); + } +} + +#[test] +fn fundamentals_rejects_output_files_and_input_aliases() { + let tmp = TempDirGuard::new("path-safety"); + let valid_fin = tmp.path().join("fin.bson"); + let valid_fil = tmp.path().join("fil.bson"); + let valid_map = tmp.path().join("map.tsv"); + let valid_venues = tmp.path().join("venues.tsv"); + + let fin_bytes = make_financials_doc( + Some("NVDA"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(100.0), + ..Default::default() + }, + ); + let fil_bytes = make_filing_doc( + Some("NVDA"), + "2024-05-01T16:10:00 EDT", + "10-Q", + Some("f1"), + None, + ); + fs::write(&valid_fin, &fin_bytes).unwrap(); + fs::write(&valid_fil, &fil_bytes).unwrap(); + fs::write(&valid_map, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); + fs::write(&valid_venues, "101\tus_tsx\n").unwrap(); + + // 1. Regular file at out_dir + let file_as_out = tmp.path().join("out_is_file"); + let sentinel = b"do-not-overwrite-out-file".to_vec(); + fs::write(&file_as_out, &sentinel).unwrap(); + let args = default_test_args( + valid_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + file_as_out.clone(), + ); + assert!(matches!( + run_curate_fundamentals(&args).unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert!(matches!( + run_curate_fundamentals_with_readers( + &args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert_eq!(fs::read(&file_as_out).unwrap(), sentinel); + + // 2. Regular file at /fundamentals_pit + let out_with_file = tmp.path().join("out_with_dataset_file"); + fs::create_dir_all(&out_with_file).unwrap(); + let dataset_file = out_with_file.join("fundamentals_pit"); + fs::write(&dataset_file, b"dataset-file-sentinel").unwrap(); + let before = snapshot_tree(&out_with_file); + let args = default_test_args( + valid_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + out_with_file.clone(), + ); + assert!(matches!( + run_curate_fundamentals(&args).unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert!(matches!( + run_curate_fundamentals_with_readers( + &args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert_eq!(snapshot_tree(&out_with_file), before); + + // 3. All four inputs resolving to out_dir or inside /fundamentals_pit + let alias_out = tmp.path().join("alias_out"); + let inside_ds = alias_out.join("fundamentals_pit").join("year=2024"); + fs::create_dir_all(&inside_ds).unwrap(); + let inside_fin = inside_ds.join("fin.bson"); + let inside_fil = inside_ds.join("fil.bson"); + let inside_map = inside_ds.join("map.tsv"); + let inside_venues = inside_ds.join("venues.tsv"); + fs::write(&inside_fin, &fin_bytes).unwrap(); + fs::write(&inside_fil, &fil_bytes).unwrap(); + fs::write(&inside_map, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); + fs::write(&inside_venues, "101\tus_tsx\n").unwrap(); + let alias_before = snapshot_tree(&alias_out); + + for bad_args in [ + default_test_args( + inside_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + alias_out.clone(), + ), + default_test_args( + valid_fin.clone(), + inside_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + alias_out.clone(), + ), + default_test_args( + valid_fin.clone(), + valid_fil.clone(), + inside_map.clone(), + valid_venues.clone(), + alias_out.clone(), + ), + default_test_args( + valid_fin.clone(), + valid_fil.clone(), + valid_map.clone(), + inside_venues.clone(), + alias_out.clone(), + ), + // Input equal to out_dir itself + default_test_args( + alias_out.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + alias_out.clone(), + ), + ] { + assert!(matches!( + run_curate_fundamentals(&bad_args).unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert!(matches!( + run_curate_fundamentals_with_readers( + &bad_args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert_eq!(snapshot_tree(&alias_out), alias_before); + } + + // 4. Unix symlink-before-`..` resolution and symlinked year=2024 partition aliasing an external input + #[cfg(unix)] + { + use std::os::unix::fs::symlink; + + // Symlink-before-`..`: link_dir -> real_parent/child; link_dir/../out_target resolves to + // real_parent/out_target (NOT tmp/out_target). + let real_parent = tmp.path().join("real_parent"); + let real_child = real_parent.join("child"); + fs::create_dir_all(&real_child).unwrap(); + let real_out = real_parent.join("out_target"); + let real_ds = real_out.join("fundamentals_pit"); + fs::create_dir_all(&real_ds).unwrap(); + let ext_input = real_ds.join("aliased_fin.bson"); + fs::write(&ext_input, &fin_bytes).unwrap(); + let ext_before = fs::read(&ext_input).unwrap(); + let real_out_before = snapshot_tree(&real_out); + + let link_dir = tmp.path().join("link_dir"); + symlink(&real_child, &link_dir).unwrap(); + let symlink_dotdot_out = link_dir.join("..").join("out_target"); + + let args = default_test_args( + ext_input.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + symlink_dotdot_out, + ); + assert!(matches!( + run_curate_fundamentals(&args).unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert!(matches!( + run_curate_fundamentals_with_readers( + &args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert_eq!(snapshot_tree(&real_out), real_out_before); + assert_eq!(fs::read(&ext_input).unwrap(), ext_before); + + // Symlinked year=2024 partition pointing to external dir containing an input file. + let ext_dir = tmp.path().join("external_year_target"); + fs::create_dir_all(&ext_dir).unwrap(); + let ext_part_input = ext_dir.join("part.parquet"); + fs::write(&ext_part_input, &fin_bytes).unwrap(); + let ext_part_before = fs::read(&ext_part_input).unwrap(); + + let sym_out = tmp.path().join("sym_year_out"); + let sym_ds = sym_out.join("fundamentals_pit"); + fs::create_dir_all(&sym_ds).unwrap(); + symlink(&ext_dir, sym_ds.join("year=2024")).unwrap(); + let sym_out_before = snapshot_tree(&sym_out); + + let args = default_test_args( + ext_part_input.clone(), + valid_fil.clone(), + valid_map.clone(), + valid_venues.clone(), + sym_out.clone(), + ); + assert!(matches!( + run_curate_fundamentals(&args).unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert!(matches!( + run_curate_fundamentals_with_readers( + &args, + Cursor::new(fin_bytes.as_slice()), + Cursor::new(fil_bytes.as_slice()), + ) + .unwrap_err(), + RunCurateFundamentalsError::InvalidOutDir { .. } + )); + assert_eq!(snapshot_tree(&sym_out), sym_out_before); + assert_eq!(fs::read(&ext_part_input).unwrap(), ext_part_before); + } +} + +#[test] +fn fundamentals_empty_inputs_publish_nothing() { + let tmp = TempDirGuard::new("empty"); + let fin_path = tmp.path().join("empty_fin.bson"); + let fil_path = tmp.path().join("empty_fil.bson"); + let map_path = tmp.path().join("map.tsv"); + let venues_path = tmp.path().join("venues.tsv"); + fs::write(&fin_path, []).unwrap(); + fs::write(&fil_path, []).unwrap(); + fs::write(&map_path, "qm\tNVDA\t2020-01-01\t\t101\n").unwrap(); + fs::write(&venues_path, "101\tus_tsx\n").unwrap(); + + // Fresh output directory: dataset directory must not be created. + let fresh_out = tmp.path().join("fresh_out"); + let args = default_test_args( + fin_path.clone(), + fil_path.clone(), + map_path.clone(), + venues_path.clone(), + fresh_out.clone(), + ); + let report = run_curate_fundamentals(&args).unwrap(); + assert_conservation(&report); + assert_eq!(report.write_stats.rows_written, 0); + assert_eq!(report.write_stats.files_written, 0); + assert!(!fresh_out.join("fundamentals_pit").exists()); + + // Pre-existing partition: rerun with empty inputs must leave it byte-identical. + let seeded_out = tmp.path().join("seeded_out"); + let seed_fin = tmp.path().join("seed_fin.bson"); + fs::write( + &seed_fin, + make_financials_doc( + Some("NVDA"), + "2024-03-31", + None, + "Q1", + "USD", + FundamentalsFields { + revenue: Some(50.0), + ..Default::default() + }, + ), + ) + .unwrap(); + let seed_args = default_test_args( + seed_fin, + fil_path.clone(), + map_path.clone(), + venues_path.clone(), + seeded_out.clone(), + ); + run_curate_fundamentals(&seed_args).unwrap(); + let before = snapshot_tree(&seeded_out); + + let empty_rerun = default_test_args(fin_path, fil_path, map_path, venues_path, seeded_out.clone()); + let rerun_report = run_curate_fundamentals(&empty_rerun).unwrap(); + assert_eq!(rerun_report.write_stats.rows_written, 0); + assert_eq!(rerun_report.write_stats.files_written, 0); + assert_eq!(snapshot_tree(&seeded_out), before); +} + +#[test] +fn fundamentals_all_unmapped_publish_nothing() { + let tmp = TempDirGuard::new("unmapped"); + let fin_path = tmp.path().join("unmapped_fin.bson"); + let fil_path = tmp.path().join("unmapped_fil.bson"); + let map_path = tmp.path().join("map.tsv"); + let venues_path = tmp.path().join("venues.tsv"); + + fs::write(&map_path, "qm\tKNOWN\t2020-01-01\t\t101\n").unwrap(); + fs::write(&venues_path, "101\tus_tsx\n").unwrap(); + fs::write( + &fin_path, + make_financials_doc( + Some("OTHER"), + "2024-03-31", + Some("2024-05-01"), + "Q1", + "USD", + FundamentalsFields { + revenue: Some(10.0), + ..Default::default() + }, + ), + ) + .unwrap(); + fs::write( + &fil_path, + make_filing_doc( + Some("OTHER"), + "2024-05-01T16:10:00 EDT", + "10-Q", + Some("f1"), + None, + ), + ) + .unwrap(); + + // Fresh output directory: dataset directory must not be created. + let fresh_out = tmp.path().join("fresh_out"); + let args = default_test_args( + fin_path.clone(), + fil_path.clone(), + map_path.clone(), + venues_path.clone(), + fresh_out.clone(), + ); + let report = run_curate_fundamentals(&args).unwrap(); + assert_conservation(&report); + assert_eq!(report.curate_stats.observations_in, 1); + assert_eq!(report.curate_stats.observations_dropped_unmapped, 1); + assert_eq!(report.write_stats.rows_written, 0); + assert_eq!(report.write_stats.files_written, 0); + assert!(!fresh_out.join("fundamentals_pit").exists()); + + // Pre-existing partition: rerun with all-unmapped inputs leaves it byte-identical. + let seeded_out = tmp.path().join("seeded_out"); + let seed_fin = tmp.path().join("seed_fin.bson"); + fs::write( + &seed_fin, + make_financials_doc( + Some("KNOWN"), + "2024-03-31", + None, + "Q1", + "USD", + FundamentalsFields { + revenue: Some(50.0), + ..Default::default() + }, + ), + ) + .unwrap(); + run_curate_fundamentals(&default_test_args( + seed_fin, + fil_path.clone(), + map_path.clone(), + venues_path.clone(), + seeded_out.clone(), + )) + .unwrap(); + let before = snapshot_tree(&seeded_out); + + let rerun = run_curate_fundamentals(&default_test_args( + fin_path, + fil_path, + map_path, + venues_path, + seeded_out.clone(), + )) + .unwrap(); + assert_eq!(rerun.write_stats.rows_written, 0); + assert_eq!(rerun.write_stats.files_written, 0); + assert_eq!(snapshot_tree(&seeded_out), before); +} + +#[test] +fn listing_venues_rejects_wrong_column_count() { + let tmp = TempDirGuard::new("venues-cols"); + let path = tmp.path().join("listing_venues.tsv"); + fs::write(&path, "101\tus_tsx\n202\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 2, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:2:", path.display()))); + assert_single_line(&msg); + + // Too many columns (3 columns on line 2) + fs::write(&path, "101\tus_tsx\r\n202\ttsxv_cse\textra\r\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 2, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:2:", path.display()))); + assert_single_line(&msg); +} + +#[test] +fn listing_venues_rejects_non_integer_id() { + let tmp = TempDirGuard::new("venues-non-int"); + let path = tmp.path().join("listing_venues.tsv"); + fs::write(&path, "101\tus_tsx\nabc\ttsxv_cse\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 2, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:2:", path.display()))); + assert_single_line(&msg); +} + +#[test] +fn listing_venues_rejects_non_positive_id() { + let tmp = TempDirGuard::new("venues-non-pos"); + let path = tmp.path().join("listing_venues.tsv"); + for (content, expected_line) in [ + ("101\tus_tsx\n0\ttsxv_cse\n", 2), + ("101\tus_tsx\n202\ttsxv_cse\n-5\tus_tsx\n", 3), + ] { + fs::write(&path, content).unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line, + .. + } if p == &path && line == expected_line + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:{expected_line}:", path.display()))); + assert_single_line(&msg); + } +} + +#[test] +fn listing_venues_rejects_unknown_venue() { + let tmp = TempDirGuard::new("venues-unknown"); + let path = tmp.path().join("listing_venues.tsv"); + fs::write(&path, "101\tus_tsx\n202\tUS_TSX\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 2, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:2:", path.display()))); + assert_single_line(&msg); +} + +#[test] +fn listing_venues_rejects_duplicate_id() { + let tmp = TempDirGuard::new("venues-dup"); + let path = tmp.path().join("listing_venues.tsv"); + fs::write(&path, "101\tus_tsx\n202\ttsxv_cse\n101\ttsxv_cse\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 3, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:3:", path.display()))); + assert_single_line(&msg); +} + +#[test] +fn listing_venues_rejects_interior_blank() { + let tmp = TempDirGuard::new("venues-blank"); + let path = tmp.path().join("listing_venues.tsv"); + fs::write(&path, "101\tus_tsx\n\n202\ttsxv_cse\n").unwrap(); + let err = load_listing_venues_tsv(&path).unwrap_err(); + assert!(matches!( + err, + RunCurateFundamentalsError::TsvParse { + path: ref p, + line: 2, + .. + } if p == &path + )); + let msg = err.to_string(); + assert!(msg.contains(&format!("{}:2:", path.display()))); + assert_single_line(&msg); +}