T-171: M2.2m — tools/curate-etl: file-to-file fundamentals_pit runner (decode_qm_financials_chunks in bson_stream.rs + run_curate_fundamentals.rs: raw qmFinancials + qmFilings BSON dumps + provider_mapping.tsv + listing-venue TSV → curate_and_write_fundamentals → fundamentals_pit Zstd Parquet) with tests (no new crates, no CLI/bench changes, no live Mongo)
This commit is contained in:
parent
f24dc4260d
commit
74ac9dce8d
6 changed files with 3774 additions and 8 deletions
|
|
@ -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.
|
- **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.
|
- **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.
|
- **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 `<out_dir>/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<String>` 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_id<TAB>venue`, 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 `<out_dir>/fundamentals_pit` or modifying pre-existing partitions. CLI wiring (`curate-fundamentals`) is a separate follow-up.
|
||||||
|
|
|
||||||
|
|
@ -44,6 +44,10 @@ use crate::bson_qm_events::{
|
||||||
BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, QmFilingsFieldNames,
|
BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, QmFilingsFieldNames,
|
||||||
RawQmEarning, RawQmFiling,
|
RawQmEarning, RawQmFiling,
|
||||||
};
|
};
|
||||||
|
use crate::bson_qm_financials::{
|
||||||
|
decode_qm_financials_buffer, BsonQmFinancialsDecodeStats, BsonQmFinancialsError,
|
||||||
|
QmFinancialsFieldNames, QmFinancialsFiscalPeriod,
|
||||||
|
};
|
||||||
use crate::bson_qm_intraday::{
|
use crate::bson_qm_intraday::{
|
||||||
decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, RawQmIntradayBar,
|
decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, RawQmIntradayBar,
|
||||||
};
|
};
|
||||||
|
|
@ -53,6 +57,7 @@ use crate::bson_qm_prices::{
|
||||||
use crate::bson_te_market_data::{
|
use crate::bson_te_market_data::{
|
||||||
decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError,
|
decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError,
|
||||||
};
|
};
|
||||||
|
use crate::fundamentals::FinancialObservation;
|
||||||
use crate::fx::FxDailyBar;
|
use crate::fx::FxDailyBar;
|
||||||
use crate::posts::CeoPost;
|
use crate::posts::CeoPost;
|
||||||
use crate::shorts::CeoShortReport;
|
use crate::shorts::CeoShortReport;
|
||||||
|
|
@ -1333,6 +1338,118 @@ where
|
||||||
decode_qm_earnings_chunks(&mut chunk_reader, fields, on_row)
|
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<BsonStreamError> for BsonQmFinancialsStreamError {
|
||||||
|
fn from(err: BsonStreamError) -> Self {
|
||||||
|
Self::Stream(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<BsonQmFinancialsError> 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<R, F>(
|
||||||
|
reader: &mut RawBsonChunkReader<R>,
|
||||||
|
fields: &QmFinancialsFieldNames<'_>,
|
||||||
|
fiscal_period: QmFinancialsFiscalPeriod<'_>,
|
||||||
|
mut on_row: F,
|
||||||
|
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsStreamError>
|
||||||
|
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<R, F>(
|
||||||
|
reader: R,
|
||||||
|
options: BsonStreamOptions,
|
||||||
|
fields: &QmFinancialsFieldNames<'_>,
|
||||||
|
fiscal_period: QmFinancialsFiscalPeriod<'_>,
|
||||||
|
on_row: F,
|
||||||
|
) -> Result<BsonQmFinancialsDecodeStats, BsonQmFinancialsStreamError>
|
||||||
|
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)]
|
#[cfg(test)]
|
||||||
#[path = "bson_stream_tests.rs"]
|
#[path = "bson_stream_tests.rs"]
|
||||||
mod tests;
|
mod tests;
|
||||||
|
|
|
||||||
|
|
@ -13,16 +13,22 @@ use crate::bson_eod_prices::{
|
||||||
use crate::bson_qm_actions::{
|
use crate::bson_qm_actions::{
|
||||||
decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats,
|
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::{
|
use crate::bson_qm_intraday::{
|
||||||
decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError,
|
decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError,
|
||||||
};
|
};
|
||||||
use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError};
|
use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError};
|
||||||
use crate::bson_stream::{
|
use crate::bson_stream::{
|
||||||
decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_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_dividend_stream, decode_qm_financials_chunks, decode_qm_financials_stream,
|
||||||
decode_qm_price_stream, decode_qm_split_stream, BsonStreamError, BsonStreamOptions,
|
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,
|
RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||||
};
|
};
|
||||||
|
use crate::fundamentals::FinancialObservation;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
#[derive(Debug, Clone, Copy)]
|
||||||
struct SplitMix64(u64);
|
struct SplitMix64(u64);
|
||||||
|
|
@ -2724,3 +2730,365 @@ fn decode_qm_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() {
|
||||||
} if offset == trunc_offset
|
} 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<f64>,
|
||||||
|
net_income_str: Option<&str>,
|
||||||
|
total_assets: Option<f64>,
|
||||||
|
) -> Vec<u8> {
|
||||||
|
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<String> {
|
||||||
|
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::<u8>::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<usize> {
|
||||||
|
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 { .. })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -99,12 +99,13 @@ pub use bson_stream::{
|
||||||
decode_ceo_shorts_stream, decode_eod_intraday_chunks, decode_eod_intraday_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_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_dividend_stream, decode_qm_earnings_chunks, decode_qm_earnings_stream,
|
||||||
decode_qm_filings_chunks, decode_qm_filings_stream, decode_qm_intraday_chunks,
|
decode_qm_filings_chunks, decode_qm_filings_stream, decode_qm_financials_chunks,
|
||||||
decode_qm_intraday_stream, decode_qm_price_chunks, decode_qm_price_stream,
|
decode_qm_financials_stream, decode_qm_intraday_chunks, decode_qm_intraday_stream,
|
||||||
decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks,
|
decode_qm_price_chunks, decode_qm_price_stream, decode_qm_split_chunks,
|
||||||
decode_te_market_data_stream, BsonCeoPostsStreamError, BsonCeoShortsStreamError,
|
decode_qm_split_stream, decode_te_market_data_chunks, decode_te_market_data_stream,
|
||||||
BsonQmEventsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader,
|
BsonCeoPostsStreamError, BsonCeoShortsStreamError, BsonQmEventsStreamError,
|
||||||
DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
BsonQmFinancialsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk,
|
||||||
|
RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||||
};
|
};
|
||||||
pub use bson_te_market_data::{
|
pub use bson_te_market_data::{
|
||||||
decode_te_market_data_buffer, decode_te_market_data_bytes, decode_te_market_data_doc,
|
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,
|
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 mod run_curate_shorts;
|
||||||
pub use run_curate_shorts::{
|
pub use run_curate_shorts::{
|
||||||
format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader,
|
format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader,
|
||||||
|
|
|
||||||
1119
tools/curate-etl/src/run_curate_fundamentals.rs
Normal file
1119
tools/curate-etl/src/run_curate_fundamentals.rs
Normal file
File diff suppressed because it is too large
Load diff
2146
tools/curate-etl/src/run_curate_fundamentals_tests.rs
Normal file
2146
tools/curate-etl/src/run_curate_fundamentals_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue