From 8a0a353d2ecc0cf8969cb07838e837d9c0656680 Mon Sep 17 00:00:00 2001 From: Studio Date: Sun, 29 Nov 2026 04:29:00 -0500 Subject: [PATCH] =?UTF-8?q?T-115:=20M1.2ae=20=E2=80=94=20`tools/curate-etl?= =?UTF-8?q?`:=20sixth=20runnable=20command=20`curate-events`=20(concatenat?= =?UTF-8?q?ed-BSON=20`qmFilings`=20+=20`qmEarnings`=20files=20+=20`provide?= =?UTF-8?q?r=5Fmapping`=20TSV=20=E2=86=92=20`events/year=3DYYYY/part.parqu?= =?UTF-8?q?et`)=20with=20zero-copy=20`qmFilings`=20/=20`qmEarnings`=20deco?= =?UTF-8?q?ders,=20end-to-end=20tests=20and=20local=20benchmark=20(no=20ne?= =?UTF-8?q?w=20crates,=20no=20MongoDB=20connection)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 89 +- tools/curate-etl/src/bench.rs | 526 ++++++++ tools/curate-etl/src/bson_qm_events.rs | 1059 +++++++++++++++++ tools/curate-etl/src/bson_qm_events_tests.rs | 500 ++++++++ tools/curate-etl/src/bson_stream.rs | 150 +++ tools/curate-etl/src/bson_stream_tests.rs | 142 +++ tools/curate-etl/src/cli.rs | 417 ++++++- tools/curate-etl/src/lib.rs | 24 +- tools/curate-etl/src/main.rs | 85 +- tools/curate-etl/src/run_curate_events.rs | 758 ++++++++++++ .../curate-etl/src/run_curate_events_tests.rs | 629 ++++++++++ 11 files changed, 4362 insertions(+), 17 deletions(-) create mode 100644 tools/curate-etl/src/bson_qm_events.rs create mode 100644 tools/curate-etl/src/bson_qm_events_tests.rs create mode 100644 tools/curate-etl/src/run_curate_events.rs create mode 100644 tools/curate-etl/src/run_curate_events_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 937d6cf8..1a1bda25 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, and the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`). +Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, and the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command. ## Scope & Sign Conventions @@ -158,7 +158,7 @@ Rules: - Exact duplicate filings collapse (`filings_duplicate_collapsed`); identical normalized `(key, report_date)` earnings collapse (`earnings_duplicate_collapsed`) and conflicting `(key, report_date)` groups drop entirely (`earnings_duplicate_conflict_dropped`). - Output rows are sorted deterministically by `(key, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)` and `EventsStats` reconciles exactly per kind (`filings_in == filings_out + skips + dup`, `earnings_in == earnings_out + oor + dup + conflict`, `earnings_out == linked + lagged`, `rows_out == filings_out + earnings_out`). -Deferred out of `src/events.rs`: MongoDB `qmFilings` / `qmEarnings` BSON cursors, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, and M2 `fundamentals_pit` joins. +Deferred out of `src/events.rs`: live MongoDB `qmFilings` / `qmEarnings` cursors and M2 `fundamentals_pit` joins (concatenated-BSON decoding, `provider_mapping` resolution, and Zstd Parquet publishing are wired in `src/bson_qm_events.rs` + `src/run_curate_events.rs`). ## `provider_mapping` Table (`M1.2h`) @@ -453,7 +453,7 @@ Rules: - `iter_raw_bson_docs` walks concatenated 4-byte little-endian length-prefixed BSON documents (wire / `mongodump` layout), terminating cleanly on unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) while skipping validly framed corrupt documents (`CorruptBson`). - `decode_eod_price_buffer` reports and skips per-document errors without aborting the stream, reconciling `BsonEodDecodeStats` with `decoded + rejected_total() == docs_in`. 5. **Deferred out of `M1.2o`:** - - MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`). + - MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, and decoders for remaining collections (`qmPrices`, `eodIntraday1M`). (`qmSplits`/`qmDividends`, `teMarketData`, `ceoShorts`, and `qmFilings`/`qmEarnings` decoders are now implemented alongside all six M1 `curate-*` file-to-Parquet commands.) ## `qmSplits` / `qmDividends` Raw BSON Decoders (`M1.2w`) @@ -1385,3 +1385,86 @@ Measured locally (`2026-11-29`, Linux `6.8.0-151-generic`, AMD Ryzen 9 9950X3D 1 bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --collections ceoShorts --out ``` - **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB/PostgreSQL connection, and `pct_float` is passed through as supplied rather than derived from shares outstanding. + +## `curate-events` Command (`M1.2ae`) + +End-to-end file-to-Parquet CLI command (`src/run_curate_events.rs`) wiring `RawBsonChunkReader`, the zero-copy `qmFilings` + `qmEarnings` decoders (`src/bson_qm_events.rs`, `decode_qm_filings_chunks`, `decode_qm_earnings_chunks`), `load_provider_mapping_tsv`, and `curate_and_write_events` into atomically published `/events/year=YYYY/part.parquet` partitions with zero extra crates and no database connections. + +### Invocation + +```bash +curate-etl curate-events \ + --qm-filings qmFilings.bson \ + --qm-earnings qmEarnings.bson \ + --provider-mapping provider_mapping.tsv \ + --out ./out \ + --filings-form-type-field \ + [--filings-key-field symbol] \ + [--filings-timefiled-field timefiled] \ + [--filings-filing-id-field ] \ + [--filings-url-field ] \ + [--earnings-key-field qmSearchCode] \ + [--earnings-report-date-field reportDate] \ + [--earnings-announce-time-field announceTime] \ + [--earnings-fiscal-period-end-field ] \ + [--earnings-actual-eps-field ] \ + [--earnings-revenue-field ] \ + [--mapping-source qm] +``` + +Inputs and verified vs. configured field names: +- `--qm-filings ` *(required)*: concatenated raw BSON (`mongodump` `qmFilings.bson`). +- `--qm-earnings ` *(required)*: concatenated raw BSON (`mongodump` `qmEarnings.bson`). +- `--provider-mapping ` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`). +- `--out ` *(required)*: dataset root where `events/year=YYYY/part.parquet` is atomically published. Upfront path validation rejects `--out` or `/events` being a regular file, or any input path resolving to `--out` or inside `/events/...` (preventing input clobbering). +- **Verified defaults** (grounded in `apps/stock/data-ingestion/src/handlers/qm/actions/filings.action.ts`, `events.action.ts`, and `design/DATA-CONTRACTS.md` §1): + - `qmFilings`: `--filings-key-field` (`symbol`; note `filings.action.ts` does **not** add `qmSearchCode` to stored docs despite the upsert key), `--filings-timefiled-field` (`timefiled`). + - `qmEarnings`: `--earnings-key-field` (`qmSearchCode`), `--earnings-report-date-field` (`reportDate`), `--earnings-announce-time-field` (`announceTime`). +- **Caller-configured fields (no defaults):** + - `--filings-form-type-field ` *(required, no default)*: BSON field holding the EDGAR/SEDAR+ form type string. + - Optional: `--filings-filing-id-field`, `--filings-url-field`, `--earnings-fiscal-period-end-field`, `--earnings-actual-eps-field`, `--earnings-revenue-field`. +- `--mapping-source ` *(optional, default `qm`)*: `provider_mapping` source name used to resolve `(mapping_source, key, event_date) -> listing_id` on each event's exact Eastern local calendar date. +- **`consensusEps` exclusion:** `consensusEps` is structurally omitted from `RawQmEarning` / `QmEarning` and explicitly rejected (case-insensitively as `consensusEps` / `consensus_eps`) on any earnings field flag per `design/DATA-CONTRACTS.md` §1. + +Both `--flag value` and `--flag=value` forms are accepted. Missing required flags (including `--filings-form-type-field`), duplicate flags, unknown flags, blank field names or `--mapping-source`, colliding role mappings within a collection, or any `consensusEps` mapping exit non-zero with usage on stderr. Any runtime error (missing input file, malformed/overlapping `provider_mapping.tsv`, truncated/corrupt BSON in either stream, or obstructed/overlapping `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `/events/` partitions byte-identical). + +### `qmFilings` & `qmEarnings` Decoder Rules + +- Scans and structurally validates every element and nested document/array/JS-with-scope (depth limit `128`) of each `RawDocument` before applying semantic skip rules so structural corruption always fails closed with a typed error carrying the absolute byte offset. +- `qmFilings` deterministic skip priority: `key` → `timefiled` → `form_type` (all required non-blank UTF-8 `String`s passed verbatim; timestamp syntax remains in `events::build_events`). Optional `filing_id` / `url`: unconfigured, absent, `Null`, or blank string → `None`; wrong BSON type → `None` + `nulled_wrong_type_*` (emitted rows only). +- `qmEarnings` deterministic skip priority: `key` → `report_date` → `announce_time`. `report_date` accepts BSON `DateTime` (UTC epoch day checked to `i32`) or strict `YYYY-MM-DD` `String`. Optional `fiscal_period_end` accepts absent/`Null`/blank (`None`), `DateTime` or strict `YYYY-MM-DD` (`Some(i32)`), wrong BSON type (`nulled_wrong_type_fiscal_period_end`), or malformed/out-of-range (`nulled_invalid_fiscal_period_end`, emitted rows only). Optional `actual_eps` / `revenue` accept absent/`Null` (`None`), `Double`/`Int32`/`Int64` (`Some(f64)`), or wrong BSON type (`nulled_wrong_type_*`, emitted rows only). +- Empty or all-unmapped inputs return `Ok` with `rows_written=0` and `files=0` without creating `/events` or modifying any pre-existing partitions. + +### Report Counters & Conservation Invariants + +On success, `curate-events` prints deterministic `key=value` lines to stdout (`filings_bson`, `earnings_bson`, `builder`, `curate`, `write`, ascending `years`, and `timing`): + +- **Filings BSON:** `filings_bson.docs_framed == filings_bson.docs_in == filings_bson.rows_out + filings_bson.skipped`, and `filings_bson.rows_out == builder.filings_in`. +- **Earnings BSON:** `earnings_bson.docs_framed == earnings_bson.docs_in == earnings_bson.rows_out + earnings_bson.skipped`, and `earnings_bson.rows_out == builder.earnings_in`. +- **Builder:** `builder.filings_in == builder.filings_out + malformed_ts + unknown_zone + invalid_dt + filing_dup`, `builder.earnings_in == builder.earnings_out + earnings_oor + earnings_dup + earnings_conflict`, `builder.earnings_out == linked + lagged_1605`, and `builder.rows_out == builder.filings_out + builder.earnings_out`. +- **Stage & Write:** `curate.rows_in == builder.rows_out == curate.rows_out + curate.dropped_unmapped + curate.listing_dup_collapsed`, and `write.rows_written == curate.rows_out`. + +### `bench-curate-events-cmd` + +Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `provider_mapping.tsv` (`5,000` keys with ~2% unmapped), `qmFilings.bson` (~98.5% of `rows`, mixed EST/EDT `2015..=2025`, EDGAR + SEDAR+ form types, ~0.5% skips/wrong-type optionals), and `qmEarnings.bson` (~1.5% of `rows`, mixed `DateTime`/`YYYY-MM-DD`, linked & unlinked rows, `consensusEps` present and ignored, ~0.5% skips/wrong-type optionals) into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row counts across all UTC year partitions, extrapolating to the full `30.52M + 444.9k` (`30,964,900` rows) QA MongoDB dataset, and cleaning up on drop: + +```bash +cargo run -p curate-etl --release --offline -- bench-curate-events-cmd [rows] +``` + +Measured locally (`2026-11-29`, default `500,000` rows; two back-to-back runs with identical checksum `0x2076c3a54dc2403e`): + +- Input: `rows=500000`, `filings_docs=492500` (`71,019,899 B`), `earnings_docs=7500` (`1,233,791 B`), `keys=5000`, `peak_chunk_bytes=8388608` (`8 MiB`) +- Decode counts: `filings_out=490021`, `filings_skipped=2479`, `earnings_out=7462`, `earnings_skipped=38` +- Output: `rows_out=487589` (`97.52%` retained; `filings_out=480258`, `earnings_out=7331`), `listings_out=4900`, `linked=3008`, `lagged_1605=4452`, `unmapped=9892`, `files=12`, `row_groups=12`, `bytes=14125012`, `read_back_rows=487589` +- Run 1: `decode=136.07 ms` (`3,674,605 rows/s`, `506.41 MB/s`), `curate=278.55 ms` (`1,786,003 rows/s`), `write=446.48 ms` (`1,092,064 rows/s`, `30.17 MB/s`), `total=861.10 ms` (`580,654 rows/s`), **extrapolation to `30.52M` filings + `444.9k` earnings (`30.96M` rows): `53.3 s` (`0.89 min`) single-core**, `checksum=0x2076c3a54dc2403e` +- Run 2: `decode=136.68 ms` (`3,658,115 rows/s`, `504.14 MB/s`), `curate=264.16 ms` (`1,883,251 rows/s`), `write=437.86 ms` (`1,113,564 rows/s`, `30.76 MB/s`), `total=838.71 ms` (`596,155 rows/s`), **extrapolation to `30.52M` filings + `444.9k` earnings (`30.96M` rows): `51.9 s` (`0.87 min`) single-core**, `checksum=0x2076c3a54dc2403e` + +### Known Limitations + +- **Unverified live `qmFilings` / `qmEarnings` field names:** `--filings-form-type-field`, optional filings fields (`filing_id`, `url`), optional earnings fields (`fiscal_period_end`, `actual_eps`, `revenue`), and whether live `qmFilings` documents carry `qmSearchCode` vs. `symbol` are unverified against live QA MongoDB. Confirm them before the first real run with the read-only field-shape probe: + ```bash + bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --collections qmFilings,qmEarnings --out + ``` +- **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. On Canadian tickers (e.g. `SHOP` vs. `SHOP:CA`), pass `--filings-key-field` or `--earnings-key-field` so both collections share the same key namespace as `provider_mapping` for same-day earnings↔filing linking. +- **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope. diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 291b8cdc..51bea79f 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -9635,6 +9635,470 @@ pub fn run_curate_shorts_command_benchmark( Ok(report) } +/// Default total document count for `bench-curate-events-cmd` (~98.5% `qmFilings` / ~1.5% `qmEarnings`). +pub const DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS: usize = 500_000; +/// Live QA MongoDB dataset size (`30.52M` `qmFilings` + `444.9k` `qmEarnings`) used for single-core extrapolation. +pub const CURATE_EVENTS_FULL_DATASET_ROWS: f64 = 30_520_000.0 + 444_900.0; +const CURATE_EVENTS_CMD_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7501; +const CURATE_EVENTS_CMD_BENCH_KEYS: usize = 5_000; + +/// Errors returned by [`run_curate_events_cmd_benchmark`]. +#[derive(Debug)] +pub enum CurateEventsCmdBenchError { + FixtureIo { + path: PathBuf, + source: io::Error, + }, + Run(crate::run_curate_events::RunCurateEventsError), + Verify(ParquetEventsError), +} + +impl std::fmt::Display for CurateEventsCmdBenchError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::FixtureIo { path, source } => { + write!(f, "benchmark fixture I/O '{}': {source}", path.display()) + } + Self::Run(err) => write!(f, "{err}"), + Self::Verify(err) => write!(f, "Parquet verify failed: {err}"), + } + } +} + +impl std::error::Error for CurateEventsCmdBenchError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::FixtureIo { source, .. } => Some(source), + Self::Run(err) => Some(err), + Self::Verify(err) => Some(err), + } + } +} + +/// Summary metrics produced by [`run_curate_events_cmd_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CurateEventsCmdBenchReport { + pub rows: usize, + pub key_count: usize, + pub filings_docs_framed: u64, + pub filings_bytes_read: u64, + pub earnings_docs_framed: u64, + pub earnings_bytes_read: u64, + pub peak_chunk_bytes: usize, + pub rows_out: usize, + pub filings_out: usize, + pub earnings_out: usize, + pub listings_out: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub read_back_rows: usize, + pub decode_elapsed_ms: f64, + pub decode_rows_per_sec: f64, + pub input_mb_per_sec: f64, + pub curate_elapsed_ms: f64, + pub curate_rows_per_sec: f64, + pub write_elapsed_ms: f64, + pub write_rows_per_sec: f64, + pub write_mb_per_sec: f64, + pub total_elapsed_ms: f64, + pub total_rows_per_sec: f64, + pub total_extrap_full_secs: f64, + pub checksum: u64, + pub filings_decode: crate::bson_qm_events::BsonQmFilingsDecodeStats, + pub earnings_decode: crate::bson_qm_events::BsonQmEarningsDecodeStats, + pub curate_stats: crate::curate_events::CurateEventsStats, +} + +fn run_curate_events_cmd_benchmark_tracked( + rows: usize, +) -> Result<(CurateEventsCmdBenchReport, PathBuf), CurateEventsCmdBenchError> { + use std::io::{BufWriter, Write}; + + use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; + use bson::DateTime as BsonDateTime; + + use crate::bson_eod_prices::MILLIS_PER_DAY; + use crate::bson_qm_events::{ + BsonQmEarningsDecodeStats, BsonQmFilingsDecodeStats, DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, + DEFAULT_EARNINGS_KEY_FIELD, DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, + DEFAULT_FILINGS_TIMEFILED_FIELD, + }; + use crate::curate_events::CurateEventsStats; + use crate::run_curate_events::{ + run_curate_events_timed, CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE, + }; + + const MIB: f64 = 1024.0 * 1024.0; + const FORM_TYPES: [&str; 10] = [ + "8-K", + "10-Q", + "10-K", + "4", + "144", + "News release", + "Interim financial statements", + "Annual financial statements", + "MD&A", + "52-109", + ]; + const ANNOUNCE_TIMES: [&str; 3] = ["N/A", "AMC", "BTO"]; + + let temp = BenchTempDir::new_in_with_prefix( + &std::env::temp_dir(), + "curate-etl-bench-curate-events-cmd", + ) + .map_err(|(path, source)| CurateEventsCmdBenchError::FixtureIo { path, source })?; + let temp_path = temp.path.clone(); + + if rows == 0 { + drop(temp); + return Ok(( + CurateEventsCmdBenchReport { + rows: 0, + key_count: 0, + filings_docs_framed: 0, + filings_bytes_read: 0, + earnings_docs_framed: 0, + earnings_bytes_read: 0, + peak_chunk_bytes: 0, + rows_out: 0, + filings_out: 0, + earnings_out: 0, + listings_out: 0, + files_written: 0, + row_groups_written: 0, + bytes_written: 0, + read_back_rows: 0, + decode_elapsed_ms: 0.0, + decode_rows_per_sec: 0.0, + input_mb_per_sec: 0.0, + curate_elapsed_ms: 0.0, + curate_rows_per_sec: 0.0, + write_elapsed_ms: 0.0, + write_rows_per_sec: 0.0, + write_mb_per_sec: 0.0, + total_elapsed_ms: 0.0, + total_rows_per_sec: 0.0, + total_extrap_full_secs: 0.0, + checksum: 0, + filings_decode: BsonQmFilingsDecodeStats::default(), + earnings_decode: BsonQmEarningsDecodeStats::default(), + curate_stats: CurateEventsStats::default(), + }, + temp_path, + )); + } + + let key_count = CURATE_EVENTS_CMD_BENCH_KEYS; + let mapped_keys = (key_count * 98) / 100; // ~2% unmapped keys + let keys: Vec = (0..key_count) + .map(|i| { + if i % 3 == 0 { + format!("QM{i:04}:CA") + } else { + format!("QM{i:04}") + } + }) + .collect(); + + // Write provider_mapping.tsv + let mapping_path = temp.path.join("provider_mapping.tsv"); + { + let f = fs::File::create(&mapping_path).map_err(|source| { + CurateEventsCmdBenchError::FixtureIo { + path: mapping_path.clone(), + source, + } + })?; + let mut w = BufWriter::with_capacity(256 * 1024, f); + for (idx, key) in keys.iter().take(mapped_keys).enumerate() { + let listing_id = (idx as i32) + 1; + writeln!( + w, + "{DEFAULT_EVENTS_MAPPING_SOURCE}\t{key}\t2015-01-01\t\t{listing_id}" + ) + .map_err(|source| CurateEventsCmdBenchError::FixtureIo { + path: mapping_path.clone(), + source, + })?; + } + w.flush() + .map_err(|source| CurateEventsCmdBenchError::FixtureIo { + path: mapping_path.clone(), + source, + })?; + } + + let min_day = ymd_to_epoch_days(2015, 1, 2).unwrap_or(16_437); + let max_day = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); + let day_span = (max_day - min_day + 1) as u64; + + let earnings_target = ((rows as u64 * 15) / 1_000).max(1) as usize; + let filings_target = rows.saturating_sub(earnings_target); + + let filings_path = temp.path.join("qmFilings.bson"); + let earnings_path = temp.path.join("qmEarnings.bson"); + + let mut rng = SplitMix64::new(CURATE_EVENTS_CMD_BENCH_SEED); + + // Record a sample of (key_idx, epoch_day) from qualifying 8-K / News release filings so ~40% + // of synthetic earnings link to a real same-day filing. + let mut link_anchors: Vec<(usize, i32)> = Vec::with_capacity(earnings_target); + + { + let f = fs::File::create(&filings_path).map_err(|source| { + CurateEventsCmdBenchError::FixtureIo { + path: filings_path.clone(), + source, + } + })?; + let mut w = BufWriter::with_capacity(1024 * 1024, f); + let mut doc = RawDocumentBuf::new(); + + for i in 0..filings_target { + doc = RawDocumentBuf::new(); + let key_idx = (rng.next_u64() as usize) % key_count; + let epoch_day = min_day + (rng.next_u64() % day_span) as i32; + let (y, m, d) = epoch_days_to_ymd(epoch_day); + let hh = (rng.next_u64() % 18) + 6; // 06..=23 + let mm = rng.next_u64() % 60; + let ss = rng.next_u64() % 60; + let tz = if (4..=10).contains(&m) { "EDT" } else { "EST" }; + let form_idx = (rng.next_u64() as usize) % FORM_TYPES.len(); + let form_type = FORM_TYPES[form_idx]; + let roll = rng.next_u64() % 1_000; + + doc.append(cstr!("symbol"), keys[key_idx].as_str()); + doc.append( + cstr!("timefiled"), + format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02} {tz}"), + ); + if roll < 5 { + // ~0.5% semantic skip (blank formtype) + doc.append(cstr!("formtype"), " "); + } else { + doc.append(cstr!("formtype"), form_type); + if (form_idx == 0 || form_idx == 5) && link_anchors.len() < earnings_target { + link_anchors.push((key_idx, epoch_day)); + } + } + + if roll == 10 { + doc.append(cstr!("filingId"), 42_i32); // wrong type -> nulled + } else { + doc.append(cstr!("filingId"), format!("F-{i:08}")); + } + + if roll == 11 { + doc.append(cstr!("url"), false); // wrong type -> nulled + } else if i % 4 != 0 { + doc.append(cstr!("url"), format!("https://filings.example/{i}")); + } else { + doc.append(cstr!("url"), RawBsonRef::Null); + } + + w.write_all(doc.as_bytes()).map_err(|source| { + CurateEventsCmdBenchError::FixtureIo { + path: filings_path.clone(), + source, + } + })?; + } + let _ = doc; + w.flush() + .map_err(|source| CurateEventsCmdBenchError::FixtureIo { + path: filings_path.clone(), + source, + })?; + } + + { + let f = fs::File::create(&earnings_path).map_err(|source| { + CurateEventsCmdBenchError::FixtureIo { + path: earnings_path.clone(), + source, + } + })?; + let mut w = BufWriter::with_capacity(256 * 1024, f); + for i in 0..earnings_target { + let mut doc = RawDocumentBuf::new(); + let (key_idx, epoch_day) = if i % 5 < 2 && i < link_anchors.len() { + link_anchors[i] + } else { + ( + (rng.next_u64() as usize) % key_count, + min_day + (rng.next_u64() % day_span) as i32, + ) + }; + let (y, m, d) = epoch_days_to_ymd(epoch_day); + let roll = rng.next_u64() % 1_000; + + doc.append(cstr!("qmSearchCode"), keys[key_idx].as_str()); + if i % 2 == 0 { + doc.append( + cstr!("reportDate"), + BsonDateTime::from_millis(i64::from(epoch_day) * MILLIS_PER_DAY), + ); + } else { + doc.append(cstr!("reportDate"), format!("{y:04}-{m:02}-{d:02}")); + } + + if roll < 5 { + doc.append(cstr!("announceTime"), ""); // ~0.5% semantic skip + } else { + let at = ANNOUNCE_TIMES[(rng.next_u64() as usize) % ANNOUNCE_TIMES.len()]; + doc.append(cstr!("announceTime"), at); + } + + let fpe_day = epoch_day - 45; + if roll == 12 { + doc.append(cstr!("periodEndDate"), "bad-date"); + } else { + let (fy, fm, fd) = epoch_days_to_ymd(fpe_day); + doc.append(cstr!("periodEndDate"), format!("{fy:04}-{fm:02}-{fd:02}")); + } + + let eps = ((rng.next_u64() % 800) as f64 - 200.0) / 100.0; + if roll == 13 { + doc.append(cstr!("actualEps"), "bad-eps"); + } else { + doc.append(cstr!("actualEps"), eps); + } + doc.append( + cstr!("revenue"), + ((rng.next_u64() % 50_000) as i64 + 10) * 1_000_000, + ); + // Include post-hoc consensusEps to verify it is ignored on the hot path. + doc.append(cstr!("consensusEps"), eps + 0.05); + + w.write_all(doc.as_bytes()).map_err(|source| { + CurateEventsCmdBenchError::FixtureIo { + path: earnings_path.clone(), + source, + } + })?; + } + w.flush() + .map_err(|source| CurateEventsCmdBenchError::FixtureIo { + path: earnings_path.clone(), + source, + })?; + } + + let out_dir = temp.path.join("out"); + let args = CurateEventsArgs { + qm_filings: filings_path, + qm_earnings: earnings_path, + provider_mapping: mapping_path, + out_dir: out_dir.clone(), + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: "formtype".to_string(), + filings_filing_id_field: Some("filingId".to_string()), + filings_url_field: Some("url".to_string()), + earnings_key_field: DEFAULT_EARNINGS_KEY_FIELD.to_string(), + earnings_report_date_field: DEFAULT_EARNINGS_REPORT_DATE_FIELD.to_string(), + earnings_announce_time_field: DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD.to_string(), + earnings_fiscal_period_end_field: Some("periodEndDate".to_string()), + earnings_actual_eps_field: Some("actualEps".to_string()), + earnings_revenue_field: Some("revenue".to_string()), + mapping_source: DEFAULT_EVENTS_MAPPING_SOURCE.to_string(), + }; + + let timed = run_curate_events_timed(&args).map_err(CurateEventsCmdBenchError::Run)?; + + let read_back_rows = verify_parquet_events_row_count( + &out_dir, + timed.report.write_stats.rows_by_year.keys().copied(), + timed.report.write_stats.rows_written, + ) + .map_err(CurateEventsCmdBenchError::Verify)?; + + let total_bytes_read = timed.report.filings_bytes_read + timed.report.earnings_bytes_read; + let decode_elapsed_ms = timed.decode_elapsed_secs * 1_000.0; + let curate_elapsed_ms = timed.curate_elapsed_secs * 1_000.0; + let write_elapsed_ms = timed.write_elapsed_secs * 1_000.0; + let total_elapsed_secs = + timed.decode_elapsed_secs + timed.curate_elapsed_secs + timed.write_elapsed_secs; + let total_elapsed_ms = total_elapsed_secs * 1_000.0; + + let (decode_rows_per_sec, _) = compute_rates(rows, timed.decode_elapsed_secs); + let input_mb_per_sec = if timed.decode_elapsed_secs > 0.0 { + (total_bytes_read as f64 / MIB) / timed.decode_elapsed_secs + } else { + 0.0 + }; + let (curate_rows_per_sec, _) = compute_rates( + timed.report.curate_stats.builder.filings_in + + timed.report.curate_stats.builder.earnings_in, + timed.curate_elapsed_secs, + ); + let (write_rows_per_sec, _) = + compute_rates(timed.report.write_stats.rows_written, timed.write_elapsed_secs); + let write_mb_per_sec = if timed.write_elapsed_secs > 0.0 { + (timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_elapsed_secs + } else { + 0.0 + }; + let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs); + let total_extrap_full_secs = if total_rows_per_sec > 0.0 { + CURATE_EVENTS_FULL_DATASET_ROWS / total_rows_per_sec + } else { + 0.0 + }; + + let peak_chunk_bytes = timed + .report + .filings_peak_chunk_bytes + .max(timed.report.earnings_peak_chunk_bytes); + + let report = CurateEventsCmdBenchReport { + rows, + key_count, + filings_docs_framed: timed.report.filings_docs_framed, + filings_bytes_read: timed.report.filings_bytes_read, + earnings_docs_framed: timed.report.earnings_docs_framed, + earnings_bytes_read: timed.report.earnings_bytes_read, + peak_chunk_bytes, + rows_out: timed.report.curate_stats.rows_out, + filings_out: timed.report.curate_stats.filings_out, + earnings_out: timed.report.curate_stats.earnings_out, + listings_out: timed.report.curate_stats.listings_out, + files_written: timed.report.write_stats.files_written, + row_groups_written: timed.report.write_stats.row_groups_written, + bytes_written: timed.report.write_stats.bytes_written, + read_back_rows, + decode_elapsed_ms, + decode_rows_per_sec, + input_mb_per_sec, + curate_elapsed_ms, + curate_rows_per_sec, + write_elapsed_ms, + write_rows_per_sec, + write_mb_per_sec, + total_elapsed_ms, + total_rows_per_sec, + total_extrap_full_secs, + checksum: timed.checksum, + filings_decode: timed.report.filings_decode, + earnings_decode: timed.report.earnings_decode, + curate_stats: timed.report.curate_stats, + }; + + drop(temp); + Ok((report, temp_path)) +} + +/// Runs the fixed-seed end-to-end `curate-events` file -> Parquet benchmark for `rows` synthetic +/// `qmFilings` (~98.5%) + `qmEarnings` (~1.5%) BSON documents and `provider_mapping.tsv`. +pub fn run_curate_events_cmd_benchmark( + rows: usize, +) -> Result { + let (report, _) = run_curate_events_cmd_benchmark_tracked(rows)?; + Ok(report) +} + #[cfg(test)] mod tests { use super::*; @@ -11565,4 +12029,66 @@ mod tests { assert_eq!(report.read_back_rows, 0); assert_eq!(report.checksum, 0); } + + #[test] + fn curate_events_cmd_benchmark_small_run_is_deterministic_cleans_up_and_conserves_counts() { + let (a, dir_a) = run_curate_events_cmd_benchmark_tracked(5_000).unwrap(); + let (b, dir_b) = run_curate_events_cmd_benchmark_tracked(5_000).unwrap(); + + assert!(!dir_a.exists(), "temp dir {} should be removed", dir_a.display()); + assert!(!dir_b.exists(), "temp dir {} should be removed", dir_b.display()); + assert_eq!(a.rows, 5_000); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert_eq!(a.rows_out, b.rows_out); + assert!(a.rows_out > 0); + assert_eq!(a.read_back_rows, a.rows_out); + assert!(a.files_written > 0); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.peak_chunk_bytes > 0); + assert!(a.curate_stats.builder.earnings_linked_to_filing > 0); + assert!(a.curate_stats.builder.earnings_lagged_1605 > 0); + assert!(a.curate_stats.dropped_unmapped > 0); + + // Conservation invariants + assert_eq!(a.filings_docs_framed as usize, a.filings_decode.docs_in); + assert_eq!( + a.filings_decode.docs_in, + a.filings_decode.rows_out + a.filings_decode.skipped_total() + ); + assert_eq!(a.earnings_docs_framed as usize, a.earnings_decode.docs_in); + assert_eq!( + a.earnings_decode.docs_in, + a.earnings_decode.rows_out + a.earnings_decode.skipped_total() + ); + assert_eq!( + a.filings_decode.rows_out, + a.curate_stats.builder.filings_in + ); + assert_eq!( + a.earnings_decode.rows_out, + a.curate_stats.builder.earnings_in + ); + assert_eq!(a.curate_stats.rows_in, a.curate_stats.builder.rows_out); + assert_eq!( + a.curate_stats.rows_in, + a.curate_stats.rows_out + + a.curate_stats.dropped_unmapped + + a.curate_stats.listing_duplicate_collapsed + ); + } + + #[test] + fn curate_events_cmd_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_curate_events_cmd_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.filings_docs_framed, 0); + assert_eq!(report.earnings_docs_framed, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.checksum, 0); + } } diff --git a/tools/curate-etl/src/bson_qm_events.rs b/tools/curate-etl/src/bson_qm_events.rs new file mode 100644 index 00000000..bb2c2117 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_events.rs @@ -0,0 +1,1059 @@ +//! Zero-copy raw BSON decoders for MongoDB `qmFilings` and `qmEarnings` documents (`M1.2ae`). +//! +//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without +//! allocating a `bson::Document` or per-row `String`s, emitting borrowed [`RawQmFiling<&str>`] +//! and [`RawQmEarning<&str>`] views via a caller-supplied callback. +//! +//! # Verified vs. Caller-Configured Field Names +//! +//! Field defaults are restricted strictly to names established by in-repo evidence: +//! - **`qmFilings`** (`apps/stock/data-ingestion/src/handlers/qm/actions/filings.action.ts` +//! stores `{ ...filing, symbol, exchange }` — note it does **not** add `qmSearchCode` to the +//! stored document even though the upsert key names `['qmSearchCode', 'filingId']`; +//! `design/DATA-CONTRACTS.md` §1 establishes `timefiled`): +//! - Verified defaults: `key = "symbol"` ([`DEFAULT_FILINGS_KEY_FIELD`]), +//! `timefiled = "timefiled"` ([`DEFAULT_FILINGS_TIMEFILED_FIELD`]). +//! - Caller-configured (no default): `form_type` (required; live QuoteMedia field name is not +//! recorded in the repo), `filing_id` (optional), `url` (optional). +//! - **`qmEarnings`** (`apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts` +//! stores `{ ...earning, symbol, exchange, qmSearchCode, reportDate: new Date(...) }`; +//! `design/DATA-CONTRACTS.md` §1 establishes `reportDate`, `announceTime`, and forbids +//! `consensusEps` because it is overwritten post-hoc): +//! - Verified defaults: `key = "qmSearchCode"` ([`DEFAULT_EARNINGS_KEY_FIELD`]), +//! `report_date = "reportDate"` ([`DEFAULT_EARNINGS_REPORT_DATE_FIELD`]), +//! `announce_time = "announceTime"` ([`DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD`]). +//! - Caller-configured (optional, unconfigured unless passed): `fiscal_period_end`, +//! `actual_eps`, `revenue`. +//! - Confirm unverified live field names before the first QA/prod run via the read-only probe in +//! `apps/stock/data-pipeline/src/security-master/source-field-shapes.ts` +//! (`probe-source-field-shapes.ts --collections qmFilings,qmEarnings`). +//! - **Key-namespace alignment note:** `qmFilings` defaults to `symbol` while `qmEarnings` +//! defaults to `qmSearchCode`. On Canadian tickers (e.g. `SHOP` vs. `SHOP:CA`), operators must +//! pass `--filings-key-field` or `--earnings-key-field` as needed so both collections share the +//! same key namespace as `provider_mapping` for same-day earnings↔filing linking. +//! - **Point-in-time safety (`consensusEps`):** `consensusEps` is structurally omitted from +//! [`RawQmEarning`] and [`QmEarning`], never decoded from BSON, and explicitly rejected by +//! [`QmEarningsFieldNames::validate`] if configured on any role. +//! +//! # Decoding & Validation Rules +//! - Every element and nested subdocument/array/JS-with-scope (up to depth `128`) of each +//! [`RawDocument`] is scanned and structurally validated to completion before applying semantic +//! skip rules so structural BSON corruption always returns `Err(BsonQmEventsError::CorruptBson)` +//! rather than being masked by an earlier semantic skip. +//! - **`qmFilings`** deterministic skip priority: `key` → `timefiled` → `form_type`. All three +//! are required non-blank UTF-8 BSON `String`s passed verbatim (timestamp syntax validation +//! remains in [`crate::events::build_events`]). Optional `filing_id` and `url`: unconfigured, +//! absent, BSON `Null`, or blank `String` yields `None`; wrong BSON type yields `None` and +//! increments `nulled_wrong_type_*` (only on emitted rows). +//! - **`qmEarnings`** deterministic skip priority: `key` → `report_date` → `announce_time`. +//! `key` and `announce_time` are required non-blank UTF-8 BSON `String`s passed verbatim. +//! `report_date` accepts BSON `DateTime` (`timestamp_millis().div_euclid(86_400_000)` checked +//! to `i32`) or strict `YYYY-MM-DD` BSON `String`. Optional `fiscal_period_end` accepts absent / +//! `Null` / blank `String` (`None`), `DateTime` or strict `YYYY-MM-DD` `String` (`Some(i32)`), +//! wrong BSON type (`None` + `nulled_wrong_type_fiscal_period_end`), or malformed string / +//! out-of-range `DateTime` (`None` + `nulled_invalid_fiscal_period_end`, emitted rows only). +//! Optional `actual_eps` and `revenue` accept absent / `Null` (`None`), `Double` / `Int32` / +//! `Int64` (`Some(f64)`, non-finite sanitized downstream by `events::build_events`), or wrong +//! BSON type (`None` + `nulled_wrong_type_*`, emitted rows only). +//! - Conservation invariant on both stats structs: `docs_in == rows_out + skipped_total()`. + +use std::error::Error; +use std::fmt; + +use bson::raw::{RawBsonRef, RawDocument}; + +use crate::bson_eod_prices::{ + iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError, + MILLIS_PER_DAY, +}; +use crate::events::{QmEarning, QmFiling}; + +/// Verified default BSON field name for the `qmFilings` security key (`filings.action.ts`). +pub const DEFAULT_FILINGS_KEY_FIELD: &str = "symbol"; +/// Verified default BSON field name for `qmFilings.timefiled` (`design/DATA-CONTRACTS.md` §1). +pub const DEFAULT_FILINGS_TIMEFILED_FIELD: &str = "timefiled"; + +/// Verified default BSON field name for the `qmEarnings` security key (`events.action.ts`). +pub const DEFAULT_EARNINGS_KEY_FIELD: &str = "qmSearchCode"; +/// Verified default BSON field name for `qmEarnings.reportDate` (`events.action.ts`, `DATA-CONTRACTS.md` §1). +pub const DEFAULT_EARNINGS_REPORT_DATE_FIELD: &str = "reportDate"; +/// Verified default BSON field name for `qmEarnings.announceTime` (`design/DATA-CONTRACTS.md` §1). +pub const DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD: &str = "announceTime"; + +/// Borrowed BSON field-name configuration for decoding `qmFilings` documents. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct QmFilingsFieldNames<'a> { + pub key: &'a str, + pub timefiled: &'a str, + pub form_type: &'a str, + pub filing_id: Option<&'a str>, + pub url: Option<&'a str>, +} + +impl<'a> QmFilingsFieldNames<'a> { + /// Validates that every configured field name is non-empty/non-blank and that no two + /// configured roles point to the same BSON field name. + pub fn validate(&self) -> Result<(), BsonQmEventsError> { + let roles: [(&'static str, Option<&str>); 5] = [ + ("filings.key", Some(self.key)), + ("filings.timefiled", Some(self.timefiled)), + ("filings.form_type", Some(self.form_type)), + ("filings.filing_id", self.filing_id), + ("filings.url", self.url), + ]; + validate_role_names(&roles, false) + } +} + +/// Borrowed BSON field-name configuration for decoding `qmEarnings` documents. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct QmEarningsFieldNames<'a> { + pub key: &'a str, + pub report_date: &'a str, + pub announce_time: &'a str, + pub fiscal_period_end: Option<&'a str>, + pub actual_eps: Option<&'a str>, + pub revenue: Option<&'a str>, +} + +impl<'a> QmEarningsFieldNames<'a> { + /// Validates that every configured field name is non-empty/non-blank, that no two configured + /// roles point to the same BSON field name, and that no role maps to `consensusEps` / + /// `consensus_eps` (case-insensitive), which is forbidden per `design/DATA-CONTRACTS.md` §1. + pub fn validate(&self) -> Result<(), BsonQmEventsError> { + let roles: [(&'static str, Option<&str>); 6] = [ + ("earnings.key", Some(self.key)), + ("earnings.report_date", Some(self.report_date)), + ("earnings.announce_time", Some(self.announce_time)), + ("earnings.fiscal_period_end", self.fiscal_period_end), + ("earnings.actual_eps", self.actual_eps), + ("earnings.revenue", self.revenue), + ]; + validate_role_names(&roles, true) + } +} + +#[inline] +fn is_forbidden_consensus_eps_field(name: &str) -> bool { + let trimmed = name.trim(); + trimmed.eq_ignore_ascii_case("consensuseps") || trimmed.eq_ignore_ascii_case("consensus_eps") +} + +fn validate_role_names( + roles: &[(&'static str, Option<&str>)], + forbid_consensus_eps: bool, +) -> Result<(), BsonQmEventsError> { + for &(role, name_opt) in roles { + if let Some(name) = name_opt { + if name.trim().is_empty() { + return Err(BsonQmEventsError::InvalidFieldNames { + detail: format!("field name for '{role}' must not be empty or blank"), + }); + } + if forbid_consensus_eps && is_forbidden_consensus_eps_field(name) { + return Err(BsonQmEventsError::InvalidFieldNames { + detail: format!( + "field name '{name}' for '{role}' is forbidden (consensusEps is not point-in-time safe)" + ), + }); + } + } + } + + for i in 0..roles.len() { + let (role_a, Some(name_a)) = roles[i] else { + continue; + }; + for &(role_b, name_b_opt) in &roles[i + 1..] { + if let Some(name_b) = name_b_opt { + if name_a == name_b { + return Err(BsonQmEventsError::InvalidFieldNames { + detail: format!( + "roles '{role_a}' and '{role_b}' cannot share BSON field '{name_a}'" + ), + }); + } + } + } + } + + Ok(()) +} + +/// Borrowed zero-copy view of a single decoded `qmFilings` BSON document. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RawQmFiling<'a> { + pub key: &'a str, + pub timefiled: &'a str, + pub form_type: &'a str, + pub filing_id: Option<&'a str>, + pub url: Option<&'a str>, +} + +impl<'a> RawQmFiling<'a> { + /// Converts this borrowed view into an owned [`QmFiling`] using a caller-supplied key. + #[inline] + pub fn to_qm_filing(self, key: K) -> QmFiling { + QmFiling { + key, + timefiled: self.timefiled.to_string(), + form_type: self.form_type.to_string(), + filing_id: self.filing_id.map(str::to_string), + url: self.url.map(str::to_string), + } + } +} + +/// Borrowed zero-copy view of a single decoded `qmEarnings` BSON document. +/// +/// Structurally omits `consensusEps`, which is overwritten post-hoc in `qmEarnings` per +/// `design/DATA-CONTRACTS.md` §1 and is not point-in-time safe. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RawQmEarning<'a> { + pub key: &'a str, + pub report_date: i32, + pub announce_time: &'a str, + pub fiscal_period_end: Option, + pub actual_eps: Option, + pub revenue: Option, +} + +impl<'a> RawQmEarning<'a> { + /// Converts this borrowed view into an owned [`QmEarning`] using a caller-supplied key. + #[inline] + pub fn to_qm_earning(self, key: K) -> QmEarning { + QmEarning { + key, + report_date: self.report_date, + announce_time: self.announce_time.to_string(), + fiscal_period_end: self.fiscal_period_end, + actual_eps: self.actual_eps, + revenue: self.revenue, + } + } +} + +/// Typed errors returned while validating field configuration or decoding raw `qmFilings` / +/// `qmEarnings` BSON. +/// +/// Structural BSON framing or element errors fail closed and carry a `u64` byte offset; +/// every variant's `Display` output is a single line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BsonQmEventsError { + /// Invalid [`QmFilingsFieldNames`] or [`QmEarningsFieldNames`] configuration. + InvalidFieldNames { detail: String }, + /// Buffer ended before a complete 4-byte length prefix or declared document body. + TruncatedDocument { + offset: u64, + remaining: usize, + declared_len: Option, + }, + /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single + /// document slice). + CorruptDocumentLength { offset: u64, declared_len: i32 }, + /// Underlying BSON framing or element bytes were malformed. + CorruptBson { offset: u64, detail: String }, +} + +impl fmt::Display for BsonQmEventsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidFieldNames { detail } => { + write!(f, "invalid qmEvents field configuration: {detail}") + } + Self::TruncatedDocument { + offset, + remaining, + declared_len, + } => match declared_len { + Some(len) => write!( + f, + "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" + ), + None => write!( + f, + "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" + ), + }, + Self::CorruptDocumentLength { + offset, + declared_len, + } => write!( + f, + "corrupt BSON document length {declared_len} at byte offset {offset}" + ), + Self::CorruptBson { offset, detail } => { + write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") + } + } + } +} + +impl Error for BsonQmEventsError {} + +#[inline] +fn map_framing_error(err: BsonEodPriceError) -> BsonQmEventsError { + match err { + BsonEodPriceError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonQmEventsError::TruncatedDocument { + offset: offset as u64, + remaining, + declared_len, + }, + BsonEodPriceError::CorruptDocumentLength { + offset, + declared_len, + } => BsonQmEventsError::CorruptDocumentLength { + offset: offset as u64, + declared_len, + }, + BsonEodPriceError::CorruptBson { offset, detail } => BsonQmEventsError::CorruptBson { + offset: offset as u64, + detail, + }, + other => BsonQmEventsError::CorruptBson { + offset: 0, + detail: other.to_string(), + }, + } +} + +/// Per-batch decode accounting for `qmFilings`. +/// +/// Conservation invariant: +/// `docs_in == rows_out + skipped_total()` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BsonQmFilingsDecodeStats { + pub docs_in: usize, + pub rows_out: usize, + pub skipped_missing_key: usize, + pub skipped_wrong_key_type: usize, + pub skipped_empty_key: usize, + pub skipped_missing_timefiled: usize, + pub skipped_wrong_timefiled_type: usize, + pub skipped_empty_timefiled: usize, + pub skipped_missing_form_type: usize, + pub skipped_wrong_form_type_type: usize, + pub skipped_empty_form_type: usize, + pub nulled_wrong_type_filing_id: usize, + pub nulled_wrong_type_url: usize, +} + +impl BsonQmFilingsDecodeStats { + /// Total number of semantically skipped `qmFilings` documents across all skip categories. + #[inline] + pub fn skipped_total(&self) -> usize { + self.skipped_missing_key + + self.skipped_wrong_key_type + + self.skipped_empty_key + + self.skipped_missing_timefiled + + self.skipped_wrong_timefiled_type + + self.skipped_empty_timefiled + + self.skipped_missing_form_type + + self.skipped_wrong_form_type_type + + self.skipped_empty_form_type + } + + /// Accumulates counters from another batch into `self`. + #[inline] + pub fn merge(&mut self, other: &Self) { + self.docs_in += other.docs_in; + self.rows_out += other.rows_out; + self.skipped_missing_key += other.skipped_missing_key; + self.skipped_wrong_key_type += other.skipped_wrong_key_type; + self.skipped_empty_key += other.skipped_empty_key; + self.skipped_missing_timefiled += other.skipped_missing_timefiled; + self.skipped_wrong_timefiled_type += other.skipped_wrong_timefiled_type; + self.skipped_empty_timefiled += other.skipped_empty_timefiled; + self.skipped_missing_form_type += other.skipped_missing_form_type; + self.skipped_wrong_form_type_type += other.skipped_wrong_form_type_type; + self.skipped_empty_form_type += other.skipped_empty_form_type; + self.nulled_wrong_type_filing_id += other.nulled_wrong_type_filing_id; + self.nulled_wrong_type_url += other.nulled_wrong_type_url; + } +} + +impl std::ops::AddAssign for BsonQmFilingsDecodeStats { + #[inline] + fn add_assign(&mut self, rhs: Self) { + self.merge(&rhs); + } +} + +/// Per-batch decode accounting for `qmEarnings`. +/// +/// Conservation invariant: +/// `docs_in == rows_out + skipped_total()` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct BsonQmEarningsDecodeStats { + pub docs_in: usize, + pub rows_out: usize, + pub skipped_missing_key: usize, + pub skipped_wrong_key_type: usize, + pub skipped_empty_key: usize, + pub skipped_missing_report_date: usize, + pub skipped_wrong_report_date_type: usize, + pub skipped_invalid_report_date: usize, + pub skipped_report_date_out_of_range: usize, + pub skipped_missing_announce_time: usize, + pub skipped_wrong_announce_time_type: usize, + pub skipped_empty_announce_time: usize, + pub nulled_wrong_type_fiscal_period_end: usize, + pub nulled_invalid_fiscal_period_end: usize, + pub nulled_wrong_type_actual_eps: usize, + pub nulled_wrong_type_revenue: usize, +} + +impl BsonQmEarningsDecodeStats { + /// Total number of semantically skipped `qmEarnings` documents across all skip categories. + #[inline] + pub fn skipped_total(&self) -> usize { + self.skipped_missing_key + + self.skipped_wrong_key_type + + self.skipped_empty_key + + self.skipped_missing_report_date + + self.skipped_wrong_report_date_type + + self.skipped_invalid_report_date + + self.skipped_report_date_out_of_range + + self.skipped_missing_announce_time + + self.skipped_wrong_announce_time_type + + self.skipped_empty_announce_time + } + + /// Accumulates counters from another batch into `self`. + #[inline] + pub fn merge(&mut self, other: &Self) { + self.docs_in += other.docs_in; + self.rows_out += other.rows_out; + self.skipped_missing_key += other.skipped_missing_key; + self.skipped_wrong_key_type += other.skipped_wrong_key_type; + self.skipped_empty_key += other.skipped_empty_key; + self.skipped_missing_report_date += other.skipped_missing_report_date; + self.skipped_wrong_report_date_type += other.skipped_wrong_report_date_type; + self.skipped_invalid_report_date += other.skipped_invalid_report_date; + self.skipped_report_date_out_of_range += other.skipped_report_date_out_of_range; + self.skipped_missing_announce_time += other.skipped_missing_announce_time; + self.skipped_wrong_announce_time_type += other.skipped_wrong_announce_time_type; + self.skipped_empty_announce_time += other.skipped_empty_announce_time; + self.nulled_wrong_type_fiscal_period_end += other.nulled_wrong_type_fiscal_period_end; + self.nulled_invalid_fiscal_period_end += other.nulled_invalid_fiscal_period_end; + self.nulled_wrong_type_actual_eps += other.nulled_wrong_type_actual_eps; + self.nulled_wrong_type_revenue += other.nulled_wrong_type_revenue; + } +} + +impl std::ops::AddAssign for BsonQmEarningsDecodeStats { + #[inline] + fn add_assign(&mut self, rhs: Self) { + self.merge(&rhs); + } +} + +enum ReqStrState<'a> { + Missing, + WrongType, + Empty, + Valid(&'a str), +} + +enum OptStrState<'a> { + None, + WrongType, + Valid(&'a str), +} + +enum ReqDateState { + Missing, + WrongType, + Invalid, + OutOfRange, + Valid(i32), +} + +enum OptDateState { + None, + WrongType, + Invalid, + Valid(i32), +} + +enum OptNumState { + None, + WrongType, + Valid(f64), +} + +#[inline] +fn decode_required_str<'a>(val: RawBsonRef<'a>) -> ReqStrState<'a> { + match val { + RawBsonRef::String(s) => { + if s.trim().is_empty() { + ReqStrState::Empty + } else { + ReqStrState::Valid(s) + } + } + _ => ReqStrState::WrongType, + } +} + +#[inline] +fn decode_optional_str<'a>(val: RawBsonRef<'a>) -> OptStrState<'a> { + match val { + RawBsonRef::Null => OptStrState::None, + RawBsonRef::String(s) => { + if s.trim().is_empty() { + OptStrState::None + } else { + OptStrState::Valid(s) + } + } + _ => OptStrState::WrongType, + } +} + +#[inline] +fn decode_required_date(val: RawBsonRef<'_>) -> ReqDateState { + match val { + RawBsonRef::DateTime(dt) => { + let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); + match i32::try_from(days) { + Ok(d) => ReqDateState::Valid(d), + Err(_) => ReqDateState::OutOfRange, + } + } + RawBsonRef::String(s) => match parse_ymd_strict_days(s) { + Some(d) => ReqDateState::Valid(d), + None => ReqDateState::Invalid, + }, + _ => ReqDateState::WrongType, + } +} + +#[inline] +fn decode_optional_date(val: RawBsonRef<'_>) -> OptDateState { + match val { + RawBsonRef::Null => OptDateState::None, + RawBsonRef::DateTime(dt) => { + let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY); + match i32::try_from(days) { + Ok(d) => OptDateState::Valid(d), + Err(_) => OptDateState::Invalid, + } + } + RawBsonRef::String(s) => { + if s.trim().is_empty() { + OptDateState::None + } else { + match parse_ymd_strict_days(s) { + Some(d) => OptDateState::Valid(d), + None => OptDateState::Invalid, + } + } + } + _ => OptDateState::WrongType, + } +} + +#[inline] +fn decode_optional_number(val: RawBsonRef<'_>) -> OptNumState { + match val { + RawBsonRef::Null => OptNumState::None, + RawBsonRef::Double(v) => OptNumState::Valid(v), + RawBsonRef::Int32(v) => OptNumState::Valid(f64::from(v)), + RawBsonRef::Int64(v) => OptNumState::Valid(v as f64), + _ => OptNumState::WrongType, + } +} + +/// Maximum recursive nesting depth accepted while validating raw BSON documents and arrays. +const MAX_BSON_VALIDATION_DEPTH: usize = 128; + +#[inline] +fn is_exact_array_index(key: &str, expected: usize) -> bool { + let bytes = key.as_bytes(); + if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') { + return false; + } + let mut parsed: usize = 0; + for &b in bytes { + if !b.is_ascii_digit() { + return false; + } + let digit = usize::from(b - b'0'); + match parsed.checked_mul(10).and_then(|n| n.checked_add(digit)) { + Some(next) => parsed = next, + None => return false, + } + } + parsed == expected +} + +fn validate_raw_bson_value( + val: RawBsonRef<'_>, + doc_offset: u64, + field_name: &str, + depth: usize, +) -> Result<(), BsonQmEventsError> { + match val { + RawBsonRef::Document(subdoc) => { + validate_raw_document(subdoc, doc_offset, field_name, depth + 1) + } + RawBsonRef::Array(arr) => { + if depth >= MAX_BSON_VALIDATION_DEPTH { + return Err(BsonQmEventsError::CorruptBson { + offset: doc_offset, + detail: format!( + "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" + ), + }); + } + for (expected_idx, elem_res) in arr.iter_elements().enumerate() { + let elem = elem_res.map_err(|err| BsonQmEventsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{field_name}': {err}"), + })?; + let key = elem.key().as_str(); + if !is_exact_array_index(key, expected_idx) { + return Err(BsonQmEventsError::CorruptBson { + offset: doc_offset, + detail: format!( + "field '{field_name}': invalid BSON array index '{key}' at position {expected_idx}" + ), + }); + } + let item = elem.value().map_err(|err| BsonQmEventsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{field_name}': {err}"), + })?; + validate_raw_bson_value(item, doc_offset, field_name, depth + 1)?; + } + Ok(()) + } + RawBsonRef::JavaScriptCodeWithScope(code_with_scope) => { + validate_raw_document(code_with_scope.scope, doc_offset, field_name, depth + 1) + } + _ => Ok(()), + } +} + +fn validate_raw_document( + doc: &RawDocument, + doc_offset: u64, + field_name: &str, + depth: usize, +) -> Result<(), BsonQmEventsError> { + if depth > MAX_BSON_VALIDATION_DEPTH { + return Err(BsonQmEventsError::CorruptBson { + offset: doc_offset, + detail: format!( + "field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}" + ), + }); + } + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonQmEventsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{field_name}': {err}"), + })?; + let val = elem.value().map_err(|err| BsonQmEventsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{field_name}': {err}"), + })?; + validate_raw_bson_value(val, doc_offset, field_name, depth)?; + } + Ok(()) +} + +fn decode_qm_filing_doc_at<'a, F>( + doc: &'a RawDocument, + doc_offset: u64, + fields: &QmFilingsFieldNames<'_>, + mut on_row: F, +) -> Result +where + F: FnMut(RawQmFiling<'a>), +{ + let mut stats = BsonQmFilingsDecodeStats { + docs_in: 1, + ..BsonQmFilingsDecodeStats::default() + }; + + let mut key_state = ReqStrState::Missing; + let mut timefiled_state = ReqStrState::Missing; + let mut form_type_state = ReqStrState::Missing; + let mut filing_id_state = OptStrState::None; + let mut url_state = OptStrState::None; + + // Scan and structurally validate every element and nested raw value to completion so + // structural BSON corruption always fails closed rather than being masked by a semantic skip. + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonQmEventsError::CorruptBson { + offset: doc_offset, + detail: err.to_string(), + })?; + let name = elem.key().as_str(); + let val = elem.value().map_err(|err| BsonQmEventsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{name}': {err}"), + })?; + validate_raw_bson_value(val, doc_offset, name, 0)?; + + if name == fields.key { + key_state = decode_required_str(val); + } else if name == fields.timefiled { + timefiled_state = decode_required_str(val); + } else if name == fields.form_type { + form_type_state = decode_required_str(val); + } else if fields.filing_id == Some(name) { + filing_id_state = decode_optional_str(val); + } else if fields.url == Some(name) { + url_state = decode_optional_str(val); + } + } + + // Apply deterministic semantic skip priority: key -> timefiled -> form_type. + let key = match key_state { + ReqStrState::Valid(s) => s, + ReqStrState::Missing => { + stats.skipped_missing_key += 1; + return Ok(stats); + } + ReqStrState::WrongType => { + stats.skipped_wrong_key_type += 1; + return Ok(stats); + } + ReqStrState::Empty => { + stats.skipped_empty_key += 1; + return Ok(stats); + } + }; + + let timefiled = match timefiled_state { + ReqStrState::Valid(s) => s, + ReqStrState::Missing => { + stats.skipped_missing_timefiled += 1; + return Ok(stats); + } + ReqStrState::WrongType => { + stats.skipped_wrong_timefiled_type += 1; + return Ok(stats); + } + ReqStrState::Empty => { + stats.skipped_empty_timefiled += 1; + return Ok(stats); + } + }; + + let form_type = match form_type_state { + ReqStrState::Valid(s) => s, + ReqStrState::Missing => { + stats.skipped_missing_form_type += 1; + return Ok(stats); + } + ReqStrState::WrongType => { + stats.skipped_wrong_form_type_type += 1; + return Ok(stats); + } + ReqStrState::Empty => { + stats.skipped_empty_form_type += 1; + return Ok(stats); + } + }; + + let filing_id = match filing_id_state { + OptStrState::Valid(s) => Some(s), + OptStrState::None => None, + OptStrState::WrongType => { + stats.nulled_wrong_type_filing_id += 1; + None + } + }; + + let url = match url_state { + OptStrState::Valid(s) => Some(s), + OptStrState::None => None, + OptStrState::WrongType => { + stats.nulled_wrong_type_url += 1; + None + } + }; + + stats.rows_out += 1; + on_row(RawQmFiling { + key, + timefiled, + form_type, + filing_id, + url, + }); + Ok(stats) +} + +fn decode_qm_earning_doc_at<'a, F>( + doc: &'a RawDocument, + doc_offset: u64, + fields: &QmEarningsFieldNames<'_>, + mut on_row: F, +) -> Result +where + F: FnMut(RawQmEarning<'a>), +{ + let mut stats = BsonQmEarningsDecodeStats { + docs_in: 1, + ..BsonQmEarningsDecodeStats::default() + }; + + let mut key_state = ReqStrState::Missing; + let mut date_state = ReqDateState::Missing; + let mut announce_state = ReqStrState::Missing; + let mut fiscal_end_state = OptDateState::None; + let mut actual_eps_state = OptNumState::None; + let mut revenue_state = OptNumState::None; + + // Scan and structurally validate every element and nested raw value to completion so + // structural BSON corruption always fails closed rather than being masked by a semantic skip. + // Note: `consensusEps` is never matched or decoded. + for elem_res in doc.iter_elements() { + let elem = elem_res.map_err(|err| BsonQmEventsError::CorruptBson { + offset: doc_offset, + detail: err.to_string(), + })?; + let name = elem.key().as_str(); + let val = elem.value().map_err(|err| BsonQmEventsError::CorruptBson { + offset: doc_offset, + detail: format!("field '{name}': {err}"), + })?; + validate_raw_bson_value(val, doc_offset, name, 0)?; + + if name == fields.key { + key_state = decode_required_str(val); + } else if name == fields.report_date { + date_state = decode_required_date(val); + } else if name == fields.announce_time { + announce_state = decode_required_str(val); + } else if fields.fiscal_period_end == Some(name) { + fiscal_end_state = decode_optional_date(val); + } else if fields.actual_eps == Some(name) { + actual_eps_state = decode_optional_number(val); + } else if fields.revenue == Some(name) { + revenue_state = decode_optional_number(val); + } + } + + // Apply deterministic semantic skip priority: key -> report_date -> announce_time. + let key = match key_state { + ReqStrState::Valid(s) => s, + ReqStrState::Missing => { + stats.skipped_missing_key += 1; + return Ok(stats); + } + ReqStrState::WrongType => { + stats.skipped_wrong_key_type += 1; + return Ok(stats); + } + ReqStrState::Empty => { + stats.skipped_empty_key += 1; + return Ok(stats); + } + }; + + let report_date = match date_state { + ReqDateState::Valid(d) => d, + ReqDateState::Missing => { + stats.skipped_missing_report_date += 1; + return Ok(stats); + } + ReqDateState::WrongType => { + stats.skipped_wrong_report_date_type += 1; + return Ok(stats); + } + ReqDateState::Invalid => { + stats.skipped_invalid_report_date += 1; + return Ok(stats); + } + ReqDateState::OutOfRange => { + stats.skipped_report_date_out_of_range += 1; + return Ok(stats); + } + }; + + let announce_time = match announce_state { + ReqStrState::Valid(s) => s, + ReqStrState::Missing => { + stats.skipped_missing_announce_time += 1; + return Ok(stats); + } + ReqStrState::WrongType => { + stats.skipped_wrong_announce_time_type += 1; + return Ok(stats); + } + ReqStrState::Empty => { + stats.skipped_empty_announce_time += 1; + return Ok(stats); + } + }; + + let fiscal_period_end = match fiscal_end_state { + OptDateState::Valid(d) => Some(d), + OptDateState::None => None, + OptDateState::WrongType => { + stats.nulled_wrong_type_fiscal_period_end += 1; + None + } + OptDateState::Invalid => { + stats.nulled_invalid_fiscal_period_end += 1; + None + } + }; + + let actual_eps = match actual_eps_state { + OptNumState::Valid(v) => Some(v), + OptNumState::None => None, + OptNumState::WrongType => { + stats.nulled_wrong_type_actual_eps += 1; + None + } + }; + + let revenue = match revenue_state { + OptNumState::Valid(v) => Some(v), + OptNumState::None => None, + OptNumState::WrongType => { + stats.nulled_wrong_type_revenue += 1; + None + } + }; + + stats.rows_out += 1; + on_row(RawQmEarning { + key, + report_date, + announce_time, + fiscal_period_end, + actual_eps, + revenue, + }); + Ok(stats) +} + +/// Decodes a single `&RawDocument` representing a `qmFilings` MongoDB document in one forward +/// pass without allocating a `bson::Document` or per-row `String`s. +pub fn decode_qm_filing_doc<'a, F>( + doc: &'a RawDocument, + fields: &QmFilingsFieldNames<'_>, + on_row: F, +) -> Result +where + F: FnMut(RawQmFiling<'a>), +{ + fields.validate()?; + decode_qm_filing_doc_at(doc, 0, fields, on_row) +} + +/// Decodes a single length-prefixed raw BSON document byte slice representing a `qmFilings` +/// document. +pub fn decode_qm_filing_bytes<'a, F>( + bytes: &'a [u8], + fields: &QmFilingsFieldNames<'_>, + on_row: F, +) -> Result +where + F: FnMut(RawQmFiling<'a>), +{ + fields.validate()?; + let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; + decode_qm_filing_doc_at(doc, 0, fields, on_row) +} + +/// Streams a concatenated length-prefixed BSON buffer of `qmFilings` documents through +/// [`decode_qm_filing_doc`], emitting every valid [`RawQmFiling<&str>`] to `on_row` and failing +/// closed on any structural BSON framing or element corruption. +/// +/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`. +pub fn decode_qm_filing_buffer<'a, F>( + buf: &'a [u8], + fields: &QmFilingsFieldNames<'_>, + mut on_row: F, +) -> Result +where + F: FnMut(RawQmFiling<'a>), +{ + fields.validate()?; + let mut total = BsonQmFilingsDecodeStats::default(); + let mut iter = iter_raw_bson_docs(buf); + while let Some(item) = iter.next_with_offset() { + match item { + Ok((offset, doc)) => { + let doc_stats = decode_qm_filing_doc_at(doc, offset as u64, fields, &mut on_row)?; + total += doc_stats; + } + Err((_, err)) => return Err(map_framing_error(err)), + } + } + Ok(total) +} + +/// Decodes a single `&RawDocument` representing a `qmEarnings` MongoDB document in one forward +/// pass without allocating a `bson::Document` or per-row `String`s. +pub fn decode_qm_earning_doc<'a, F>( + doc: &'a RawDocument, + fields: &QmEarningsFieldNames<'_>, + on_row: F, +) -> Result +where + F: FnMut(RawQmEarning<'a>), +{ + fields.validate()?; + decode_qm_earning_doc_at(doc, 0, fields, on_row) +} + +/// Decodes a single length-prefixed raw BSON document byte slice representing a `qmEarnings` +/// document. +pub fn decode_qm_earning_bytes<'a, F>( + bytes: &'a [u8], + fields: &QmEarningsFieldNames<'_>, + on_row: F, +) -> Result +where + F: FnMut(RawQmEarning<'a>), +{ + fields.validate()?; + let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; + decode_qm_earning_doc_at(doc, 0, fields, on_row) +} + +/// Streams a concatenated length-prefixed BSON buffer of `qmEarnings` documents through +/// [`decode_qm_earning_doc`], emitting every valid [`RawQmEarning<&str>`] to `on_row` and failing +/// closed on any structural BSON framing or element corruption. +/// +/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`. +pub fn decode_qm_earning_buffer<'a, F>( + buf: &'a [u8], + fields: &QmEarningsFieldNames<'_>, + mut on_row: F, +) -> Result +where + F: FnMut(RawQmEarning<'a>), +{ + fields.validate()?; + let mut total = BsonQmEarningsDecodeStats::default(); + let mut iter = iter_raw_bson_docs(buf); + while let Some(item) = iter.next_with_offset() { + match item { + Ok((offset, doc)) => { + let doc_stats = decode_qm_earning_doc_at(doc, offset as u64, fields, &mut on_row)?; + total += doc_stats; + } + Err((_, err)) => return Err(map_framing_error(err)), + } + } + Ok(total) +} + +#[cfg(test)] +#[path = "bson_qm_events_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/bson_qm_events_tests.rs b/tools/curate-etl/src/bson_qm_events_tests.rs new file mode 100644 index 00000000..01df13f6 --- /dev/null +++ b/tools/curate-etl/src/bson_qm_events_tests.rs @@ -0,0 +1,500 @@ +use bson::{rawdoc, DateTime, RawDocumentBuf}; + +use super::*; +use crate::split::ymd_to_epoch_days; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn dt_from_ymd(y: i32, m: u32, d: u32) -> DateTime { + DateTime::from_millis(i64::from(day(y, m, d)) * MILLIS_PER_DAY) +} + +fn default_filings_fields() -> QmFilingsFieldNames<'static> { + QmFilingsFieldNames { + key: DEFAULT_FILINGS_KEY_FIELD, + timefiled: DEFAULT_FILINGS_TIMEFILED_FIELD, + form_type: "formtype", + filing_id: Some("filingId"), + url: Some("url"), + } +} + +fn default_earnings_fields() -> QmEarningsFieldNames<'static> { + QmEarningsFieldNames { + key: DEFAULT_EARNINGS_KEY_FIELD, + report_date: DEFAULT_EARNINGS_REPORT_DATE_FIELD, + announce_time: DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, + fiscal_period_end: Some("periodEndDate"), + actual_eps: Some("actualEps"), + revenue: Some("revenue"), + } +} + +fn make_raw_doc_with_invalid_utf8_unused_field(include_required: bool) -> Vec { + let mut body = Vec::new(); + if include_required { + // String field "symbol": "AAPL" + body.push(0x02); + body.extend_from_slice(b"symbol\0"); + body.extend_from_slice(&5_i32.to_le_bytes()); + body.extend_from_slice(b"AAPL\0"); + // String field "timefiled": "2025-01-31T06:01:27 EST" + let ts = b"2025-01-31T06:01:27 EST"; + body.push(0x02); + body.extend_from_slice(b"timefiled\0"); + body.extend_from_slice(&((ts.len() + 1) as i32).to_le_bytes()); + body.extend_from_slice(ts); + body.push(0); + // String field "formtype": "10-K" + body.push(0x02); + body.extend_from_slice(b"formtype\0"); + body.extend_from_slice(&5_i32.to_le_bytes()); + body.extend_from_slice(b"10-K\0"); + } + // Unused string field "extra" with invalid UTF-8 bytes [0xFF, 0xFE] + body.push(0x02); + body.extend_from_slice(b"extra\0"); + body.extend_from_slice(&3_i32.to_le_bytes()); + body.extend_from_slice(&[0xFF, 0xFE, 0x00]); + body.push(0x00); // doc terminator + + let total_len = (4 + body.len()) as i32; + let mut out = Vec::with_capacity(total_len as usize); + out.extend_from_slice(&total_len.to_le_bytes()); + out.extend_from_slice(&body); + out +} + +fn make_raw_doc_with_bad_array_index() -> Vec { + // Nested array "badArr" with key "1" instead of "0" + let mut arr_body = Vec::new(); + arr_body.push(0x10); // Int32 + arr_body.extend_from_slice(b"1\0"); + arr_body.extend_from_slice(&42_i32.to_le_bytes()); + arr_body.push(0x00); + let arr_len = (4 + arr_body.len()) as i32; + + let mut body = Vec::new(); + body.push(0x04); // Array + body.extend_from_slice(b"badArr\0"); + body.extend_from_slice(&arr_len.to_le_bytes()); + body.extend_from_slice(&arr_body); + body.push(0x00); + + let total_len = (4 + body.len()) as i32; + let mut out = Vec::with_capacity(total_len as usize); + out.extend_from_slice(&total_len.to_le_bytes()); + out.extend_from_slice(&body); + out +} + +#[test] +fn field_name_validation_rejects_blank_colliding_and_consensus_eps() { + assert!(default_filings_fields().validate().is_ok()); + assert!(default_earnings_fields().validate().is_ok()); + + // Blank required / optional filings fields + let mut f = default_filings_fields(); + f.form_type = " "; + let err = f.validate().unwrap_err(); + assert!(matches!(err, BsonQmEventsError::InvalidFieldNames { .. })); + assert!(!err.to_string().contains('\n')); + + let mut f = default_filings_fields(); + f.url = Some(""); + assert!(matches!( + f.validate(), + Err(BsonQmEventsError::InvalidFieldNames { .. }) + )); + + // Colliding filings fields + let mut f = default_filings_fields(); + f.form_type = DEFAULT_FILINGS_KEY_FIELD; + assert!(matches!( + f.validate(), + Err(BsonQmEventsError::InvalidFieldNames { .. }) + )); + + // Blank earnings field + let mut e = default_earnings_fields(); + e.actual_eps = Some(" \t "); + assert!(matches!( + e.validate(), + Err(BsonQmEventsError::InvalidFieldNames { .. }) + )); + + // Colliding earnings fields + let mut e = default_earnings_fields(); + e.revenue = Some("actualEps"); + assert!(matches!( + e.validate(), + Err(BsonQmEventsError::InvalidFieldNames { .. }) + )); + + // Forbidden consensusEps / consensus_eps (case-insensitive) on any role + for bad in ["consensusEps", "CONSENSUSEPS", "consensus_eps", " Consensus_Eps "] { + let mut e = default_earnings_fields(); + e.actual_eps = Some(bad); + let err = e.validate().unwrap_err(); + assert!(matches!(err, BsonQmEventsError::InvalidFieldNames { .. })); + assert!(err.to_string().contains("consensusEps")); + assert!(!err.to_string().contains('\n')); + + let mut e2 = default_earnings_fields(); + e2.revenue = Some(bad); + assert!(matches!( + e2.validate(), + Err(BsonQmEventsError::InvalidFieldNames { .. }) + )); + } +} + +#[test] +fn qm_filings_happy_path_and_optionals() { + let fields = default_filings_fields(); + let doc1 = rawdoc! { + "symbol": " AAPL ", // preserved verbatim + "timefiled": "2025-01-31T06:01:27 EST", + "formtype": "10-Q", + "filingId": "0000320193-25-000008", + "url": "https://www.sec.gov/Archives/edgar/data/320193/10q.htm", + "extra": { "nested": [1, 2, 3] }, + }; + let doc2 = rawdoc! { + "symbol": "SHOP:CA", + "timefiled": "2025-07-15T17:05:00 EDT", + "formtype": "News release", + "filingId": null, + "url": " ", + }; + + let mut buf = Vec::new(); + buf.extend_from_slice(doc1.as_bytes()); + buf.extend_from_slice(doc2.as_bytes()); + + let mut rows = Vec::new(); + let stats = decode_qm_filing_buffer(&buf, &fields, |r| { + rows.push(r.to_qm_filing(r.key.to_string())); + }) + .expect("decode succeeds"); + + assert_eq!(stats.docs_in, 2); + assert_eq!(stats.rows_out, 2); + assert_eq!(stats.skipped_total(), 0); + assert_eq!(stats.nulled_wrong_type_filing_id, 0); + assert_eq!(stats.nulled_wrong_type_url, 0); + assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total()); + + assert_eq!(rows[0].key, " AAPL "); + assert_eq!(rows[0].timefiled, "2025-01-31T06:01:27 EST"); + assert_eq!(rows[0].form_type, "10-Q"); + assert_eq!(rows[0].filing_id.as_deref(), Some("0000320193-25-000008")); + assert_eq!( + rows[0].url.as_deref(), + Some("https://www.sec.gov/Archives/edgar/data/320193/10q.htm") + ); + + assert_eq!(rows[1].key, "SHOP:CA"); + assert_eq!(rows[1].filing_id, None); + assert_eq!(rows[1].url, None); +} + +#[test] +fn qm_filings_skip_reasons_priority_and_optional_wrong_type_counters() { + let fields = default_filings_fields(); + let docs: Vec = vec![ + // 1. missing key (even though timefiled & formtype are also missing + optional wrong type) + rawdoc! { "filingId": 123, "url": false }, + // 2. wrong key type (priority over missing timefiled) + rawdoc! { "symbol": 42 }, + // 3. empty key (priority over missing formtype) + rawdoc! { "symbol": " ", "timefiled": "2025-01-31T06:01:27 EST" }, + // 4. missing timefiled (priority over missing formtype) + rawdoc! { "symbol": "AAPL" }, + // 5. wrong timefiled type + rawdoc! { "symbol": "AAPL", "timefiled": 12345, "formtype": "8-K" }, + // 6. empty timefiled + rawdoc! { "symbol": "AAPL", "timefiled": "", "formtype": "8-K" }, + // 7. missing formtype + rawdoc! { "symbol": "AAPL", "timefiled": "2025-01-31T06:01:27 EST" }, + // 8. wrong formtype type + rawdoc! { "symbol": "AAPL", "timefiled": "2025-01-31T06:01:27 EST", "formtype": 10 }, + // 9. empty formtype (with wrong-type optionals that must NOT increment nulled counters) + rawdoc! { + "symbol": "AAPL", + "timefiled": "2025-01-31T06:01:27 EST", + "formtype": " \t ", + "filingId": 999, + "url": 888, + }, + // 10. valid row with wrong-type optionals -> emitted with None + nulled counters incremented + rawdoc! { + "symbol": "MSFT", + "timefiled": "2025-02-01T16:30:00 EST", + "formtype": "8-K", + "filingId": 999, + "url": true, + }, + ]; + + let mut buf = Vec::new(); + for d in &docs { + buf.extend_from_slice(d.as_bytes()); + } + + let mut emitted = Vec::new(); + let stats = decode_qm_filing_buffer(&buf, &fields, |r| { + emitted.push(r.to_qm_filing(r.key.to_string())); + }) + .expect("decode succeeds"); + + assert_eq!(stats.docs_in, 10); + assert_eq!(stats.rows_out, 1); + assert_eq!(stats.skipped_missing_key, 1); + assert_eq!(stats.skipped_wrong_key_type, 1); + assert_eq!(stats.skipped_empty_key, 1); + assert_eq!(stats.skipped_missing_timefiled, 1); + assert_eq!(stats.skipped_wrong_timefiled_type, 1); + assert_eq!(stats.skipped_empty_timefiled, 1); + assert_eq!(stats.skipped_missing_form_type, 1); + assert_eq!(stats.skipped_wrong_form_type_type, 1); + assert_eq!(stats.skipped_empty_form_type, 1); + assert_eq!(stats.skipped_total(), 9); + assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total()); + assert_eq!(stats.nulled_wrong_type_filing_id, 1); + assert_eq!(stats.nulled_wrong_type_url, 1); + + assert_eq!(emitted.len(), 1); + assert_eq!(emitted[0].key, "MSFT"); + assert_eq!(emitted[0].filing_id, None); + assert_eq!(emitted[0].url, None); +} + +#[test] +fn qm_earnings_happy_path_types_and_ignores_consensus_eps() { + let fields = default_earnings_fields(); + let doc1 = rawdoc! { + "qmSearchCode": "AAPL", + "reportDate": dt_from_ymd(2025, 1, 30), + "announceTime": "AMC", + "periodEndDate": dt_from_ymd(2024, 12, 28), + "actualEps": 2.40_f64, + "revenue": 124_300_000_000_i64, + "consensusEps": 2.35_f64, + }; + let doc2 = rawdoc! { + "qmSearchCode": "SHOP:CA", + "reportDate": "2025-02-11", + "announceTime": "N/A", + "periodEndDate": "2024-12-31", + "actualEps": 1_i32, + "revenue": 2_810_000_000.5_f64, + "consensusEps": 0.99_f64, + }; + let doc3 = rawdoc! { + "qmSearchCode": "TD:CA", + "reportDate": "2025-02-27", + "announceTime": "BTO", + "periodEndDate": null, + "actualEps": null, + "revenue": null, + }; + + let mut buf = Vec::new(); + buf.extend_from_slice(doc1.as_bytes()); + buf.extend_from_slice(doc2.as_bytes()); + buf.extend_from_slice(doc3.as_bytes()); + + let mut rows = Vec::new(); + let stats = decode_qm_earning_buffer(&buf, &fields, |r| { + rows.push(r.to_qm_earning(r.key.to_string())); + }) + .expect("decode succeeds"); + + assert_eq!(stats.docs_in, 3); + assert_eq!(stats.rows_out, 3); + assert_eq!(stats.skipped_total(), 0); + assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total()); + + assert_eq!(rows[0].key, "AAPL"); + assert_eq!(rows[0].report_date, day(2025, 1, 30)); + assert_eq!(rows[0].announce_time, "AMC"); + assert_eq!(rows[0].fiscal_period_end, Some(day(2024, 12, 28))); + assert_eq!(rows[0].actual_eps, Some(2.40)); + assert_eq!(rows[0].revenue, Some(124_300_000_000.0)); + + assert_eq!(rows[1].key, "SHOP:CA"); + assert_eq!(rows[1].report_date, day(2025, 2, 11)); + assert_eq!(rows[1].announce_time, "N/A"); + assert_eq!(rows[1].fiscal_period_end, Some(day(2024, 12, 31))); + assert_eq!(rows[1].actual_eps, Some(1.0)); + assert_eq!(rows[1].revenue, Some(2_810_000_000.5)); + + assert_eq!(rows[2].key, "TD:CA"); + assert_eq!(rows[2].fiscal_period_end, None); + assert_eq!(rows[2].actual_eps, None); + assert_eq!(rows[2].revenue, None); +} + +#[test] +fn qm_earnings_skip_reasons_priority_and_optional_nulling_counters() { + let fields = default_earnings_fields(); + let oor_dt = DateTime::from_millis(i64::MAX); + let docs: Vec = vec![ + // 1. missing key (with bad optionals that must not increment nulled counters) + rawdoc! { "periodEndDate": 123, "actualEps": "bad", "revenue": false }, + // 2. wrong key type + rawdoc! { "qmSearchCode": 100 }, + // 3. empty key + rawdoc! { "qmSearchCode": " ", "reportDate": "2025-01-30", "announceTime": "AMC" }, + // 4. missing reportDate + rawdoc! { "qmSearchCode": "AAPL", "announceTime": "AMC" }, + // 5. wrong reportDate type + rawdoc! { "qmSearchCode": "AAPL", "reportDate": 20250130, "announceTime": "AMC" }, + // 6. invalid reportDate string + rawdoc! { "qmSearchCode": "AAPL", "reportDate": "2025-02-30", "announceTime": "AMC" }, + // 7. out-of-range reportDate DateTime + rawdoc! { "qmSearchCode": "AAPL", "reportDate": oor_dt, "announceTime": "AMC" }, + // 8. missing announceTime + rawdoc! { "qmSearchCode": "AAPL", "reportDate": "2025-01-30" }, + // 9. wrong announceTime type + rawdoc! { "qmSearchCode": "AAPL", "reportDate": "2025-01-30", "announceTime": 1 }, + // 10. empty announceTime (bad optionals must NOT increment nulled counters) + rawdoc! { + "qmSearchCode": "AAPL", + "reportDate": "2025-01-30", + "announceTime": " ", + "periodEndDate": "not-a-date", + "actualEps": "1.2", + "revenue": "500", + }, + // 11. valid row with wrong-type optionals + rawdoc! { + "qmSearchCode": "NVDA", + "reportDate": "2025-02-26", + "announceTime": "AMC", + "periodEndDate": 20250126, + "actualEps": "0.89", + "revenue": true, + }, + // 12. valid row with invalid string fiscal_period_end + rawdoc! { + "qmSearchCode": "AMD", + "reportDate": "2025-02-04", + "announceTime": "AMC", + "periodEndDate": "2024-13-01", + "actualEps": 1.09, + "revenue": 7_658_000_000_i64, + }, + // 13. valid row with out-of-range DateTime fiscal_period_end + rawdoc! { + "qmSearchCode": "INTC", + "reportDate": "2025-01-30", + "announceTime": "AMC", + "periodEndDate": oor_dt, + }, + ]; + + let mut buf = Vec::new(); + for d in &docs { + buf.extend_from_slice(d.as_bytes()); + } + + let mut emitted = Vec::new(); + let stats = decode_qm_earning_buffer(&buf, &fields, |r| { + emitted.push(r.to_qm_earning(r.key.to_string())); + }) + .expect("decode succeeds"); + + assert_eq!(stats.docs_in, 13); + assert_eq!(stats.rows_out, 3); + assert_eq!(stats.skipped_missing_key, 1); + assert_eq!(stats.skipped_wrong_key_type, 1); + assert_eq!(stats.skipped_empty_key, 1); + assert_eq!(stats.skipped_missing_report_date, 1); + assert_eq!(stats.skipped_wrong_report_date_type, 1); + assert_eq!(stats.skipped_invalid_report_date, 1); + assert_eq!(stats.skipped_report_date_out_of_range, 1); + assert_eq!(stats.skipped_missing_announce_time, 1); + assert_eq!(stats.skipped_wrong_announce_time_type, 1); + assert_eq!(stats.skipped_empty_announce_time, 1); + assert_eq!(stats.skipped_total(), 10); + assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total()); + + assert_eq!(stats.nulled_wrong_type_fiscal_period_end, 1); + assert_eq!(stats.nulled_invalid_fiscal_period_end, 2); + assert_eq!(stats.nulled_wrong_type_actual_eps, 1); + assert_eq!(stats.nulled_wrong_type_revenue, 1); + + assert_eq!(emitted.len(), 3); + assert_eq!(emitted[0].fiscal_period_end, None); + assert_eq!(emitted[0].actual_eps, None); + assert_eq!(emitted[0].revenue, None); + assert_eq!(emitted[1].fiscal_period_end, None); + assert_eq!(emitted[1].actual_eps, Some(1.09)); + assert_eq!(emitted[2].fiscal_period_end, None); +} + +#[test] +fn corrupt_and_truncated_bson_fail_closed_even_when_required_fields_missing() { + let f_fields = default_filings_fields(); + let e_fields = default_earnings_fields(); + + // Invalid UTF-8 in unused field with NO required fields present -> must still Err(CorruptBson) + let corrupt_no_req = make_raw_doc_with_invalid_utf8_unused_field(false); + assert!(matches!( + decode_qm_filing_bytes(&corrupt_no_req, &f_fields, |_| {}), + Err(BsonQmEventsError::CorruptBson { offset: 0, .. }) + )); + assert!(matches!( + decode_qm_earning_bytes(&corrupt_no_req, &e_fields, |_| {}), + Err(BsonQmEventsError::CorruptBson { offset: 0, .. }) + )); + + // Invalid UTF-8 in unused field with required fields present -> must Err(CorruptBson) + let corrupt_with_req = make_raw_doc_with_invalid_utf8_unused_field(true); + assert!(matches!( + decode_qm_filing_bytes(&corrupt_with_req, &f_fields, |_| {}), + Err(BsonQmEventsError::CorruptBson { offset: 0, .. }) + )); + + // Bad nested array index -> Err(CorruptBson) + let bad_arr = make_raw_doc_with_bad_array_index(); + assert!(matches!( + decode_qm_filing_bytes(&bad_arr, &f_fields, |_| {}), + Err(BsonQmEventsError::CorruptBson { offset: 0, .. }) + )); + assert!(matches!( + decode_qm_earning_bytes(&bad_arr, &e_fields, |_| {}), + Err(BsonQmEventsError::CorruptBson { offset: 0, .. }) + )); + + // Truncated BSON buffer after one valid doc -> Err(TruncatedDocument) with exact offset + let valid_doc = rawdoc! { + "symbol": "AAPL", + "timefiled": "2025-01-31T06:01:27 EST", + "formtype": "10-K", + }; + let mut trunc_buf = valid_doc.as_bytes().to_vec(); + let expected_offset = trunc_buf.len() as u64; + trunc_buf.extend_from_slice(&valid_doc.as_bytes()[..10]); + + let err = decode_qm_filing_buffer(&trunc_buf, &f_fields, |_| {}).unwrap_err(); + assert!(matches!( + err, + BsonQmEventsError::TruncatedDocument { offset, .. } if offset == expected_offset + )); + assert!(!err.to_string().contains('\n')); + + // Corrupt document length (< 5) -> Err(CorruptDocumentLength) + let bad_len = 3_i32.to_le_bytes(); + assert!(matches!( + decode_qm_earning_buffer(&bad_len, &e_fields, |_| {}), + Err(BsonQmEventsError::CorruptDocumentLength { + offset: 0, + declared_len: 3 + }) + )); +} diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs index 3f755d56..f7b18e97 100644 --- a/tools/curate-etl/src/bson_stream.rs +++ b/tools/curate-etl/src/bson_stream.rs @@ -31,6 +31,11 @@ use crate::bson_qm_actions::{ decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, BsonQmActionError, RawQmDividend, RawQmSplit, }; +use crate::bson_qm_events::{ + decode_qm_earning_buffer, decode_qm_filing_buffer, BsonQmEarningsDecodeStats, + BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, QmFilingsFieldNames, + RawQmEarning, RawQmFiling, +}; use crate::bson_te_market_data::{ decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError, }; @@ -855,6 +860,151 @@ where decode_ceo_shorts_chunks(&mut chunk_reader, fields, on_row) } +/// Terminal error returned by [`decode_qm_filings_chunks`], [`decode_qm_filings_stream`], +/// [`decode_qm_earnings_chunks`], and [`decode_qm_earnings_stream`]. +#[derive(Debug)] +pub enum BsonQmEventsStreamError { + Stream(BsonStreamError), + Decode(BsonQmEventsError), +} + +impl fmt::Display for BsonQmEventsStreamError { + 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 BsonQmEventsStreamError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::Stream(err) => Some(err), + Self::Decode(err) => Some(err), + } + } +} + +impl From for BsonQmEventsStreamError { + fn from(err: BsonStreamError) -> Self { + Self::Stream(err) + } +} + +impl From for BsonQmEventsStreamError { + fn from(err: BsonQmEventsError) -> Self { + Self::Decode(err) + } +} + +#[inline] +fn rebase_qm_events_error(base: u64, err: BsonQmEventsError) -> BsonQmEventsError { + match err { + BsonQmEventsError::TruncatedDocument { + offset, + remaining, + declared_len, + } => BsonQmEventsError::TruncatedDocument { + offset: base.saturating_add(offset), + remaining, + declared_len, + }, + BsonQmEventsError::CorruptDocumentLength { + offset, + declared_len, + } => BsonQmEventsError::CorruptDocumentLength { + offset: base.saturating_add(offset), + declared_len, + }, + BsonQmEventsError::CorruptBson { offset, detail } => BsonQmEventsError::CorruptBson { + offset: base.saturating_add(offset), + detail, + }, + other => other, + } +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_filing_buffer`], +/// accumulating [`BsonQmFilingsDecodeStats`] and rebasing structural BSON error offsets to +/// absolute stream byte offsets. +pub fn decode_qm_filings_chunks( + reader: &mut RawBsonChunkReader, + fields: &QmFilingsFieldNames<'_>, + mut on_row: F, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmFiling<'a>), +{ + fields.validate()?; + let mut total = BsonQmFilingsDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = decode_qm_filing_buffer(chunk.bytes, fields, &mut on_row) + .map_err(|err| BsonQmEventsStreamError::Decode(rebase_qm_events_error(base, err)))?; + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `qmFilings` [`std::io::Read`] source through +/// [`decode_qm_filing_buffer`] with bounded memory. +pub fn decode_qm_filings_stream( + reader: R, + options: BsonStreamOptions, + fields: &QmFilingsFieldNames<'_>, + on_row: F, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmFiling<'a>), +{ + fields.validate()?; + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_qm_filings_chunks(&mut chunk_reader, fields, on_row) +} + +/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_earning_buffer`], +/// accumulating [`BsonQmEarningsDecodeStats`] and rebasing structural BSON error offsets to +/// absolute stream byte offsets. +pub fn decode_qm_earnings_chunks( + reader: &mut RawBsonChunkReader, + fields: &QmEarningsFieldNames<'_>, + mut on_row: F, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmEarning<'a>), +{ + fields.validate()?; + let mut total = BsonQmEarningsDecodeStats::default(); + while let Some(chunk) = reader.next_chunk()? { + let base = chunk.start_offset; + let chunk_stats = decode_qm_earning_buffer(chunk.bytes, fields, &mut on_row) + .map_err(|err| BsonQmEventsStreamError::Decode(rebase_qm_events_error(base, err)))?; + total += chunk_stats; + } + Ok(total) +} + +/// Streams a concatenated raw BSON `qmEarnings` [`std::io::Read`] source through +/// [`decode_qm_earning_buffer`] with bounded memory. +pub fn decode_qm_earnings_stream( + reader: R, + options: BsonStreamOptions, + fields: &QmEarningsFieldNames<'_>, + on_row: F, +) -> Result +where + R: io::Read, + F: for<'a> FnMut(RawQmEarning<'a>), +{ + fields.validate()?; + let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; + decode_qm_earnings_chunks(&mut chunk_reader, fields, 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 f895a8e5..15745b65 100644 --- a/tools/curate-etl/src/bson_stream_tests.rs +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -1871,3 +1871,145 @@ fn ceo_shorts_stream_rebases_corrupt_bson_offset_and_rejects_invalid_fields() { "expected rebased CorruptBson at {expected_offset}, got {err:?}" ); } + +#[test] +fn qm_filings_and_earnings_stream_match_buffer_and_rebase_corrupt_offsets() { + use super::{ + decode_qm_earnings_chunks, decode_qm_earnings_stream, decode_qm_filings_chunks, + decode_qm_filings_stream, BsonQmEventsStreamError, BsonStreamOptions, RawBsonChunkReader, + }; + use crate::bson_qm_events::{ + decode_qm_earning_buffer, decode_qm_filing_buffer, BsonQmEventsError, + QmEarningsFieldNames, QmFilingsFieldNames, + }; + + let f_fields = QmFilingsFieldNames { + key: "symbol", + timefiled: "timefiled", + form_type: "formtype", + filing_id: Some("filingId"), + url: Some("url"), + }; + let e_fields = QmEarningsFieldNames { + key: "qmSearchCode", + report_date: "reportDate", + announce_time: "announceTime", + fiscal_period_end: Some("periodEndDate"), + actual_eps: Some("actualEps"), + revenue: Some("revenue"), + }; + + let mut filings_buf = Vec::new(); + let mut earnings_buf = Vec::new(); + for i in 0..30_i32 { + let mut fdoc = RawDocumentBuf::new(); + fdoc.append(cstr!("symbol"), format!("SYM{}", i % 5)); + fdoc.append(cstr!("timefiled"), format!("2025-01-{:02}T10:00:00 EST", 1 + (i % 20))); + if i % 9 == 0 { + fdoc.append(cstr!("formtype"), 99_i32); // semantic skip + } else { + fdoc.append(cstr!("formtype"), if i % 2 == 0 { "8-K" } else { "10-Q" }); + } + fdoc.append(cstr!("filingId"), format!("F-{i}")); + fdoc.append(cstr!("url"), format!("https://example.test/{i}")); + filings_buf.extend_from_slice(fdoc.as_bytes()); + + let mut edoc = RawDocumentBuf::new(); + edoc.append(cstr!("qmSearchCode"), format!("SYM{}", i % 5)); + if i % 2 == 0 { + edoc.append(cstr!("reportDate"), format!("2025-01-{:02}", 1 + (i % 20))); + } else { + let ms = (20_089_i64 + i64::from(i % 20)) * 86_400_000; + edoc.append(cstr!("reportDate"), bson::DateTime::from_millis(ms)); + } + if i % 10 == 0 { + edoc.append(cstr!("announceTime"), ""); // semantic skip + } else { + edoc.append(cstr!("announceTime"), if i % 3 == 0 { "N/A" } else { "AMC" }); + } + edoc.append(cstr!("actualEps"), 1.25 + f64::from(i) * 0.1); + edoc.append(cstr!("consensusEps"), 999.0_f64); + earnings_buf.extend_from_slice(edoc.as_bytes()); + } + + let mut exp_filings = Vec::new(); + let exp_f_stats = decode_qm_filing_buffer(&filings_buf, &f_fields, |r| { + exp_filings.push(r.to_qm_filing(r.key.to_owned())); + }) + .expect("filings buffer decode"); + + let mut exp_earnings = Vec::new(); + let exp_e_stats = decode_qm_earning_buffer(&earnings_buf, &e_fields, |r| { + exp_earnings.push(r.to_qm_earning(r.key.to_owned())); + }) + .expect("earnings buffer decode"); + + for cap in [96usize, 256, 1024] { + let opts = BsonStreamOptions { + chunk_capacity_bytes: cap, + max_doc_bytes: 4096, + }; + let mut f_reader = + RawBsonChunkReader::with_options(FixedStepReader::new(&filings_buf, 29), opts).unwrap(); + let mut got_filings = Vec::new(); + let got_f_stats = decode_qm_filings_chunks(&mut f_reader, &f_fields, |r| { + got_filings.push(r.to_qm_filing(r.key.to_owned())); + }) + .expect("filings chunk decode"); + assert_eq!(got_f_stats, exp_f_stats, "filings cap={cap}"); + assert_eq!(got_filings, exp_filings, "filings rows cap={cap}"); + + let mut e_reader = + RawBsonChunkReader::with_options(FixedStepReader::new(&earnings_buf, 31), opts).unwrap(); + let mut got_earnings = Vec::new(); + let got_e_stats = decode_qm_earnings_chunks(&mut e_reader, &e_fields, |r| { + got_earnings.push(r.to_qm_earning(r.key.to_owned())); + }) + .expect("earnings chunk decode"); + assert_eq!(got_e_stats, exp_e_stats, "earnings cap={cap}"); + assert_eq!(got_earnings, exp_earnings, "earnings rows cap={cap}"); + } + + // Corrupt BSON mid-stream rebases offset accurately for both filings and earnings streams. + let mut good_f = RawDocumentBuf::new(); + good_f.append(cstr!("symbol"), "AAPL"); + good_f.append(cstr!("timefiled"), "2025-01-31T06:01:27 EST"); + good_f.append(cstr!("formtype"), "10-K"); + let good_f_bytes = good_f.into_bytes(); + + let mut corrupt = RawDocumentBuf::new(); + corrupt.append(cstr!("symbol"), "BAD"); + corrupt.append(cstr!("z"), 1_i32); + let mut corrupt_bytes = corrupt.into_bytes(); + let z_pos = corrupt_bytes + .windows(3) + .position(|w| w == [0x10, b'z', 0x00]) + .expect("locate z"); + corrupt_bytes[z_pos] = 0x7e; + + let mut combined = Vec::new(); + combined.extend_from_slice(&good_f_bytes); + combined.extend_from_slice(&good_f_bytes); + let expected_offset = combined.len() as u64; + combined.extend_from_slice(&corrupt_bytes); + + let opts = BsonStreamOptions { + chunk_capacity_bytes: good_f_bytes.len(), + max_doc_bytes: 4096, + }; + let err_f = decode_qm_filings_stream(Cursor::new(combined.clone()), opts, &f_fields, |_| {}) + .unwrap_err(); + assert!(matches!( + err_f, + BsonQmEventsStreamError::Decode(BsonQmEventsError::CorruptBson { offset, .. }) + if offset == expected_offset + )); + + let err_e = + decode_qm_earnings_stream(Cursor::new(combined), opts, &e_fields, |_| {}).unwrap_err(); + assert!(matches!( + err_e, + BsonQmEventsStreamError::Decode(BsonQmEventsError::CorruptBson { offset, .. }) + if offset == expected_offset + )); +} diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 1c317f91..fa8d15f9 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -13,18 +13,23 @@ use crate::bench::{ DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_BARS_CMD_BENCH_ROWS, DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_CURATE_CORPORATE_ACTIONS_CMD_BENCH_EVENTS, DEFAULT_CURATE_EVENTS_BENCH_ROWS, - DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_FX_CMD_BENCH_ROWS, - DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, - DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, - DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, - DEFAULT_PARQUET_EVENTS_BENCH_ROWS, DEFAULT_PARQUET_FX_BENCH_ROWS, - DEFAULT_PARQUET_SHORTS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, - DEFAULT_SHORTS_BENCH_ROWS, + DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS, + DEFAULT_CURATE_FX_CMD_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, + DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, + DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, + DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, + DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS, + DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS, }; use crate::bson_ceo_shorts::{DEFAULT_KEY_FIELD, DEFAULT_REPORT_DATE_FIELD}; +use crate::bson_qm_events::{ + DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, DEFAULT_EARNINGS_KEY_FIELD, + DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD, +}; use crate::run_curate_adj::CurateAdjFactorsArgs; use crate::run_curate_bars::{CurateBars1dArgs, DEFAULT_CURATE_BARS_REL_TOLERANCE}; use crate::run_curate_corporate_actions::CurateCorporateActionsArgs; +use crate::run_curate_events::{CurateEventsArgs, DEFAULT_EVENTS_MAPPING_SOURCE}; use crate::run_curate_fx::{is_supported_te_symbol, CurateFx1dArgs, DEFAULT_TE_SYMBOL}; use crate::run_curate_shorts::{CurateShortsArgs, DEFAULT_MAPPING_SOURCE}; @@ -38,6 +43,7 @@ pub enum CliAction { CurateCorporateActions(CurateCorporateActionsArgs), CurateFx1d(CurateFx1dArgs), CurateShorts(CurateShortsArgs), + CurateEvents(CurateEventsArgs), BenchSplit(usize), BenchAdj(usize), BenchCorporateActions(usize), @@ -60,6 +66,7 @@ pub enum CliAction { BenchCurateShorts(usize), BenchCurateShortsCommand(usize), BenchCurateEvents(usize), + BenchCurateEventsCmd(usize), BenchCurateFx(usize), BenchCurateFxCmd(usize), BenchCurateAdj(usize), @@ -86,6 +93,8 @@ pub fn format_usage(name: &str, version: &str) -> String { Curate USD/CAD fx_1d from eodPrices + teMarketData BSON files into fx_1d/part.parquet (default --te-symbol: {DEFAULT_TE_SYMBOL})\n\ {name} curate-shorts --ceo-shorts --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ Curate shorts from ceoShorts BSON + provider_mapping TSV into shorts/part.parquet (defaults: --key-field {DEFAULT_KEY_FIELD}, --report-date-field {DEFAULT_REPORT_DATE_FIELD}, --mapping-source {DEFAULT_MAPPING_SOURCE})\n\ + {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ + Curate events from qmFilings + qmEarnings BSON + provider_mapping TSV into events/year=YYYY/part.parquet (defaults: --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --earnings-key-field {DEFAULT_EARNINGS_KEY_FIELD}, --earnings-report-date-field {DEFAULT_EARNINGS_REPORT_DATE_FIELD}, --earnings-announce-time-field {DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD}, --mapping-source {DEFAULT_EVENTS_MAPPING_SOURCE})\n\ {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ {name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\ {name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\ @@ -108,6 +117,7 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\ {name} bench-curate-shorts-command [rows] Run fixed-seed end-to-end curate-shorts file->Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS})\n\ {name} bench-curate-events [rows] Run fixed-seed events curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_BENCH_ROWS})\n\ + {name} bench-curate-events-cmd [rows] Run fixed-seed end-to-end curate-events file->Parquet benchmark (default: {DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS})\n\ {name} bench-curate-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})\n\ {name} bench-curate-fx-cmd [rows] Run fixed-seed end-to-end curate-fx-1d file->Parquet benchmark (default: {DEFAULT_CURATE_FX_CMD_BENCH_ROWS})\n\ {name} bench-curate-adj [events] Run fixed-seed adj_factors curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_ADJ_BENCH_EVENTS})\n\ @@ -128,6 +138,7 @@ pub fn format_usage_stderr(name: &str) -> String { {name} curate-corporate-actions --qm-splits --qm-dividends --provider-mapping [--delistings ] --out \n\ {name} curate-fx-1d --eod-prices --te-market-data [--te-symbol ] --out \n\ {name} curate-shorts --ceo-shorts --provider-mapping --out --shares-short-field [--key-field ] [--report-date-field ] [--net-change-field ] [--pct-float-field ] [--mapping-source ]\n\ + {name} curate-events --qm-filings --qm-earnings --provider-mapping --out --filings-form-type-field [--filings-key-field ] [--filings-timefiled-field ] [--filings-filing-id-field ] [--filings-url-field ] [--earnings-key-field ] [--earnings-report-date-field ] [--earnings-announce-time-field ] [--earnings-fiscal-period-end-field ] [--earnings-actual-eps-field ] [--earnings-revenue-field ] [--mapping-source ]\n\ {name} bench-split [rows]\n\ {name} bench-adj [events]\n\ {name} bench-corporate-actions [events]\n\ @@ -150,6 +161,7 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-curate-shorts [rows]\n\ {name} bench-curate-shorts-command [rows]\n\ {name} bench-curate-events [rows]\n\ + {name} bench-curate-events-cmd [rows]\n\ {name} bench-curate-fx [rows]\n\ {name} bench-curate-fx-cmd [rows]\n\ {name} bench-curate-adj [events]\n\ @@ -562,6 +574,190 @@ fn parse_curate_shorts_args(args: &[&str]) -> Result { Ok(parsed) } +fn parse_curate_events_args(args: &[&str]) -> Result { + let mut qm_filings: Option = None; + let mut qm_earnings: Option = None; + let mut provider_mapping: Option = None; + let mut out_dir: Option = None; + let mut filings_key_field: Option = None; + let mut filings_timefiled_field: Option = None; + let mut filings_form_type_field: Option = None; + let mut filings_filing_id_field: Option = None; + let mut filings_url_field: Option = None; + let mut earnings_key_field: Option = None; + let mut earnings_report_date_field: Option = None; + let mut earnings_announce_time_field: Option = None; + let mut earnings_fiscal_period_end_field: Option = None; + let mut earnings_actual_eps_field: Option = None; + let mut earnings_revenue_field: Option = None; + let mut mapping_source: Option = None; + + let mut i = 0usize; + while i < args.len() { + let token = args[i]; + if !token.starts_with("--") { + return Err(format!( + "unexpected positional argument '{token}' for curate-events" + )); + } + + let (flag, value) = if let Some((k, v)) = token.split_once('=') { + i += 1; + (k, v) + } else { + let Some(&v) = args.get(i + 1) else { + return Err(format!("missing value for flag '{token}'")); + }; + if v.starts_with("--") { + return Err(format!("missing value for flag '{token}'")); + } + i += 2; + (token, v) + }; + + let set_path = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate flag '{flag_name}'")); + } + if raw.is_empty() { + return Err(format!("empty value for flag '{flag_name}'")); + } + *slot = Some(PathBuf::from(raw)); + Ok(()) + }; + + let set_name = |slot: &mut Option, flag_name: &str, raw: &str| -> Result<(), String> { + if slot.is_some() { + return Err(format!("duplicate flag '{flag_name}'")); + } + if raw.trim().is_empty() { + return Err(format!("empty value for flag '{flag_name}'")); + } + *slot = Some(raw.to_string()); + Ok(()) + }; + + match flag { + "--qm-filings" => set_path(&mut qm_filings, "--qm-filings", value)?, + "--qm-earnings" => set_path(&mut qm_earnings, "--qm-earnings", value)?, + "--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?, + "--out" => set_path(&mut out_dir, "--out", value)?, + "--filings-key-field" => { + set_name(&mut filings_key_field, "--filings-key-field", value)?; + } + "--filings-timefiled-field" => { + set_name( + &mut filings_timefiled_field, + "--filings-timefiled-field", + value, + )?; + } + "--filings-form-type-field" => { + set_name( + &mut filings_form_type_field, + "--filings-form-type-field", + value, + )?; + } + "--filings-filing-id-field" => { + set_name( + &mut filings_filing_id_field, + "--filings-filing-id-field", + value, + )?; + } + "--filings-url-field" => { + set_name(&mut filings_url_field, "--filings-url-field", value)?; + } + "--earnings-key-field" => { + set_name(&mut earnings_key_field, "--earnings-key-field", value)?; + } + "--earnings-report-date-field" => { + set_name( + &mut earnings_report_date_field, + "--earnings-report-date-field", + value, + )?; + } + "--earnings-announce-time-field" => { + set_name( + &mut earnings_announce_time_field, + "--earnings-announce-time-field", + value, + )?; + } + "--earnings-fiscal-period-end-field" => { + set_name( + &mut earnings_fiscal_period_end_field, + "--earnings-fiscal-period-end-field", + value, + )?; + } + "--earnings-actual-eps-field" => { + set_name( + &mut earnings_actual_eps_field, + "--earnings-actual-eps-field", + value, + )?; + } + "--earnings-revenue-field" => { + set_name( + &mut earnings_revenue_field, + "--earnings-revenue-field", + value, + )?; + } + "--mapping-source" => set_name(&mut mapping_source, "--mapping-source", value)?, + other => return Err(format!("unknown flag '{other}' for curate-events")), + } + } + + let qm_filings = + qm_filings.ok_or_else(|| "missing required flag '--qm-filings'".to_string())?; + let qm_earnings = + qm_earnings.ok_or_else(|| "missing required flag '--qm-earnings'".to_string())?; + let provider_mapping = + provider_mapping.ok_or_else(|| "missing required flag '--provider-mapping'".to_string())?; + let out_dir = out_dir.ok_or_else(|| "missing required flag '--out'".to_string())?; + let filings_form_type_field = filings_form_type_field + .ok_or_else(|| "missing required flag '--filings-form-type-field'".to_string())?; + + let parsed = CurateEventsArgs { + qm_filings, + qm_earnings, + provider_mapping, + out_dir, + filings_key_field: filings_key_field + .unwrap_or_else(|| DEFAULT_FILINGS_KEY_FIELD.to_string()), + filings_timefiled_field: filings_timefiled_field + .unwrap_or_else(|| DEFAULT_FILINGS_TIMEFILED_FIELD.to_string()), + filings_form_type_field, + filings_filing_id_field, + filings_url_field, + earnings_key_field: earnings_key_field + .unwrap_or_else(|| DEFAULT_EARNINGS_KEY_FIELD.to_string()), + earnings_report_date_field: earnings_report_date_field + .unwrap_or_else(|| DEFAULT_EARNINGS_REPORT_DATE_FIELD.to_string()), + earnings_announce_time_field: earnings_announce_time_field + .unwrap_or_else(|| DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD.to_string()), + earnings_fiscal_period_end_field, + earnings_actual_eps_field, + earnings_revenue_field, + mapping_source: mapping_source + .unwrap_or_else(|| DEFAULT_EVENTS_MAPPING_SOURCE.to_string()), + }; + + parsed + .filings_field_names() + .validate() + .map_err(|e| e.to_string())?; + parsed + .earnings_field_names() + .validate() + .map_err(|e| e.to_string())?; + Ok(parsed) +} + /// Parses CLI arguments (excluding `argv[0]`) into a [`CliAction`]. pub fn parse_args(args: &[String]) -> Result { let slices: Vec<&str> = args.iter().map(String::as_str).collect(); @@ -582,6 +778,7 @@ pub fn parse_args(args: &[String]) -> Result { } ["curate-fx-1d", rest @ ..] => parse_curate_fx_1d_args(rest).map(CliAction::CurateFx1d), ["curate-shorts", rest @ ..] => parse_curate_shorts_args(rest).map(CliAction::CurateShorts), + ["curate-events", rest @ ..] => parse_curate_events_args(rest).map(CliAction::CurateEvents), ["bench-split"] => Ok(CliAction::BenchSplit(DEFAULT_BENCH_ROWS)), ["bench-split", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchSplit(n)), @@ -814,6 +1011,18 @@ pub fn parse_args(args: &[String]) -> Result { ["bench-curate-events", _, ..] => { Err("too many arguments for bench-curate-events".to_string()) } + ["bench-curate-events-cmd"] => Ok(CliAction::BenchCurateEventsCmd( + DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, + )), + ["bench-curate-events-cmd", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchCurateEventsCmd(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-curate-events-cmd", _, ..] => { + Err("too many arguments for bench-curate-events-cmd".to_string()) + } ["bench-curate-fx"] => Ok(CliAction::BenchCurateFx(DEFAULT_CURATE_FX_BENCH_ROWS)), ["bench-curate-fx", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchCurateFx(n)), @@ -2211,4 +2420,198 @@ mod tests { assert!(parse_args(&to_args(&["bench-curate-shorts-command", "abc"])).is_err()); assert!(parse_args(&to_args(&["bench-curate-shorts-command", "1", "2"])).is_err()); } + + #[test] + fn curate_events_and_bench_curate_events_cmd_parsing_and_usage() { + let usage = format_usage("curate-etl", "0.1.0"); + let stderr_usage = format_usage_stderr("curate-etl"); + assert!(usage.contains("curate-events --qm-filings")); + assert!(usage.contains("bench-curate-events-cmd [rows]")); + assert!(stderr_usage.contains("curate-events --qm-filings")); + assert!(stderr_usage.contains("bench-curate-events-cmd [rows]")); + + // Minimal required flags with defaults + let action = parse_args(&to_args(&[ + "curate-events", + "--qm-filings", + "f.bson", + "--qm-earnings", + "e.bson", + "--provider-mapping", + "m.tsv", + "--out", + "out_dir", + "--filings-form-type-field", + "formtype", + ])) + .expect("minimal curate-events args"); + assert_eq!( + action, + CliAction::CurateEvents(CurateEventsArgs { + qm_filings: PathBuf::from("f.bson"), + qm_earnings: PathBuf::from("e.bson"), + provider_mapping: PathBuf::from("m.tsv"), + out_dir: PathBuf::from("out_dir"), + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: "formtype".to_string(), + filings_filing_id_field: None, + filings_url_field: None, + earnings_key_field: DEFAULT_EARNINGS_KEY_FIELD.to_string(), + earnings_report_date_field: DEFAULT_EARNINGS_REPORT_DATE_FIELD.to_string(), + earnings_announce_time_field: DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD.to_string(), + earnings_fiscal_period_end_field: None, + earnings_actual_eps_field: None, + earnings_revenue_field: None, + mapping_source: DEFAULT_EVENTS_MAPPING_SOURCE.to_string(), + }) + ); + + // Full custom flags via --flag=value + let full = parse_args(&to_args(&[ + "curate-events", + "--qm-filings=f2.bson", + "--qm-earnings=e2.bson", + "--provider-mapping=m2.tsv", + "--out=o2", + "--filings-key-field=qmSearchCode", + "--filings-timefiled-field=ts", + "--filings-form-type-field=form", + "--filings-filing-id-field=fid", + "--filings-url-field=docUrl", + "--earnings-key-field=symbol", + "--earnings-report-date-field=rDate", + "--earnings-announce-time-field=aTime", + "--earnings-fiscal-period-end-field=fpe", + "--earnings-actual-eps-field=eps", + "--earnings-revenue-field=rev", + "--mapping-source=qm_alt", + ])) + .expect("full curate-events args"); + assert_eq!( + full, + CliAction::CurateEvents(CurateEventsArgs { + qm_filings: PathBuf::from("f2.bson"), + qm_earnings: PathBuf::from("e2.bson"), + provider_mapping: PathBuf::from("m2.tsv"), + out_dir: PathBuf::from("o2"), + filings_key_field: "qmSearchCode".to_string(), + filings_timefiled_field: "ts".to_string(), + filings_form_type_field: "form".to_string(), + filings_filing_id_field: Some("fid".to_string()), + filings_url_field: Some("docUrl".to_string()), + earnings_key_field: "symbol".to_string(), + earnings_report_date_field: "rDate".to_string(), + earnings_announce_time_field: "aTime".to_string(), + earnings_fiscal_period_end_field: Some("fpe".to_string()), + earnings_actual_eps_field: Some("eps".to_string()), + earnings_revenue_field: Some("rev".to_string()), + mapping_source: "qm_alt".to_string(), + }) + ); + + // Missing required --filings-form-type-field + let err = parse_args(&to_args(&[ + "curate-events", + "--qm-filings", + "f.bson", + "--qm-earnings", + "e.bson", + "--provider-mapping", + "m.tsv", + "--out", + "out_dir", + ])) + .unwrap_err(); + assert!(err.contains("missing required flag '--filings-form-type-field'"), "{err}"); + + // Duplicate flag + let err = parse_args(&to_args(&[ + "curate-events", + "--qm-filings", + "f.bson", + "--qm-filings", + "f2.bson", + "--qm-earnings", + "e.bson", + "--provider-mapping", + "m.tsv", + "--out", + "out_dir", + "--filings-form-type-field", + "formtype", + ])) + .unwrap_err(); + assert!(err.contains("duplicate flag '--qm-filings'"), "{err}"); + + // Unknown flag + let err = parse_args(&to_args(&[ + "curate-events", + "--qm-filings", + "f.bson", + "--qm-earnings", + "e.bson", + "--provider-mapping", + "m.tsv", + "--out", + "out_dir", + "--filings-form-type-field", + "formtype", + "--nope", + "1", + ])) + .unwrap_err(); + assert!(err.contains("unknown flag '--nope'"), "{err}"); + + // Colliding field names + let err = parse_args(&to_args(&[ + "curate-events", + "--qm-filings", + "f.bson", + "--qm-earnings", + "e.bson", + "--provider-mapping", + "m.tsv", + "--out", + "out_dir", + "--filings-form-type-field", + "symbol", + ])) + .unwrap_err(); + assert!(err.contains("cannot share BSON field 'symbol'"), "{err}"); + + // Forbidden consensusEps + let err = parse_args(&to_args(&[ + "curate-events", + "--qm-filings", + "f.bson", + "--qm-earnings", + "e.bson", + "--provider-mapping", + "m.tsv", + "--out", + "out_dir", + "--filings-form-type-field", + "formtype", + "--earnings-actual-eps-field", + "consensusEps", + ])) + .unwrap_err(); + assert!(err.contains("consensusEps"), "{err}"); + + // bench-curate-events-cmd + assert_eq!( + parse_args(&to_args(&["bench-curate-events-cmd"])), + Ok(CliAction::BenchCurateEventsCmd( + DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-curate-events-cmd", "1000"])), + Ok(CliAction::BenchCurateEventsCmd(1_000)) + ); + assert!(parse_args(&to_args(&["bench-curate-events-cmd", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-events-cmd", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-curate-events-cmd", "1", "2"])).is_err()); + } } diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index fe0ecb4f..785adf7d 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -6,6 +6,7 @@ pub mod bench; pub mod bson_ceo_shorts; pub mod bson_eod_prices; pub mod bson_qm_actions; +pub mod bson_qm_events; pub mod bson_stream; pub mod bson_te_market_data; pub mod cli; @@ -47,13 +48,22 @@ pub use bson_qm_actions::{ BsonQmActionError, RawQmDividend, RawQmSplit, FIELD_DATE, FIELD_DECLARED, FIELD_DIVIDEND_CASH, FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE, }; +pub use bson_qm_events::{ + decode_qm_earning_buffer, decode_qm_earning_bytes, decode_qm_earning_doc, + decode_qm_filing_buffer, decode_qm_filing_bytes, decode_qm_filing_doc, + BsonQmEarningsDecodeStats, BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, + QmFilingsFieldNames, RawQmEarning, RawQmFiling, DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, + DEFAULT_EARNINGS_KEY_FIELD, DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, + DEFAULT_FILINGS_TIMEFILED_FIELD, +}; pub use bson_stream::{ decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_price_chunks, decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream, - decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks, - decode_te_market_data_stream, BsonCeoShortsStreamError, BsonStreamError, BsonStreamOptions, - RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, - MIN_BSON_DOC_BYTES, + decode_qm_earnings_chunks, decode_qm_earnings_stream, decode_qm_filings_chunks, + decode_qm_filings_stream, decode_qm_split_chunks, decode_qm_split_stream, + decode_te_market_data_chunks, decode_te_market_data_stream, BsonCeoShortsStreamError, + BsonQmEventsStreamError, 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, @@ -199,3 +209,9 @@ pub use run_curate_shorts::{ format_curate_shorts_report, run_curate_shorts, CurateShortsArgs, CurateShortsRunReport, RunCurateShortsError, DEFAULT_MAPPING_SOURCE, }; + +pub mod run_curate_events; +pub use run_curate_events::{ + format_curate_events_report, run_curate_events, CurateEventsArgs, CurateEventsRunReport, + RunCurateEventsError, DEFAULT_EVENTS_MAPPING_SOURCE, +}; diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 9ee7d106..dcdee8dc 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -9,9 +9,9 @@ use curate_etl::bench::{ run_curate_adj_benchmark, run_curate_adj_cmd_benchmark, run_curate_bars_benchmark, run_curate_bars_cmd_benchmark, run_curate_corporate_actions_benchmark, run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark, - run_curate_fx_benchmark, run_curate_fx_cmd_benchmark, run_curate_shorts_benchmark, - run_curate_shorts_command_benchmark, run_events_benchmark, run_fx_benchmark, - run_parquet_adj_benchmark, run_parquet_bars_benchmark, + run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark, + run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark, + run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark, @@ -22,6 +22,7 @@ use curate_etl::run_curate_bars::{format_curate_bars_report, run_curate_bars_1d} use curate_etl::run_curate_corporate_actions::{ format_curate_corporate_actions_report, run_curate_corporate_actions, }; +use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events}; use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d}; use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts}; @@ -94,6 +95,16 @@ fn main() -> ExitCode { ExitCode::FAILURE } }, + Ok(CliAction::CurateEvents(curate_args)) => match run_curate_events(&curate_args) { + Ok(report) => { + println!("{}", format_curate_events_report(&report)); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("error: {err}"); + ExitCode::FAILURE + } + }, Ok(CliAction::BenchSplit(rows)) => { let report = match run_split_benchmark(rows) { Ok(report) => report, @@ -904,6 +915,74 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchCurateEventsCmd(rows)) => { + let report = match run_curate_events_cmd_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: curate-events-cmd benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + let retention_pct = if report.rows > 0 { + (report.rows_out as f64 / report.rows as f64) * 100.0 + } else { + 0.0 + }; + println!("curate-etl bench-curate-events-cmd"); + println!( + " input: rows={} filings_docs={} filings_bytes={} earnings_docs={} earnings_bytes={} keys={} peak_chunk_bytes={}", + report.rows, + report.filings_docs_framed, + report.filings_bytes_read, + report.earnings_docs_framed, + report.earnings_bytes_read, + report.key_count, + report.peak_chunk_bytes + ); + println!( + " decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s filings_out={} filings_skipped={} earnings_out={} earnings_skipped={}", + report.decode_elapsed_ms, + report.decode_rows_per_sec, + report.input_mb_per_sec, + report.filings_decode.rows_out, + report.filings_decode.skipped_total(), + report.earnings_decode.rows_out, + report.earnings_decode.skipped_total() + ); + println!( + " curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) filings_out={} earnings_out={} listings_out={} linked={} lagged_1605={} unmapped={} listing_dup={}", + report.curate_elapsed_ms, + report.curate_rows_per_sec, + report.rows_out, + retention_pct, + report.filings_out, + report.earnings_out, + report.listings_out, + report.curate_stats.builder.earnings_linked_to_filing, + report.curate_stats.builder.earnings_lagged_1605, + report.curate_stats.dropped_unmapped, + report.curate_stats.listing_duplicate_collapsed + ); + println!( + " write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}", + report.write_elapsed_ms, + report.write_rows_per_sec, + report.write_mb_per_sec, + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows + ); + println!( + " total: elapsed={:.2} ms throughput={:.0} rows/s proj_30.96M={:.1}s ({:.2}m) checksum=0x{:016x}", + report.total_elapsed_ms, + report.total_rows_per_sec, + report.total_extrap_full_secs, + report.total_extrap_full_secs / 60.0, + report.checksum + ); + ExitCode::SUCCESS + } Ok(CliAction::BenchCurateFx(rows)) => { let report = match run_curate_fx_benchmark(rows) { Ok(report) => report, diff --git a/tools/curate-etl/src/run_curate_events.rs b/tools/curate-etl/src/run_curate_events.rs new file mode 100644 index 00000000..5512c70c --- /dev/null +++ b/tools/curate-etl/src/run_curate_events.rs @@ -0,0 +1,758 @@ +//! File-to-file `curate-events` command runner (`M1.2ae`). +//! +//! Streams concatenated raw BSON `qmFilings` and `qmEarnings` dump files alongside +//! `provider_mapping.tsv` into atomically published `/events/year=YYYY/part.parquet` +//! partitions via [`curate_and_write_events`]. +//! +//! # Contract & Point-in-Time Rules +//! - Verified defaults match in-repo evidence (`symbol` / `timefiled` on `qmFilings`; +//! `qmSearchCode` / `reportDate` / `announceTime` on `qmEarnings`). Unverified fields +//! (`--filings-form-type-field`, plus optional `filing_id`, `url`, `fiscal_period_end`, +//! `actual_eps`, `revenue`) have no defaults and are validated up front before touching disk. +//! - `consensusEps` is structurally excluded from decoding and explicitly rejected by +//! [`QmEarningsFieldNames::validate`] on any earnings field flag. +//! - `provider_mapping.tsv` uses the strict headerless 5-column TSV format from +//! [`crate::run_curate_bars::load_provider_mapping_tsv`]. +//! - All decoded [`QmFiling`] and [`QmEarning`] rows are passed directly to +//! [`curate_and_write_events`], which links same-day `8-K` / `News release` filings to +//! earnings, falls back unlinked earnings to `16:05 ET`, resolves `provider_mapping` on each +//! event's exact Eastern local calendar date (never UTC or `known_at` date), and counts +//! unmapped keys in [`CurateEventsStats::dropped_unmapped`]. +//! - **Empty / all-unmapped behavior:** delegated unchanged to [`curate_and_write_events`] / +//! [`write_events_dataset`], returning `Ok` with `rows_written == 0` and `files_written == 0` +//! without creating `/events` or modifying any pre-existing partitions. +//! - **Fail-closed safety:** invalid `--out` (including `--out` or `/events` being a regular +//! file, or any input path resolving to `--out` or inside `/events`), invalid field names, +//! empty `--mapping-source`, unreadable inputs, malformed/overlapping `provider_mapping.tsv`, +//! and truncated/corrupt BSON framing or element bytes return a typed [`RunCurateEventsError`] +//! before touching `args.out_dir`. +//! +//! # Counter Conservation Invariants +//! Every successful [`CurateEventsRunReport`] satisfies: +//! - `filings_docs_framed as usize == filings_decode.docs_in == filings_decode.rows_out + filings_decode.skipped_total()` +//! - `earnings_docs_framed as usize == earnings_decode.docs_in == earnings_decode.rows_out + earnings_decode.skipped_total()` +//! - `filings_decode.rows_out == curate_stats.builder.filings_in` +//! - `earnings_decode.rows_out == curate_stats.builder.earnings_in` +//! - `curate_stats.rows_in == curate_stats.builder.rows_out == curate_stats.rows_out + curate_stats.dropped_unmapped + curate_stats.listing_duplicate_collapsed` +//! - `write_stats.rows_written == curate_stats.rows_out` + +use std::collections::HashSet; +use std::error::Error; +use std::fmt::{self, Write as _}; +use std::fs::File; +use std::io; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use std::time::Instant; + +use crate::bson_qm_events::{ + BsonQmEarningsDecodeStats, BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, + QmFilingsFieldNames, +}; +use crate::bson_stream::{ + decode_qm_earnings_chunks, decode_qm_filings_chunks, BsonQmEventsStreamError, BsonStreamError, + BsonStreamOptions, RawBsonChunkReader, +}; +use crate::curate_events::{ + curate_and_write_events, curate_events, CurateEventsStats, CurateEventsWriteError, +}; +use crate::events::{QmEarning, QmFiling}; +use crate::parquet_events::{ + write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, +}; +use crate::provider_mapping::{ProviderMappingError, ProviderMappingTable}; +use crate::run_curate_bars::{load_provider_mapping_tsv, RunCurateBarsError}; + +/// Default `--mapping-source` passed to `provider_mapping` lookups for `qmFilings` / `qmEarnings`. +pub const DEFAULT_EVENTS_MAPPING_SOURCE: &str = "qm"; + +/// Parsed arguments for the `curate-events` CLI command. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CurateEventsArgs { + pub qm_filings: PathBuf, + pub qm_earnings: PathBuf, + pub provider_mapping: PathBuf, + pub out_dir: PathBuf, + 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 earnings_key_field: String, + pub earnings_report_date_field: String, + pub earnings_announce_time_field: String, + pub earnings_fiscal_period_end_field: Option, + pub earnings_actual_eps_field: Option, + pub earnings_revenue_field: Option, + pub mapping_source: String, +} + +impl CurateEventsArgs { + /// 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(), + } + } + + /// Borrows the configured `qmEarnings` BSON field names as [`QmEarningsFieldNames`]. + #[inline] + pub fn earnings_field_names(&self) -> QmEarningsFieldNames<'_> { + QmEarningsFieldNames { + key: self.earnings_key_field.as_str(), + report_date: self.earnings_report_date_field.as_str(), + announce_time: self.earnings_announce_time_field.as_str(), + fiscal_period_end: self.earnings_fiscal_period_end_field.as_deref(), + actual_eps: self.earnings_actual_eps_field.as_deref(), + revenue: self.earnings_revenue_field.as_deref(), + } + } +} + +/// Full run report produced by [`run_curate_events`]. +#[derive(Debug, Clone, PartialEq)] +pub struct CurateEventsRunReport { + pub filings_docs_framed: u64, + pub filings_bytes_read: u64, + pub filings_peak_chunk_bytes: usize, + pub filings_decode: BsonQmFilingsDecodeStats, + pub earnings_docs_framed: u64, + pub earnings_bytes_read: u64, + pub earnings_peak_chunk_bytes: usize, + pub earnings_decode: BsonQmEarningsDecodeStats, + pub curate_stats: CurateEventsStats, + pub write_stats: EventsWriteStats, + pub elapsed_secs: f64, +} + +/// Stage-timed run output used internally by `bench-curate-events-cmd`. +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct CurateEventsTimedRun { + pub report: CurateEventsRunReport, + pub decode_elapsed_secs: f64, + pub curate_elapsed_secs: f64, + pub write_elapsed_secs: f64, + pub checksum: u64, +} + +/// Typed errors returned by [`run_curate_events`]. +/// +/// 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 RunCurateEventsError { + InvalidOutDir { + path: PathBuf, + detail: String, + }, + InvalidFieldNames { + source: BsonQmEventsError, + }, + EmptyMappingSource, + 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, + }, + CorruptBson { + label: &'static str, + path: PathBuf, + offset: u64, + source: BsonQmEventsError, + }, + CurateWrite { + out_dir: PathBuf, + source: CurateEventsWriteError, + }, +} + +impl fmt::Display for RunCurateEventsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidOutDir { path, detail } => { + write!(f, "invalid --out '{}': {detail}", path.display()) + } + Self::InvalidFieldNames { source } => write!(f, "{source}"), + Self::EmptyMappingSource => { + write!(f, "invalid --mapping-source: must not be empty or blank") + } + Self::OpenInput { + label, + path, + source, + } => write!(f, "failed to open {label} '{}': {source}", path.display()), + Self::ReadInput { + label, + path, + source, + } => write!(f, "failed to read {label} '{}': {source}", path.display()), + Self::TsvParse { path, line, detail } => { + write!(f, "{}:{line}: {detail}", path.display()) + } + Self::ProviderMapping { path, source } => { + write!(f, "invalid provider_mapping '{}': {source}", path.display()) + } + Self::BsonStream { + label, + path, + source, + } => write!(f, "failed reading {label} '{}': {source}", path.display()), + Self::CorruptBson { + label, + path, + offset, + source, + } => write!( + f, + "corrupt {label} BSON '{}' at byte offset {offset}: {source}", + path.display() + ), + Self::CurateWrite { out_dir, source } => { + write!(f, "curate/write to '{}' failed: {source}", out_dir.display()) + } + } + } +} + +impl Error for RunCurateEventsError { + fn source(&self) -> Option<&(dyn Error + 'static)> { + match self { + Self::InvalidFieldNames { source } => Some(source), + Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source), + Self::ProviderMapping { source, .. } => Some(source), + Self::BsonStream { source, .. } => Some(source), + Self::CorruptBson { source, .. } => Some(source), + Self::CurateWrite { source, .. } => Some(source), + Self::InvalidOutDir { .. } | Self::EmptyMappingSource | Self::TsvParse { .. } => None, + } + } +} + +/// Resolves `path` to an absolute normalized path by canonicalizing its deepest existing ancestor +/// (resolving symlinks) and lexically normalizing any remaining non-existent components. +fn resolve_normalized_path(path: &Path) -> PathBuf { + 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() + }; + + // Lexically normalize `.` and `..` first so ancestor lookups walk real parents. + let mut lex = PathBuf::new(); + for comp in abs.components() { + match comp { + Component::CurDir => {} + Component::ParentDir => { + if !lex.pop() { + lex.push(comp.as_os_str()); + } + } + other => lex.push(other.as_os_str()), + } + } + + // Walk upward until we find an existing ancestor that can be canonicalized. + let mut tail: Vec = Vec::new(); + let mut cur = lex.as_path(); + loop { + if let Ok(canon) = cur.canonicalize() { + let mut out = canon; + for seg in tail.into_iter().rev() { + out.push(seg); + } + return out; + } + match (cur.parent(), cur.file_name()) { + (Some(parent), Some(name)) => { + tail.push(name.to_os_string()); + cur = parent; + } + _ => return lex, + } + } +} + +fn validate_out_dir_and_inputs(args: &CurateEventsArgs) -> Result<(), RunCurateEventsError> { + if args.out_dir.exists() && !args.out_dir.is_dir() { + return Err(RunCurateEventsError::InvalidOutDir { + path: args.out_dir.clone(), + detail: "path exists and is not a directory".to_string(), + }); + } + + let events_dir = args.out_dir.join("events"); + if events_dir.exists() && !events_dir.is_dir() { + return Err(RunCurateEventsError::InvalidOutDir { + path: events_dir, + detail: "events output path exists and is not a directory".to_string(), + }); + } + + let resolved_out = resolve_normalized_path(&args.out_dir); + let resolved_events = resolve_normalized_path(&events_dir); + + for (label, input_path) in [ + ("qm-filings", &args.qm_filings), + ("qm-earnings", &args.qm_earnings), + ("provider-mapping", &args.provider_mapping), + ] { + let resolved_in = resolve_normalized_path(input_path); + if resolved_in == resolved_out + || resolved_in == resolved_events + || resolved_in.starts_with(&resolved_events) + { + return Err(RunCurateEventsError::InvalidOutDir { + path: args.out_dir.clone(), + detail: format!( + "output directory would overlap {label} input '{}'", + input_path.display() + ), + }); + } + } + + Ok(()) +} + +fn map_tsv_error(path: &Path, err: RunCurateBarsError) -> RunCurateEventsError { + match err { + RunCurateBarsError::OpenInput { + label, + path, + source, + } => RunCurateEventsError::OpenInput { + label, + path, + source, + }, + RunCurateBarsError::ReadInput { + label, + path, + source, + } => RunCurateEventsError::ReadInput { + label, + path, + source, + }, + RunCurateBarsError::TsvParse { path, line, detail } => { + RunCurateEventsError::TsvParse { path, line, detail } + } + RunCurateBarsError::ProviderMapping { path, source } => { + RunCurateEventsError::ProviderMapping { path, source } + } + other => RunCurateEventsError::TsvParse { + path: path.to_path_buf(), + line: 0, + detail: other.to_string(), + }, + } +} + +fn bson_error_offset(err: &BsonQmEventsError) -> u64 { + match err { + BsonQmEventsError::TruncatedDocument { offset, .. } + | BsonQmEventsError::CorruptDocumentLength { offset, .. } + | BsonQmEventsError::CorruptBson { offset, .. } => *offset, + BsonQmEventsError::InvalidFieldNames { .. } => 0, + } +} + +fn map_stream_error( + label: &'static str, + path: &Path, + err: BsonQmEventsStreamError, +) -> RunCurateEventsError { + match err { + BsonQmEventsStreamError::Stream(source) => RunCurateEventsError::BsonStream { + label, + path: path.to_path_buf(), + source, + }, + BsonQmEventsStreamError::Decode(source) => match &source { + BsonQmEventsError::InvalidFieldNames { .. } => { + RunCurateEventsError::InvalidFieldNames { source } + } + _ => { + let offset = bson_error_offset(&source); + RunCurateEventsError::CorruptBson { + label, + 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 DecodedEventsInputs { + mapping: ProviderMappingTable, + filings: Vec>>, + earnings: Vec>>, + filings_docs_framed: u64, + filings_bytes_read: u64, + filings_peak_chunk_bytes: usize, + filings_decode: BsonQmFilingsDecodeStats, + earnings_docs_framed: u64, + earnings_bytes_read: u64, + earnings_peak_chunk_bytes: usize, + earnings_decode: BsonQmEarningsDecodeStats, +} + +fn decode_all_inputs(args: &CurateEventsArgs) -> Result { + let filings_fields = args.filings_field_names(); + filings_fields + .validate() + .map_err(|source| RunCurateEventsError::InvalidFieldNames { source })?; + + let earnings_fields = args.earnings_field_names(); + earnings_fields + .validate() + .map_err(|source| RunCurateEventsError::InvalidFieldNames { source })?; + + if args.mapping_source.trim().is_empty() { + return Err(RunCurateEventsError::EmptyMappingSource); + } + + 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| { + RunCurateEventsError::ProviderMapping { + path: args.provider_mapping.clone(), + source, + } + })?; + + let mut key_interner: HashSet> = HashSet::new(); + + // Stream and decode qmFilings. + let filings_file = + File::open(&args.qm_filings).map_err(|source| RunCurateEventsError::OpenInput { + label: "qm-filings", + path: args.qm_filings.clone(), + source, + })?; + let mut filings_reader = + RawBsonChunkReader::with_options(filings_file, BsonStreamOptions::default()).map_err( + |source| RunCurateEventsError::BsonStream { + label: "qm-filings", + path: args.qm_filings.clone(), + source, + }, + )?; + + let mut filings: Vec>> = Vec::new(); + let filings_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_stream_error("qm-filings", &args.qm_filings, err))?; + + // Stream and decode qmEarnings (reusing the same key interner). + let earnings_file = + File::open(&args.qm_earnings).map_err(|source| RunCurateEventsError::OpenInput { + label: "qm-earnings", + path: args.qm_earnings.clone(), + source, + })?; + let mut earnings_reader = + RawBsonChunkReader::with_options(earnings_file, BsonStreamOptions::default()).map_err( + |source| RunCurateEventsError::BsonStream { + label: "qm-earnings", + path: args.qm_earnings.clone(), + source, + }, + )?; + + let mut earnings: Vec>> = Vec::new(); + let earnings_decode = + decode_qm_earnings_chunks(&mut earnings_reader, &earnings_fields, |raw| { + let key = intern_key(&mut key_interner, raw.key); + earnings.push(raw.to_qm_earning(key)); + }) + .map_err(|err| map_stream_error("qm-earnings", &args.qm_earnings, err))?; + + Ok(DecodedEventsInputs { + mapping, + filings, + earnings, + filings_docs_framed: filings_reader.docs_framed(), + filings_bytes_read: filings_reader.bytes_read(), + filings_peak_chunk_bytes: filings_reader.buffer_capacity(), + filings_decode, + earnings_docs_framed: earnings_reader.docs_framed(), + earnings_bytes_read: earnings_reader.bytes_read(), + earnings_peak_chunk_bytes: earnings_reader.buffer_capacity(), + earnings_decode, + }) +} + +/// Runs the end-to-end `curate-events` file-to-Parquet pipeline via [`curate_and_write_events`]. +/// +/// Any validation, I/O, TSV, mapping, BSON framing/corruption, or curation error returns before +/// touching `args.out_dir`, leaving any pre-existing `/events/` partitions +/// byte-identical. +pub fn run_curate_events( + args: &CurateEventsArgs, +) -> Result { + let start = Instant::now(); + validate_out_dir_and_inputs(args)?; + + let decoded = decode_all_inputs(args)?; + + let write_report = curate_and_write_events( + &args.out_dir, + decoded.filings, + decoded.earnings, + &args.mapping_source, + &decoded.mapping, + EventsWriteOptions::default(), + ) + .map_err(|source| RunCurateEventsError::CurateWrite { + out_dir: args.out_dir.clone(), + source, + })?; + + Ok(CurateEventsRunReport { + 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, + earnings_docs_framed: decoded.earnings_docs_framed, + earnings_bytes_read: decoded.earnings_bytes_read, + earnings_peak_chunk_bytes: decoded.earnings_peak_chunk_bytes, + earnings_decode: decoded.earnings_decode, + curate_stats: write_report.curate_stats, + write_stats: write_report.write_stats, + elapsed_secs: start.elapsed().as_secs_f64(), + }) +} + +fn compute_rows_checksum(rows: &[EventsParquetRow]) -> u64 { + let mut hash = 0xcbf2_9ce4_8422_2325_u64; + let mix = |mut h: u64, v: u64| -> u64 { + h ^= v; + h = h.wrapping_mul(0x0000_0100_0000_01b3); + h + }; + let mix_str = |mut h: u64, s: &str| -> u64 { + h = mix(h, s.len() as u64); + for &b in s.as_bytes() { + h = mix(h, u64::from(b)); + } + h + }; + for row in rows { + hash = mix(hash, row.listing_id as u64); + hash = mix(hash, row.ts_micros as u64); + hash = mix(hash, row.known_at_micros as u64); + hash = mix_str(hash, row.known_at_source.as_ref()); + hash = mix_str(hash, row.kind.as_ref()); + hash = mix_str(hash, &row.subtype); + hash = mix_str(hash, &row.payload_json); + } + hash +} + +/// Stage-timed variant of [`run_curate_events`] used internally by `bench-curate-events-cmd`. +/// +/// Separately times `decode` (TSV load + both BSON streams), `curate` (`curate_events`), and +/// `write` (`write_events_dataset`), and computes a deterministic FNV-1a checksum over all 7 +/// columns of the curated rows. +pub(crate) fn run_curate_events_timed( + args: &CurateEventsArgs, +) -> Result { + let total_start = Instant::now(); + validate_out_dir_and_inputs(args)?; + + let decode_start = Instant::now(); + let decoded = decode_all_inputs(args)?; + let decode_elapsed_secs = decode_start.elapsed().as_secs_f64(); + + let curate_start = Instant::now(); + let curated = curate_events( + decoded.filings, + decoded.earnings, + &args.mapping_source, + &decoded.mapping, + ) + .map_err(|source| RunCurateEventsError::CurateWrite { + out_dir: args.out_dir.clone(), + source: CurateEventsWriteError::Curate(source), + })?; + let curate_elapsed_secs = curate_start.elapsed().as_secs_f64(); + + let checksum = compute_rows_checksum(&curated.rows); + + let write_start = Instant::now(); + let write_stats = + write_events_dataset(&args.out_dir, &curated.rows, EventsWriteOptions::default()).map_err( + |source| RunCurateEventsError::CurateWrite { + out_dir: args.out_dir.clone(), + source: CurateEventsWriteError::Parquet(source), + }, + )?; + let write_elapsed_secs = write_start.elapsed().as_secs_f64(); + + let report = CurateEventsRunReport { + 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, + earnings_docs_framed: decoded.earnings_docs_framed, + earnings_bytes_read: decoded.earnings_bytes_read, + earnings_peak_chunk_bytes: decoded.earnings_peak_chunk_bytes, + earnings_decode: decoded.earnings_decode, + curate_stats: curated.stats, + write_stats, + elapsed_secs: total_start.elapsed().as_secs_f64(), + }; + + Ok(CurateEventsTimedRun { + report, + decode_elapsed_secs, + curate_elapsed_secs, + write_elapsed_secs, + checksum, + }) +} + +/// Formats [`CurateEventsRunReport`] into a deterministic machine-readable `key=value` summary. +/// +/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`). +pub fn format_curate_events_report(report: &CurateEventsRunReport) -> String { + let fd = &report.filings_decode; + let ed = &report.earnings_decode; + let b = &report.curate_stats.builder; + 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-events\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 earnings_bson: docs_framed={} bytes_read={} peak_chunk_bytes={} docs_in={} rows_out={} skipped={} (missing_key={} wrong_key_type={} empty_key={} missing_date={} wrong_date_type={} invalid_date={} date_oor={} missing_announce={} wrong_announce_type={} empty_announce={}) nulled=(wrong_fiscal_end={} invalid_fiscal_end={} wrong_eps={} wrong_revenue={})\n\ + \x20 builder: filings_in={} filings_out={} malformed_ts={} unknown_zone={} invalid_dt={} filing_dup={} earnings_in={} earnings_out={} linked={} lagged_1605={} earnings_oor={} earnings_dup={} earnings_conflict={} rows_out={} keys_out={}\n\ + \x20 curate: rows_in={} rows_out={} filings_out={} earnings_out={} listings_out={} dropped_unmapped={} listing_dup_collapsed={}\n\ + \x20 write: files={} row_groups={} rows_written={} bytes_written={}\n\ + \x20 years: {}\n\ + \x20 timing: elapsed_secs={:.6}", + report.filings_docs_framed, + report.filings_bytes_read, + report.filings_peak_chunk_bytes, + fd.docs_in, + fd.rows_out, + fd.skipped_total(), + fd.skipped_missing_key, + fd.skipped_wrong_key_type, + fd.skipped_empty_key, + fd.skipped_missing_timefiled, + fd.skipped_wrong_timefiled_type, + fd.skipped_empty_timefiled, + fd.skipped_missing_form_type, + fd.skipped_wrong_form_type_type, + fd.skipped_empty_form_type, + fd.nulled_wrong_type_filing_id, + fd.nulled_wrong_type_url, + report.earnings_docs_framed, + report.earnings_bytes_read, + report.earnings_peak_chunk_bytes, + ed.docs_in, + ed.rows_out, + ed.skipped_total(), + ed.skipped_missing_key, + ed.skipped_wrong_key_type, + ed.skipped_empty_key, + ed.skipped_missing_report_date, + ed.skipped_wrong_report_date_type, + ed.skipped_invalid_report_date, + ed.skipped_report_date_out_of_range, + ed.skipped_missing_announce_time, + ed.skipped_wrong_announce_time_type, + ed.skipped_empty_announce_time, + ed.nulled_wrong_type_fiscal_period_end, + ed.nulled_invalid_fiscal_period_end, + ed.nulled_wrong_type_actual_eps, + ed.nulled_wrong_type_revenue, + b.filings_in, + b.filings_out, + b.filings_skipped_malformed_timestamp, + b.filings_skipped_unknown_zone, + b.filings_skipped_invalid_date_time, + b.filings_duplicate_collapsed, + b.earnings_in, + b.earnings_out, + b.earnings_linked_to_filing, + b.earnings_lagged_1605, + b.earnings_skipped_out_of_range, + b.earnings_duplicate_collapsed, + b.earnings_duplicate_conflict_dropped, + b.rows_out, + b.keys_out, + c.rows_in, + c.rows_out, + c.filings_out, + c.earnings_out, + c.listings_out, + c.dropped_unmapped, + c.listing_duplicate_collapsed, + w.files_written, + w.row_groups_written, + w.rows_written, + w.bytes_written, + years, + report.elapsed_secs, + ) +} + +#[cfg(test)] +#[path = "run_curate_events_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/run_curate_events_tests.rs b/tools/curate-etl/src/run_curate_events_tests.rs new file mode 100644 index 00000000..84327cc7 --- /dev/null +++ b/tools/curate-etl/src/run_curate_events_tests.rs @@ -0,0 +1,629 @@ +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use bson::{rawdoc, DateTime, RawDocumentBuf}; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::*; +use crate::bson_eod_prices::MILLIS_PER_DAY; +use crate::bson_qm_events::{ + DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD, DEFAULT_EARNINGS_KEY_FIELD, + DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD, DEFAULT_FILINGS_TIMEFILED_FIELD, +}; +use crate::events::{ + EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, + KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +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, Ordering::Relaxed); + let pid = std::process::id(); + let path = + std::env::temp_dir().join(format!("curate-etl-run-events-{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); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn utc_micros(y: i32, m: u32, d: u32, hh: u32, mm: u32, ss: u32) -> i64 { + let days = i64::from(day(y, m, d)); + let secs = days * 86_400 + i64::from(hh) * 3_600 + i64::from(mm) * 60 + i64::from(ss); + secs * 1_000_000 +} + +fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { + let mut out = Vec::new(); + for d in docs { + out.extend_from_slice(d.as_bytes()); + } + out +} + +fn default_args(dir: &Path) -> CurateEventsArgs { + CurateEventsArgs { + qm_filings: dir.join("qmFilings.bson"), + qm_earnings: dir.join("qmEarnings.bson"), + provider_mapping: dir.join("provider_mapping.tsv"), + out_dir: dir.join("out"), + filings_key_field: DEFAULT_FILINGS_KEY_FIELD.to_string(), + filings_timefiled_field: DEFAULT_FILINGS_TIMEFILED_FIELD.to_string(), + filings_form_type_field: "formtype".to_string(), + filings_filing_id_field: Some("filingId".to_string()), + filings_url_field: Some("url".to_string()), + earnings_key_field: DEFAULT_EARNINGS_KEY_FIELD.to_string(), + earnings_report_date_field: DEFAULT_EARNINGS_REPORT_DATE_FIELD.to_string(), + earnings_announce_time_field: DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD.to_string(), + earnings_fiscal_period_end_field: Some("periodEndDate".to_string()), + earnings_actual_eps_field: Some("actualEps".to_string()), + earnings_revenue_field: Some("revenue".to_string()), + mapping_source: DEFAULT_EVENTS_MAPPING_SOURCE.to_string(), + } +} + +fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int32ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int32ColumnReader"), + } + values +} + +fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int64ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int64ColumnReader"), + } + values +} + +fn read_str_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected ByteArrayColumnReader"), + } + values + .into_iter() + .map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8")) + .collect() +} + +fn read_events_parquet_file(path: &Path) -> (usize, Vec) { + let file = File::open(path).expect("open parquet file"); + let reader = SerializedFileReader::new(file).expect("open parquet reader"); + let metadata = reader.metadata(); + let footer_rows = metadata.file_metadata().num_rows() as usize; + let mut out = Vec::with_capacity(footer_rows); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let listing_id = read_i32_col(rg_reader.get_column_reader(0).unwrap(), num_rows); + let ts_micros = read_i64_col(rg_reader.get_column_reader(1).unwrap(), num_rows); + let known_at_micros = read_i64_col(rg_reader.get_column_reader(2).unwrap(), num_rows); + let known_at_source = read_str_col(rg_reader.get_column_reader(3).unwrap(), num_rows); + let kind = read_str_col(rg_reader.get_column_reader(4).unwrap(), num_rows); + let subtype = read_str_col(rg_reader.get_column_reader(5).unwrap(), num_rows); + let payload_json = read_str_col(rg_reader.get_column_reader(6).unwrap(), num_rows); + + for i in 0..num_rows { + out.push(EventsParquetRow { + listing_id: listing_id[i], + ts_micros: ts_micros[i], + known_at_micros: known_at_micros[i], + known_at_source: Cow::Owned(known_at_source[i].clone()), + kind: Cow::Owned(kind[i].clone()), + subtype: subtype[i].clone(), + payload_json: payload_json[i].clone(), + }); + } + } + (footer_rows, out) +} + +fn read_all_events_partitions(out_dir: &Path) -> BTreeMap> { + let events_dir = out_dir.join("events"); + let mut by_year: BTreeMap> = BTreeMap::new(); + for entry in fs::read_dir(&events_dir).expect("read events dir") { + let entry = entry.unwrap(); + let name = entry.file_name(); + let name_str = name.to_string_lossy(); + let Some(year_str) = name_str.strip_prefix("year=") else { + continue; + }; + let year: i32 = year_str.parse().expect("valid year partition"); + let part_path = entry.path().join("part.parquet"); + let (footer_rows, rows) = read_events_parquet_file(&part_path); + assert_eq!(footer_rows, rows.len()); + by_year.insert(year, rows); + } + by_year +} + +fn assert_report_conservation(report: &CurateEventsRunReport) { + 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.earnings_docs_framed as usize, report.earnings_decode.docs_in); + assert_eq!( + report.earnings_decode.docs_in, + report.earnings_decode.rows_out + report.earnings_decode.skipped_total() + ); + assert_eq!( + report.filings_decode.rows_out, + report.curate_stats.builder.filings_in + ); + assert_eq!( + report.earnings_decode.rows_out, + report.curate_stats.builder.earnings_in + ); + assert_eq!( + report.curate_stats.rows_in, + report.curate_stats.builder.rows_out + ); + assert_eq!( + report.curate_stats.rows_in, + report.curate_stats.rows_out + + report.curate_stats.dropped_unmapped + + report.curate_stats.listing_duplicate_collapsed + ); + assert_eq!( + report.write_stats.rows_written, + report.curate_stats.rows_out + ); +} + +#[test] +fn end_to_end_curate_events_partitions_linking_lag_rollover_and_determinism() { + let tmp = TempDirGuard::new("e2e"); + let dir = tmp.path(); + + // provider_mapping.tsv: + // - AAPL -> listing 101 (2020-01-01..open) + // - SHOP:CA -> listing 202 (2020-01-01..open) + // - ROLL -> listing 303 (2020-01-01..2024-12-31) — ends on Dec 31 ET! + let mapping_tsv = concat!( + "qm\tAAPL\t2020-01-01\t\t101\n", + "qm\tSHOP:CA\t2020-01-01\t\t202\n", + "qm\tROLL\t2020-01-01\t2024-12-31\t303\n", + ); + fs::write(dir.join("provider_mapping.tsv"), mapping_tsv).unwrap(); + + let filing_docs = vec![ + // 1. EST filing (2025-01-31 06:01:27 EST = 2025-01-31 11:01:27 UTC), 8-K linking AAPL earnings + rawdoc! { + "symbol": "AAPL", + "timefiled": "2025-01-31T06:01:27 EST", + "formtype": "8-K", + "filingId": "EDGAR-8K-001", + "url": "https://sec.gov/8k-001", + }, + // 2. EDT filing (2025-07-15 16:30:00 EDT = 2025-07-15 20:30:00 UTC), 10-Q + rawdoc! { + "symbol": "AAPL", + "timefiled": "2025-07-15T16:30:00 EDT", + "formtype": "10-Q", + "filingId": "EDGAR-10Q-002", + }, + // 3. Late-evening Dec 31 ET rollover: 2024-12-31 21:30:00 EST = 2025-01-01 02:30:00 UTC + // Mapping for ROLL ends 2024-12-31, so ET-date mapping succeeds while UTC year is 2025! + rawdoc! { + "symbol": "ROLL", + "timefiled": "2024-12-31T21:30:00 EST", + "formtype": "10-K", + "filingId": "ROLL-10K", + }, + // 4. 2024 filing for SHOP:CA -> lands in year=2024 + rawdoc! { + "symbol": "SHOP:CA", + "timefiled": "2024-11-12T07:00:00 EST", + "formtype": "News release", + "filingId": "SEDAR-NR-001", + }, + // 5. Unmapped filing -> dropped_unmapped + rawdoc! { + "symbol": "UNMAPPED", + "timefiled": "2025-03-01T09:00:00 EST", + "formtype": "8-K", + "filingId": "UNM-1", + }, + // 6. Semantically skipped filing (blank formtype) + rawdoc! { + "symbol": "AAPL", + "timefiled": "2025-03-02T09:00:00 EST", + "formtype": " ", + }, + ]; + + let earning_docs = vec![ + // 1. AAPL same-day earnings linked to EDGAR-8K-001 (with consensusEps that must NOT appear) + rawdoc! { + "qmSearchCode": "AAPL", + "reportDate": DateTime::from_millis(i64::from(day(2025, 1, 31)) * MILLIS_PER_DAY), + "announceTime": "BTO", + "periodEndDate": "2024-12-28", + "actualEps": 2.40_f64, + "revenue": 124_300_000_000_i64, + "consensusEps": 2.35_f64, + }, + // 2. SHOP:CA unlinked N/A earnings on 2025-02-11 -> lagged to 16:05 EST (21:05 UTC) + rawdoc! { + "qmSearchCode": "SHOP:CA", + "reportDate": "2025-02-11", + "announceTime": "N/A", + "periodEndDate": "2024-12-31", + "actualEps": 0.44_f64, + "revenue": 2_810_000_000_i64, + "consensusEps": 0.42_f64, + }, + // 3. Unmapped earnings -> dropped_unmapped + rawdoc! { + "qmSearchCode": "NOPE", + "reportDate": "2025-04-01", + "announceTime": "AMC", + "consensusEps": 1.0_f64, + }, + ]; + + fs::write(dir.join("qmFilings.bson"), concat_docs(&filing_docs)).unwrap(); + fs::write(dir.join("qmEarnings.bson"), concat_docs(&earning_docs)).unwrap(); + + let args = default_args(dir); + let report = run_curate_events(&args).expect("curate-events succeeds"); + assert_report_conservation(&report); + + assert_eq!(report.filings_decode.docs_in, 6); + assert_eq!(report.filings_decode.rows_out, 5); + assert_eq!(report.filings_decode.skipped_empty_form_type, 1); + assert_eq!(report.earnings_decode.docs_in, 3); + assert_eq!(report.earnings_decode.rows_out, 3); + assert_eq!(report.curate_stats.dropped_unmapped, 2); + assert_eq!(report.curate_stats.rows_out, 6); + assert_eq!(report.curate_stats.filings_out, 4); + assert_eq!(report.curate_stats.earnings_out, 2); + assert_eq!(report.curate_stats.builder.earnings_linked_to_filing, 1); + assert_eq!(report.curate_stats.builder.earnings_lagged_1605, 2); + assert_eq!(report.write_stats.files_written, 2); + assert_eq!(report.write_stats.rows_by_year.get(&2024), Some(&1)); + assert_eq!(report.write_stats.rows_by_year.get(&2025), Some(&5)); + + let by_year = read_all_events_partitions(&args.out_dir); + assert_eq!(by_year.keys().copied().collect::>(), vec![2024, 2025]); + + // Check consensusEps is absent from every emitted payload_json across all partitions. + for rows in by_year.values() { + for r in rows { + assert!( + !r.payload_json.to_ascii_lowercase().contains("consensus"), + "consensusEps leaked into payload_json: {}", + r.payload_json + ); + } + } + + // 2024 partition: SHOP:CA News release + let y2024 = &by_year[&2024]; + assert_eq!(y2024.len(), 1); + assert_eq!(y2024[0].listing_id, 202); + assert_eq!(y2024[0].ts_micros, utc_micros(2024, 11, 12, 12, 0, 0)); + assert_eq!(y2024[0].known_at_micros, utc_micros(2024, 11, 12, 12, 0, 0)); + assert_eq!(y2024[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(y2024[0].kind, EVENT_KIND_FILING); + assert_eq!(y2024[0].subtype, "news_release"); + + // 2025 partition: + let y2025 = &by_year[&2025]; + assert_eq!(y2025.len(), 5); + + // 101 AAPL linked earnings + EST 8-K at 2025-01-31 11:01:27 UTC ("earnings" < "filing") + let est_ts = utc_micros(2025, 1, 31, 11, 1, 27); + assert_eq!(y2025[0].listing_id, 101); + assert_eq!(y2025[0].kind, EVENT_KIND_EARNINGS); + assert_eq!(y2025[0].ts_micros, est_ts); + assert_eq!(y2025[0].known_at_micros, est_ts); + assert_eq!(y2025[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(y2025[0].subtype, "bto"); + assert!(y2025[0].payload_json.contains("\"linked_filing_id\":\"EDGAR-8K-001\"")); + + assert_eq!(y2025[1].listing_id, 101); + assert_eq!(y2025[1].kind, EVENT_KIND_FILING); + assert_eq!(y2025[1].ts_micros, est_ts); + assert_eq!(y2025[1].known_at_micros, est_ts); + assert_eq!(y2025[1].subtype, "8-k"); + + // 101 AAPL EDT 10-Q at 2025-07-15 20:30:00 UTC + let edt_ts = utc_micros(2025, 7, 15, 20, 30, 0); + assert_eq!(y2025[2].listing_id, 101); + assert_eq!(y2025[2].kind, EVENT_KIND_FILING); + assert_eq!(y2025[2].ts_micros, edt_ts); + assert_eq!(y2025[2].known_at_micros, edt_ts); + assert_eq!(y2025[2].subtype, "10-q"); + + // 202 SHOP:CA unlinked N/A earnings lagged to 2025-02-11 16:05 EST + let expected_lag = et_to_utc_micros(day(2025, 2, 11), 16, 5, 0).unwrap(); + assert_eq!(y2025[3].listing_id, 202); + assert_eq!(y2025[3].kind, EVENT_KIND_EARNINGS); + assert_eq!(y2025[3].ts_micros, expected_lag); + assert_eq!(y2025[3].known_at_micros, expected_lag); + assert_eq!(y2025[3].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert_eq!(y2025[3].subtype, "unknown"); + + // 303 ROLL Dec 31 late-evening ET rollover -> year=2025 UTC partition + assert_eq!(y2025[4].listing_id, 303); + assert_eq!(y2025[4].kind, EVENT_KIND_FILING); + assert_eq!(y2025[4].ts_micros, utc_micros(2025, 1, 1, 2, 30, 0)); + assert_eq!(y2025[4].subtype, "10-k"); + + // Report formatting smoke check + let formatted = format_curate_events_report(&report); + assert!(formatted.contains("curate-etl curate-events")); + assert!(formatted.contains("years: 2024=1 2025=5")); + + // Reversed input order must yield byte-identical Parquet files. + let tmp_rev = TempDirGuard::new("e2e-rev"); + let dir_rev = tmp_rev.path(); + fs::write(dir_rev.join("provider_mapping.tsv"), mapping_tsv).unwrap(); + let mut f_rev = filing_docs.clone(); + f_rev.reverse(); + let mut e_rev = earning_docs.clone(); + e_rev.reverse(); + fs::write(dir_rev.join("qmFilings.bson"), concat_docs(&f_rev)).unwrap(); + fs::write(dir_rev.join("qmEarnings.bson"), concat_docs(&e_rev)).unwrap(); + + let args_rev = default_args(dir_rev); + let report_rev = run_curate_events(&args_rev).expect("reversed run succeeds"); + assert_eq!(report_rev.write_stats, report.write_stats); + for year in [2024, 2025] { + let a = fs::read(args.out_dir.join(format!("events/year={year}/part.parquet"))).unwrap(); + let b = fs::read(args_rev.out_dir.join(format!("events/year={year}/part.parquet"))).unwrap(); + assert_eq!(a, b, "year={year} parquet must be byte-identical under reversed input"); + } +} + +#[test] +fn failure_modes_publish_nothing_and_preserve_sentinel() { + let tmp = TempDirGuard::new("failures"); + let dir = tmp.path(); + + let valid_mapping = "qm\tAAPL\t2020-01-01\t\t101\n"; + let valid_filing = rawdoc! { + "symbol": "AAPL", + "timefiled": "2025-01-31T06:01:27 EST", + "formtype": "10-K", + }; + let valid_earning = rawdoc! { + "qmSearchCode": "AAPL", + "reportDate": "2025-01-31", + "announceTime": "AMC", + }; + + fs::write(dir.join("provider_mapping.tsv"), valid_mapping).unwrap(); + fs::write(dir.join("qmFilings.bson"), valid_filing.as_bytes()).unwrap(); + fs::write(dir.join("qmEarnings.bson"), valid_earning.as_bytes()).unwrap(); + + // Plant a sentinel file under out/events/year=2025/part.parquet + let sentinel_path = dir.join("out/events/year=2025/part.parquet"); + fs::create_dir_all(sentinel_path.parent().unwrap()).unwrap(); + let sentinel_bytes = b"PREEXISTING_SENTINEL_BYTES"; + fs::write(&sentinel_path, sentinel_bytes).unwrap(); + + let assert_sentinel_untouched = || { + assert_eq!(fs::read(&sentinel_path).unwrap(), sentinel_bytes); + }; + + // 1. Missing qmFilings + let mut a = default_args(dir); + a.qm_filings = dir.join("does_not_exist_filings.bson"); + let err = run_curate_events(&a).unwrap_err(); + assert!(matches!(err, RunCurateEventsError::OpenInput { label: "qm-filings", .. })); + assert!(!err.to_string().contains('\n')); + assert_sentinel_untouched(); + + // 2. Missing qmEarnings + let mut a = default_args(dir); + a.qm_earnings = dir.join("does_not_exist_earnings.bson"); + let err = run_curate_events(&a).unwrap_err(); + assert!(matches!(err, RunCurateEventsError::OpenInput { label: "qm-earnings", .. })); + assert!(!err.to_string().contains('\n')); + assert_sentinel_untouched(); + + // 3. Missing provider_mapping + let mut a = default_args(dir); + a.provider_mapping = dir.join("does_not_exist_mapping.tsv"); + let err = run_curate_events(&a).unwrap_err(); + assert!(matches!(err, RunCurateEventsError::OpenInput { .. })); + assert!(!err.to_string().contains('\n')); + assert_sentinel_untouched(); + + // 4. Malformed provider_mapping.tsv + let bad_tsv = dir.join("bad_mapping.tsv"); + fs::write(&bad_tsv, "only_two_cols\tbad\n").unwrap(); + let mut a = default_args(dir); + a.provider_mapping = bad_tsv; + let err = run_curate_events(&a).unwrap_err(); + assert!(matches!(err, RunCurateEventsError::TsvParse { line: 1, .. })); + assert_sentinel_untouched(); + + // 5. Overlapping provider_mapping.tsv + let overlap_tsv = dir.join("overlap_mapping.tsv"); + fs::write( + &overlap_tsv, + "qm\tAAPL\t2020-01-01\t2024-06-01\t101\nqm\tAAPL\t2024-06-01\t\t102\n", + ) + .unwrap(); + let mut a = default_args(dir); + a.provider_mapping = overlap_tsv; + let err = run_curate_events(&a).unwrap_err(); + assert!(matches!(err, RunCurateEventsError::ProviderMapping { .. })); + assert_sentinel_untouched(); + + // 6. Truncated BSON in qmFilings + let trunc_f = dir.join("trunc_filings.bson"); + fs::write(&trunc_f, &valid_filing.as_bytes()[..10]).unwrap(); + let mut a = default_args(dir); + a.qm_filings = trunc_f; + let err = run_curate_events(&a).unwrap_err(); + assert!(matches!(err, RunCurateEventsError::BsonStream { label: "qm-filings", .. })); + assert_sentinel_untouched(); + + // 7. Truncated BSON in qmEarnings + let trunc_e = dir.join("trunc_earnings.bson"); + fs::write(&trunc_e, &valid_earning.as_bytes()[..10]).unwrap(); + let mut a = default_args(dir); + a.qm_earnings = trunc_e; + let err = run_curate_events(&a).unwrap_err(); + assert!(matches!(err, RunCurateEventsError::BsonStream { label: "qm-earnings", .. })); + assert_sentinel_untouched(); + + // 8. Corrupt BSON element in qmFilings and qmEarnings + let mut corrupt = rawdoc! { "symbol": "AAPL", "z": 1_i32 }.into_bytes(); + let z_pos = corrupt + .windows(3) + .position(|w| w == [0x10, b'z', 0x00]) + .unwrap(); + corrupt[z_pos] = 0x7e; + let corrupt_path = dir.join("corrupt.bson"); + fs::write(&corrupt_path, &corrupt).unwrap(); + + let mut a = default_args(dir); + a.qm_filings = corrupt_path.clone(); + assert!(matches!( + run_curate_events(&a), + Err(RunCurateEventsError::CorruptBson { + label: "qm-filings", + offset: 0, + .. + }) + )); + assert_sentinel_untouched(); + + let mut a = default_args(dir); + a.qm_earnings = corrupt_path; + assert!(matches!( + run_curate_events(&a), + Err(RunCurateEventsError::CorruptBson { + label: "qm-earnings", + offset: 0, + .. + }) + )); + assert_sentinel_untouched(); + + // 9. Blank, colliding, and consensusEps field configs + empty mapping_source + let mut a = default_args(dir); + a.filings_form_type_field = " ".to_string(); + assert!(matches!( + run_curate_events(&a), + Err(RunCurateEventsError::InvalidFieldNames { .. }) + )); + + let mut a = default_args(dir); + a.filings_form_type_field = DEFAULT_FILINGS_KEY_FIELD.to_string(); + assert!(matches!( + run_curate_events(&a), + Err(RunCurateEventsError::InvalidFieldNames { .. }) + )); + + let mut a = default_args(dir); + a.earnings_actual_eps_field = Some("consensusEps".to_string()); + assert!(matches!( + run_curate_events(&a), + Err(RunCurateEventsError::InvalidFieldNames { .. }) + )); + + let mut a = default_args(dir); + a.mapping_source = " ".to_string(); + assert!(matches!( + run_curate_events(&a), + Err(RunCurateEventsError::EmptyMappingSource) + )); + assert_sentinel_untouched(); + + // 10. --out as regular file + let reg_file = dir.join("not_a_dir"); + fs::write(®_file, b"x").unwrap(); + let mut a = default_args(dir); + a.out_dir = reg_file; + assert!(matches!( + run_curate_events(&a), + Err(RunCurateEventsError::InvalidOutDir { .. }) + )); + + // 11. /events as regular file + let out_blocked = dir.join("out_blocked"); + fs::create_dir_all(&out_blocked).unwrap(); + fs::write(out_blocked.join("events"), b"x").unwrap(); + let mut a = default_args(dir); + a.out_dir = out_blocked; + assert!(matches!( + run_curate_events(&a), + Err(RunCurateEventsError::InvalidOutDir { .. }) + )); + + // 12. Input file inside /events/ (clobber protection, including via `..`) + let mut a = default_args(dir); + a.qm_filings = dir.join("out/events/year=2025/../year=2025/part.parquet"); + assert!(matches!( + run_curate_events(&a), + Err(RunCurateEventsError::InvalidOutDir { .. }) + )); + assert_sentinel_untouched(); +} + +#[test] +fn empty_inputs_return_ok_without_creating_events_dir() { + let tmp = TempDirGuard::new("empty"); + let dir = tmp.path(); + fs::write(dir.join("provider_mapping.tsv"), "qm\tAAPL\t2020-01-01\t\t101\n").unwrap(); + fs::write(dir.join("qmFilings.bson"), b"").unwrap(); + fs::write(dir.join("qmEarnings.bson"), b"").unwrap(); + + let args = default_args(dir); + let report = run_curate_events(&args).expect("empty inputs succeed"); + assert_report_conservation(&report); + assert_eq!(report.write_stats.rows_written, 0); + assert_eq!(report.write_stats.files_written, 0); + assert!(!args.out_dir.join("events").exists()); +}