Merge branch 'dev' into feat/corp-actions-curate-stage
# Conflicts: # tools/curate-etl/README.md # tools/curate-etl/src/bench.rs # tools/curate-etl/src/cli.rs # tools/curate-etl/src/lib.rs # tools/curate-etl/src/main.rs
This commit is contained in:
commit
11ff35054c
31 changed files with 17618 additions and 75 deletions
|
|
@ -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`, and the `M1.2o` zero-copy raw BSON decoder for `eodPrices`.
|
||||
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`).
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -453,7 +453,29 @@ 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`, `qmSplits`, `qmDividends`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`).
|
||||
- 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`).
|
||||
|
||||
## `qmSplits` / `qmDividends` Raw BSON Decoders (`M1.2w`)
|
||||
|
||||
`decode_qm_split_doc`, `decode_qm_split_bytes`, `decode_qm_split_buffer`, `decode_qm_dividend_doc`, `decode_qm_dividend_bytes`, and `decode_qm_dividend_buffer` (`src/bson_qm_actions.rs`) decode raw MongoDB `qmSplits` and `qmDividends` BSON documents in a single forward pass over `RawDocument::iter_elements()` into borrowed `RawQmSplit<'a>` and `RawQmDividend<'a>` views without allocating a `String` or `bson::Document` per row, reusing `bson_eod_prices::iter_raw_bson_docs` for concatenated length-prefixed buffers.
|
||||
|
||||
1. **Field contract & cited in-repo sources:**
|
||||
- `qmSearchCode` (`FIELD_QM_SEARCH_CODE`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:98,118`.
|
||||
- `date` (`FIELD_DATE`): strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via `split::ymd_to_epoch_days`) or BSON `DateTime` (UTC epoch day via `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check so pre-1970 timestamps floor accurately). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:99,119`, `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `declared` (`FIELD_DECLARED`, optional): absent, BSON `Null`, or empty/whitespace-only `String` maps to `None`; strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`; malformed strings/out-of-range `DateTime` return `MalformedDate { field: "declared" }` and other types return `WrongType { field: "declared", .. }`. Cited: `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `splitratio` (`FIELD_SPLIT_RATIO`): BSON `Double`, `Int32`, or `Int64`; must be finite and `> 0.0`. `splitratio == 1.0` no-ops are **decoded, not dropped** here (downstream builders drop them) and counted in `BsonQmActionDecodeStats::split_noop_ratio_one` (a subset of `decoded`, never added to `rejected_total()`). Cited: `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `usdFxRate` (`FIELD_USD_FX_RATE`): explicitly ignored without calling `elem.value()` per `design/DATA-CONTRACTS.md` §1 (line 25: bogus `usdFxRate: 1` on CAD dividend rows). All other unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, nested objects/arrays) are likewise skipped without decoding.
|
||||
- `amount` (`FIELD_DIVIDEND_CASH`): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` normalized to `+0.0`). See **Unverified field names** below.
|
||||
- `currency` (`FIELD_DIVIDEND_CURRENCY`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). See **Unverified field names** below.
|
||||
2. **Zero-allocation key mapping & builder conversions:**
|
||||
- `RawQmSplit::to_split_event` → `SplitEvent`, `to_split_action_event` → `SplitActionEvent`; `RawQmDividend::to_dividend_event` → `DividendEvent`, `to_dividend_action_event` → `DividendActionEvent`.
|
||||
- `try_map_key(|code, ex_date| ...)` and `try_into_*` helpers mirror `RawEodDailyBar::try_into_eod_daily_bar` so callers can resolve `("qm", qmSearchCode, ex_date)` through `ProviderMappingTable` before allocating `currency` on dividends.
|
||||
3. **Typed errors & stream accounting policy:**
|
||||
- Never panics on untrusted input. `BsonQmActionError` names the offending field on every field-level error (`MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, plus framing variants `TruncatedDocument`, `CorruptDocumentLength`, `CorruptBson`).
|
||||
- Buffer decoders report and skip per-document errors without aborting the stream, always reconciling `decoded + rejected_total() == docs_in`.
|
||||
4. **Unverified field names:**
|
||||
- `amount` (`FIELD_DIVIDEND_CASH`) and `currency` (`FIELD_DIVIDEND_CURRENCY`) could not be proven from any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped and `design/DATA-CONTRACTS.md` names only `date`, `declared`, and `usdFxRate` for `qmDividends`). Both are isolated in single `pub const` constants so the live MongoDB cursor task can confirm or adjust them in one place before touching QA data.
|
||||
- Numeric strings (e.g. `"10.0"`, `"1.42"`) are currently rejected as `WrongType` because no in-repo source proves QuoteMedia sends `splitratio` or dividend cash as strings; live schema inspection should confirm whether string coercion is needed.
|
||||
|
||||
## Local Benchmarks
|
||||
|
||||
|
|
@ -669,6 +691,54 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x05af9d27
|
|||
- Run 2: `elapsed=217.38 ms`, `throughput=4600307 rows/s`, `scan=1253.15 MB/s`, `latency=217.38 ns/row`, `checksum=0x05af9d2746d1b5e3`
|
||||
- Extrapolation to full `846,000,000` `eodPrices` documents on one core (decode-only, excluding MongoDB cursor I/O and Parquet writes): `183.9 s`–`187.7 s` (`3.07`–`3.13 min`).
|
||||
|
||||
### `bench-bson-qm-actions`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) zero-copy raw BSON decode benchmark over `1,000,000` realistic synthetic QuoteMedia corporate-action documents (~4% `qmSplits`, ~96% `qmDividends`, with extra metadata `_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, bogus `usdFxRate: 1`, `declared` present/missing/`Null`, ~5% BSON `DateTime` dates, mixed `Double`/`Int32`/`Int64` numerics, ~1.5% `splitratio == 1` no-ops, and ~0.5% deterministic rejected rows) pre-encoded into two contiguous length-prefixed buffers up front, timing decode-only via `decode_qm_split_buffer` and `decode_qm_dividend_buffer`:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-bson-qm-actions [rows]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x6d48cd59e46dc9dc`): `cargo run --release -p curate-etl --offline -- bench-bson-qm-actions`
|
||||
|
||||
- Input: `rows=1000000`, `splits=40146`, `dividends=959854`, `bytes=236043886` (~225.1 MiB, ~236.0 bytes/doc)
|
||||
- Splits: `decoded=39937`, `noop_ratio_one=616`, `rejected=209` (`missing=93`, `empty=0`, `wrong_type=45`, `malformed_date=38`, `invalid_number=33`, `corrupt=0`)
|
||||
- Dividends: `decoded=954952`, `rejected=4902` (`missing=1952`, `empty=0`, `wrong_type=1009`, `malformed_date=946`, `invalid_number=995`, `corrupt=0`)
|
||||
- Run 1: `elapsed=275.12 ms`, `throughput=3634828 docs/s`, `scan=818.23 MB/s`, `latency=275.12 ns/doc`, `checksum=0x6d48cd59e46dc9dc`
|
||||
- Run 2: `elapsed=282.92 ms`, `throughput=3534598 docs/s`, `scan=795.67 MB/s`, `latency=282.92 ns/doc`, `checksum=0x6d48cd59e46dc9dc`
|
||||
|
||||
## Raw BSON Streaming Reader (`bson_stream`, `M1.2y`)
|
||||
|
||||
`RawBsonChunkReader<R: std::io::Read>` (`src/bson_stream.rs`) frames arbitrary concatenated length-prefixed raw BSON streams (files, stdin pipes, or future cursor adapters) into whole-document [`RawBsonChunk`] slices using a single reused buffer, feeding the existing zero-copy decoders (`decode_eod_price_buffer`, `decode_qm_split_buffer`, `decode_qm_dividend_buffer`) unchanged without requiring the full dataset to fit in memory.
|
||||
|
||||
1. **Bounded memory & exact growth:**
|
||||
- Defaults: `DEFAULT_CHUNK_CAPACITY_BYTES = 8 MiB`, `DEFAULT_MAX_DOC_BYTES = 16 MiB + 16 KiB` (MongoDB max document size plus headroom). `BsonStreamOptions::validate` rejects `chunk_capacity_bytes == 0` (`InvalidChunkCapacity`) and `max_doc_bytes < 5` (`InvalidMaxDocBytes`).
|
||||
- Reuses one internal `Vec<u8>` buffer across chunks, compacting any trailing partial document to the front via `copy_within`. Grows only via `reserve_exact` + `resize` when a single document exceeds the current buffer length (or to 4 bytes when `chunk_capacity_bytes < 4`), and never beyond `max_doc_bytes`. `buffer_capacity()` exposes the current allocation ceiling.
|
||||
- Retries `ErrorKind::Interrupted` transparently and handles arbitrary short reads down to 1 byte at a time.
|
||||
2. **Error semantics & sticky terminal state:**
|
||||
- Complete prefix documents already buffered are always yielded before surfacing a trailing framing or I/O error.
|
||||
- Terminal errors carry the absolute byte `offset: u64` of the offending document: declared length `< 5` or `> max_doc_bytes` → `CorruptDocumentLength`; EOF mid-header or mid-document → `TruncatedDocument`; underlying read error → `Io`. After any terminal error, subsequent `next_chunk()` calls keep returning an error without panicking, looping, or re-reading the underlying source.
|
||||
3. **Streaming decode helpers (`for<'a>` callbacks):**
|
||||
- `decode_eod_price_stream` / `decode_eod_price_chunks` → `Result<BsonEodDecodeStats, BsonStreamError>`
|
||||
- `decode_qm_split_stream` / `decode_qm_split_chunks` → `Result<BsonQmActionDecodeStats, BsonStreamError>`
|
||||
- `decode_qm_dividend_stream` / `decode_qm_dividend_chunks` → `Result<BsonQmActionDecodeStats, BsonStreamError>`
|
||||
- Because borrowed zero-copy views (`RawEodDailyBar<'a>`, `RawQmSplit<'a>`, `RawQmDividend<'a>`) borrow from the reused chunk buffer, callbacks are higher-ranked (`for<'a> FnMut(...)`). Per-document decode errors are skipped and reported with absolute `u64` stream offsets (rebasing embedded `offset` fields on `CorruptBson` errors), and chunk stats sum via `AddAssign` so `decoded + rejected_total() == docs_in` holds across the entire stream.
|
||||
|
||||
### `bench-bson-stream`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) streaming vs in-memory buffer decode benchmark over `2,000,000` synthetic `eodPrices` documents (reusing the exact `bench-bson-eod-prices` generator), decoding once via `decode_eod_price_buffer` and once via `RawBsonChunkReader` + `decode_eod_price_chunks` over an irregular short-read adapter (`257 B`..`128 KiB` prime steps straddling document and 4-byte header boundaries), asserting identical stats and checksum:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-bson-stream [rows]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-bson-stream`
|
||||
|
||||
- Input: `rows=2000000`, `bytes=571280190` (~544.8 MiB)
|
||||
- Decode: `decoded=1989987`, `rejected=10013` (`missing=3964`, `empty=0`, `wrong_type=2033`, `malformed_date=2027`, `invalid_number=1989`, `corrupt=0`), `checksum=0x94f87c60c9d3fbc6`
|
||||
- Buffer baseline: `elapsed=524.54 ms`, `throughput=3812856 rows/s`, `scan=1038.65 MiB/s`
|
||||
- Streamed short-read: `elapsed=544.59 ms`, `throughput=3672494 rows/s`, `scan=1000.42 MiB/s`, `ratio=0.963x`, `peak_buffer_capacity=8388608 bytes` (8 MiB)
|
||||
|
||||
## Deferred Follow-Ups (`M1.3+` / `M2`)
|
||||
|
||||
This crate currently depends only on `bson` (`=3.1.0`, `default-features = false, features = ["compat-3-0-0"]`) and `parquet` (`=60.2.0`, Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline. Follow-up tasks will add:
|
||||
|
|
@ -842,6 +912,61 @@ cargo run --release -p curate-etl --offline -- bench-curate-fx [rows]
|
|||
- Combined (stage → Parquet): `elapsed=275.456 ms`, `throughput=3630342 rows/s`
|
||||
- Overlap: `te_superseded=103169`, `checked=103169`, `within_tol=97958`, `mismatched=5211`, `max_overlap_rel=0.025000`
|
||||
|
||||
## `adj_factors` Curation Stage (`M1.2v`)
|
||||
|
||||
`curate_adj_factors`, `curate_adj_factors_as_of`, `curate_and_write_adj_factors`, `curate_and_write_adj_factors_as_of`, `read_adj_factors_dataset`, `read_adj_factors_dataset_as_of`, and `adj_factors_for_bar` (`src/curate_adj.rs`) join `ProviderMappingTable`, `build_adj_factors`, `session_close::et_session_close_utc_micros`, and `write_adj_factors_dataset` into contract `AdjFactorsParquetRow` records sorted and unique by `(listing_id, ex_date)`.
|
||||
|
||||
1. **Map-before-build rule:**
|
||||
- Resolves every source-keyed `qmSplits` and `qmDividends` event via `(mapping_source, source_key, ex_date) -> listing_id: i32` (using a cached per-key `ProviderMappingCursor`) *before* invoking `build_adj_factors::<i32, _, _>` unchanged.
|
||||
- Cumulative factors (`cum_split_factor`, `cum_total_factor`) therefore chain continuously per permanent `listing_id` across ticker renames (two adjacent source-key ranges mapping to one `listing_id`), while ticker reuse across distinct `listing_id`s (e.g. `FB` 2012–2022 vs `FB` 2025+) produces two independent chains with no cross-listing bleed.
|
||||
- Unmapped splits and dividends are dropped and counted separately (`splits_dropped_unmapped`, `dividends_dropped_unmapped`).
|
||||
2. **Collision policy (fail closed on cross-key conflict):**
|
||||
- Single-source-key groups on `(listing_id, ex_date)` pass through unchanged to `build_adj_factors` (preserving same-day multi-dividend summation, same-day split multiplication, `1:1` no-op drops, and zero-cash dividend drops).
|
||||
- Multi-source-key groups with bitwise-identical split ratios (or bitwise-identical dividend `cash`/`currency`/`prev_close`/`prev_close_currency`) collapse to one event and are counted in `splits_collision_collapsed`, `dividends_collision_collapsed`, and `listing_collision_collapsed`.
|
||||
- Multi-source-key groups with conflicting split ratios or differing dividend payloads fail closed with `CurateAdjError::ConflictingCrossKeySplit` / `CurateAdjError::ConflictingCrossKeyDividend` (silently dropping or doubling an event would corrupt every earlier cumulative factor).
|
||||
3. **Conservative `known_at` & point-in-time / vault-fence policy:**
|
||||
- Stamps every curated row with `known_at_micros = session_close::et_session_close_utc_micros(ex_date)` (`16:00:00 America/New_York` / `America/Toronto`: `21:00 UTC` in EST, `20:00 UTC` in EDT) because `qmSplits` / `qmDividends` adj builder inputs carry no announcement timestamp.
|
||||
- Any mapped row whose `ex_date` lies outside `1976-01-01..=2030-12-31` returns `CurateAdjError::ExDateOutOfRange` naming `(listing_id, ex_date)` without panicking (dropping a row would break the cumulative chain).
|
||||
- **Retrospective vs. Point-in-Time snapshots:** because `cum_split_factor` and `cum_total_factor` are right-to-left suffix products, later splits and dividends are embedded in earlier rows. `curate_adj_factors` / `curate_and_write_adj_factors` explicitly tag their output as `AdjSnapshotKind::RetrospectiveSnapshot` — slicing a retrospective snapshot with a bare `known_at <= as_of` filter would still leak future or held-out vault actions into earlier bars.
|
||||
- **Point-in-time & Vault fencing:** `curate_adj_factors_as_of` / `curate_and_write_adj_factors_as_of` accept an `AdjPointInTimeFence { as_of_micros, vault_cutoff_micros }` (`known_at <= as_of_micros` inclusive and `known_at < vault_cutoff_micros` strictly exclusive, matching `design/DATA-CONTRACTS.md` §4) and fence mapped source events *before* compaction and compounding, tagging the output as `AdjSnapshotKind::PointInTimeFenced(fence)`. Appending any future or vault-held action leaves earlier rows and `adj_factors_for_bar` reads bitwise identical.
|
||||
- **Persisted Parquet footer metadata & verified readers:** `curate_and_write_adj_factors` / `curate_and_write_adj_factors_as_of` publish `<out_dir>/adj_factors/part.parquet` in a single atomic file commit (one dataset lock, exclusive staging, live-preserving backup, single `rename`) embedding `stock_bot.adj_factors.{format_version, snapshot_kind, as_of_micros, vault_cutoff_micros, rows_written, snapshot_checksum}` directly in the Parquet footer `key_value_metadata` (where `snapshot_checksum` binds `format_version`, `snapshot_kind` / exact fence, row count, and all 8 columns of every row). When a run produces 0 rows (e.g. a fence excludes every event), an explicit 0-row Zstd Parquet file with the contract schema and embedded footer metadata is atomically published so any previous `part.parquet` is superseded rather than left stale. `read_adj_factors_dataset_as_of` requires a non-retrospective fence, fails closed on missing/corrupt/unsupported footer metadata, rejects retrospective snapshots (`RetrospectiveSnapshotRejected`) or any mismatched fence (`IncompatibleFence`), checks every row's `known_at` against the fence (`RowOutsideFence`), verifies per-listing `cum_split_factor` reverse suffix products, and verifies the bound `snapshot_checksum` (`SnapshotIntegrityMismatch`).
|
||||
4. **Accounting & error handling:**
|
||||
- Exact conservation invariants in `CurateAdjFactorsStats`:
|
||||
- `splits_in == splits_dropped_unmapped + splits_dropped_fenced + splits_collision_collapsed + builder.split_events_in`
|
||||
- `dividends_in == dividends_dropped_unmapped + dividends_dropped_fenced + dividends_collision_collapsed + builder.dividend_events_in`
|
||||
- `listing_collision_collapsed == splits_collision_collapsed + dividends_collision_collapsed`
|
||||
- `rows_out == builder.rows_out` and `listings_out == builder.keys_out`
|
||||
- For `AdjSnapshotKind::RetrospectiveSnapshot`, `splits_dropped_fenced == 0` and `dividends_dropped_fenced == 0`.
|
||||
- `curate_and_write_adj_factors` / `curate_and_write_adj_factors_as_of` run curation before touching `out_dir`, so any `CurateAdjError` leaves `out_dir` untouched and publishes no `adj_factors/part.parquet` (surfacing via `CurateAdjWriteError::{Curate, Parquet}`).
|
||||
5. **Deferred items:**
|
||||
- Live MongoDB cursor streaming and BSON decoders for `qmSplits` / `qmDividends`
|
||||
- PostgreSQL `provider_mapping` preload
|
||||
- Sourcing `DividendEvent.prev_close` from `bars_1d` (currently supplied by the caller)
|
||||
- `rayon` parallel sharding and end-to-end `curate` CLI command
|
||||
|
||||
### `bench-curate-adj`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) benchmark over `1,000,000` (default) or `[events]` source-keyed `qmSplits` (~4%) and `qmDividends` (~96%) events across `20,000` `String` source keys spanning `1990..=2025` (single-range keys, ticker-rename pairs, ticker-reuse keys with an H2-2018 gap, unmapped keys, and explicit bitwise-identical alias keys), separately timing in-memory `curate_adj_factors` and Zstd Parquet `write_adj_factors_dataset` into a temp directory with footer row-count verification and cleanup:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-curate-adj [events]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x024ec73a1afe7e6b`): `cargo run --release -p curate-etl --offline -- bench-curate-adj`
|
||||
|
||||
- Input: `events=1000000`, `splits=40221`, `dividends=959779`, `keys=20000`
|
||||
- Builder: `rows_out=946414`, `keys_out=19500`, `split_noops=1938`, `zero_div=9234`, `missing_prev_close=18458`, `currency_mismatch=18461`, `not_below_prev_close=9193`
|
||||
- Output: `rows_out=946414` (`94.64%` retained), `listings_out=19500`, `files=1`, `row_groups=1`, `bytes=11872037`, `read_back_rows=946414`
|
||||
- Curation stats: `splits_unmapped=1486`, `divs_unmapped=34220`, `splits_coll_collapsed=213`, `divs_coll_collapsed=4717`, `coll_collapsed=4930`
|
||||
- Run 1:
|
||||
- Stage (in-memory): `elapsed=930.92 ms`, `throughput=1074206 events/s`, `latency=930.92 ns/event`, `checksum=0x024ec73a1afe7e6b`
|
||||
- Parquet write: `elapsed=262.42 ms`, `throughput=3606439 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=1193.34 ms`, `throughput=837982 events/s`
|
||||
- Run 2:
|
||||
- Stage (in-memory): `elapsed=933.02 ms`, `throughput=1071785 events/s`, `latency=933.02 ns/event`, `checksum=0x024ec73a1afe7e6b`
|
||||
- Parquet write: `elapsed=262.81 ms`, `throughput=3601091 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=1195.84 ms`, `throughput=836235 events/s`
|
||||
|
||||
## `corporate_actions` Curation Stage (`M1.2u`)
|
||||
|
||||
`curate_corporate_actions` and `curate_and_write_corporate_actions` (`src/curate_corporate_actions.rs`) join `build_corporate_actions`, `ProviderMappingTable`, `session_close::et_session_close_utc_micros`, and `write_corporate_actions_dataset` into contract `CorporateActionsParquetRow` records sorted deterministically with non-decreasing `(listing_id, ex_date, kind)`.
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -42,7 +42,7 @@ use bson::spec::ElementType;
|
|||
use crate::bars::EodDailyBar;
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
pub(crate) const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
const MIN_BSON_DOC_LEN: i32 = 5;
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `eodPrices` BSON document.
|
||||
|
|
@ -235,6 +235,26 @@ impl BsonEodDecodeStats {
|
|||
| BsonEodPriceError::CorruptBson { .. } => self.rejected_corrupt_document += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_in += other.docs_in;
|
||||
self.decoded += other.decoded;
|
||||
self.rejected_missing_field += other.rejected_missing_field;
|
||||
self.rejected_empty_field += other.rejected_empty_field;
|
||||
self.rejected_wrong_type += other.rejected_wrong_type;
|
||||
self.rejected_malformed_date += other.rejected_malformed_date;
|
||||
self.rejected_invalid_number += other.rejected_invalid_number;
|
||||
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonEodDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
|
@ -250,22 +270,20 @@ fn parse_ascii_digits_u32(bytes: &[u8]) -> Option<u32> {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_ymd_strict(s: &str) -> Result<i32, BsonEodPriceError> {
|
||||
pub(crate) fn parse_ymd_strict_days(s: &str) -> Option<i32> {
|
||||
let bytes = s.as_bytes();
|
||||
if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
return None;
|
||||
}
|
||||
let Some(year_u32) = parse_ascii_digits_u32(&bytes[0..4]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
let Some(month) = parse_ascii_digits_u32(&bytes[5..7]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
let Some(day) = parse_ascii_digits_u32(&bytes[8..10]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
ymd_to_epoch_days(year_u32 as i32, month, day)
|
||||
.map_err(|_| BsonEodPriceError::MalformedDate { field: "date" })
|
||||
let year_u32 = parse_ascii_digits_u32(&bytes[0..4])?;
|
||||
let month = parse_ascii_digits_u32(&bytes[5..7])?;
|
||||
let day = parse_ascii_digits_u32(&bytes[8..10])?;
|
||||
ymd_to_epoch_days(year_u32 as i32, month, day).ok()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_ymd_strict(s: &str) -> Result<i32, BsonEodPriceError> {
|
||||
parse_ymd_strict_days(s).ok_or(BsonEodPriceError::MalformedDate { field: "date" })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
|
@ -438,11 +456,7 @@ pub fn decode_eod_price_doc<'a>(
|
|||
decode_eod_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawEodDailyBar`].
|
||||
pub fn decode_eod_price_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawEodDailyBar<'a>, BsonEodPriceError> {
|
||||
pub(crate) fn parse_single_raw_doc(bytes: &[u8]) -> Result<&RawDocument, BsonEodPriceError> {
|
||||
if bytes.len() < 4 {
|
||||
return Err(BsonEodPriceError::TruncatedDocument {
|
||||
offset: 0,
|
||||
|
|
@ -471,10 +485,18 @@ pub fn decode_eod_price_bytes<'a>(
|
|||
declared_len,
|
||||
});
|
||||
}
|
||||
let doc = RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
offset: 0,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawEodDailyBar`].
|
||||
pub fn decode_eod_price_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawEodDailyBar<'a>, BsonEodPriceError> {
|
||||
let doc = parse_single_raw_doc(bytes)?;
|
||||
decode_eod_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
|
|
|
|||
813
tools/curate-etl/src/bson_qm_actions.rs
Normal file
813
tools/curate-etl/src/bson_qm_actions.rs
Normal file
|
|
@ -0,0 +1,813 @@
|
|||
//! Zero-copy raw BSON decoders for MongoDB `qmSplits` and `qmDividends` documents (`M1.2w`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into
|
||||
//! borrowed [`RawQmSplit`] and [`RawQmDividend`] views without allocating a `String` or
|
||||
//! `bson::Document` per row. Callers convert borrowed views into [`SplitEvent`], [`DividendEvent`],
|
||||
//! [`SplitActionEvent`], or [`DividendActionEvent`], optionally resolving `("qm", qmSearchCode, ex_date)`
|
||||
//! through a caller-supplied key mapper (such as [`crate::provider_mapping::ProviderMappingTable::resolve`]).
|
||||
//!
|
||||
//! # Empirical Field Contract & Cited Sources
|
||||
//!
|
||||
//! - `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:92-124`: writes
|
||||
//! `qmSearchCode`, `symbol`, `exchange`, `reportDate: new Date(x.date)` plus the spread
|
||||
//! QuoteMedia API payload into `qmDividends` and `qmSplits`.
|
||||
//! - `design/DATA-CONTRACTS.md` §1 (line 25): documents `date`, `declared`, `splitratio`
|
||||
//! (`258` rows have `splitratio == 1`), and `usdFxRate` (bogus `usdFxRate: 1` on CAD dividend
|
||||
//! rows; contract rule: ignore `usdFxRate`).
|
||||
//! - **Unverified field names:** the raw MongoDB dividend cash and currency field names are not
|
||||
//! proven by any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped).
|
||||
//! They are isolated in [`FIELD_DIVIDEND_CASH`] (`"amount"`) and [`FIELD_DIVIDEND_CURRENCY`]
|
||||
//! (`"currency"`) and explicitly listed under "Unverified field names" in `tools/curate-etl/README.md`.
|
||||
//!
|
||||
//! Accepted BSON field representations:
|
||||
//! - `qmSearchCode`, `currency`: BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only
|
||||
//! is rejected).
|
||||
//! - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via
|
||||
//! [`crate::split::ymd_to_epoch_days`]) or BSON `DateTime` (UTC epoch day via
|
||||
//! `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check).
|
||||
//! - `declared` (optional): absent, BSON `Null`, or empty/whitespace `String` maps to `None`;
|
||||
//! otherwise strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`.
|
||||
//! - `splitratio`: BSON `Double`, `Int32`, or `Int64`; must be finite and `> 0.0`. `ratio == 1.0`
|
||||
//! no-ops are **decoded, not dropped** (downstream builders drop them) and counted in
|
||||
//! [`BsonQmActionDecodeStats::split_noop_ratio_one`].
|
||||
//! - `amount` (dividend cash): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0`
|
||||
//! (`-0.0` is normalized to `+0.0`).
|
||||
//! - `usdFxRate` and all unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`,
|
||||
//! `created_at`, `updated_at`, nested objects/arrays, etc.) are skipped without calling
|
||||
//! `elem.value()`.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{RawBsonRef, RawDocument, RawElement};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use crate::adj::DividendEvent;
|
||||
use crate::bson_eod_prices::{
|
||||
iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError,
|
||||
MILLIS_PER_DAY,
|
||||
};
|
||||
use crate::corporate_actions::{DividendActionEvent, SplitActionEvent};
|
||||
use crate::split::SplitEvent;
|
||||
|
||||
/// MongoDB field name for the QuoteMedia security key (`events.action.ts:98,118`).
|
||||
pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode";
|
||||
/// MongoDB field name for the ex-split / ex-dividend date (`events.action.ts:99,119`, `DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_DATE: &str = "date";
|
||||
/// MongoDB field name for the optional declaration date (`DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_DECLARED: &str = "declared";
|
||||
/// MongoDB field name for the split ratio (`DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_SPLIT_RATIO: &str = "splitratio";
|
||||
/// MongoDB field name for the bogus FX field explicitly ignored per contract (`DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_USD_FX_RATE: &str = "usdFxRate";
|
||||
/// MongoDB field name for dividend cash amount (**unverified in repo**; QuoteMedia convention).
|
||||
pub const FIELD_DIVIDEND_CASH: &str = "amount";
|
||||
/// MongoDB field name for dividend currency code (**unverified in repo**; QuoteMedia convention).
|
||||
pub const FIELD_DIVIDEND_CURRENCY: &str = "currency";
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `qmSplits` BSON document.
|
||||
///
|
||||
/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice.
|
||||
/// `ratio == 1.0` no-op rows are preserved here so downstream builders (`SplitTable`,
|
||||
/// `build_adj_factors`, `build_corporate_actions`) apply their own filtering and accounting.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawQmSplit<'a> {
|
||||
pub qm_search_code: &'a str,
|
||||
/// Ex-split date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub ex_date: i32,
|
||||
/// `new_shares / old_shares` (finite and `> 0.0`).
|
||||
pub ratio: f64,
|
||||
/// Optional declaration date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub declared_date: Option<i32>,
|
||||
}
|
||||
|
||||
impl<'a> RawQmSplit<'a> {
|
||||
/// Converts this borrowed split into a [`SplitEvent`] for [`crate::split::SplitTable`] or
|
||||
/// [`crate::adj::build_adj_factors`].
|
||||
#[inline]
|
||||
pub fn to_split_event(self) -> SplitEvent {
|
||||
SplitEvent {
|
||||
ex_date: self.ex_date,
|
||||
ratio: self.ratio,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this borrowed split into a [`SplitActionEvent`] for
|
||||
/// [`crate::corporate_actions::build_corporate_actions`].
|
||||
#[inline]
|
||||
pub fn to_split_action_event(self) -> SplitActionEvent {
|
||||
SplitActionEvent {
|
||||
ex_date: self.ex_date,
|
||||
ratio: self.ratio,
|
||||
declared_date: self.declared_date,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper
|
||||
/// (for example `|code, date| mapping.resolve("qm", code, date)`).
|
||||
#[inline]
|
||||
pub fn try_map_key<K, F>(self, map_key: F) -> Option<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
map_key(self.qm_search_code, self.ex_date)
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key and pairs it with [`SplitEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_split_event<K, F>(self, map_key: F) -> Option<(K, SplitEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_split_event()))
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key and pairs it with [`SplitActionEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_split_action_event<K, F>(self, map_key: F) -> Option<(K, SplitActionEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_split_action_event()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `qmDividends` BSON document.
|
||||
///
|
||||
/// Borrows `qm_search_code` and `currency` directly from the underlying `&RawDocument` byte slice.
|
||||
/// Deliberately omits `usdFxRate` per `design/DATA-CONTRACTS.md` §1.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawQmDividend<'a> {
|
||||
pub qm_search_code: &'a str,
|
||||
/// Ex-dividend date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub ex_date: i32,
|
||||
/// Cash dividend amount per share (finite and `>= 0.0`, with `-0.0` normalized to `+0.0`).
|
||||
pub cash: f64,
|
||||
/// Local dividend currency code (e.g. `"USD"`, `"CAD"`).
|
||||
pub currency: &'a str,
|
||||
/// Optional declaration date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub declared_date: Option<i32>,
|
||||
}
|
||||
|
||||
impl<'a> RawQmDividend<'a> {
|
||||
/// Converts this borrowed dividend into a [`DividendEvent`] for
|
||||
/// [`crate::adj::build_adj_factors`], attaching caller-supplied `prev_close` context.
|
||||
#[inline]
|
||||
pub fn to_dividend_event(
|
||||
self,
|
||||
prev_close: Option<f64>,
|
||||
prev_close_currency: Option<String>,
|
||||
) -> DividendEvent {
|
||||
DividendEvent {
|
||||
ex_date: self.ex_date,
|
||||
cash: self.cash,
|
||||
currency: self.currency.to_owned(),
|
||||
prev_close,
|
||||
prev_close_currency,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this borrowed dividend into a [`DividendActionEvent`] for
|
||||
/// [`crate::corporate_actions::build_corporate_actions`].
|
||||
#[inline]
|
||||
pub fn to_dividend_action_event(self) -> DividendActionEvent {
|
||||
DividendActionEvent {
|
||||
ex_date: self.ex_date,
|
||||
cash: self.cash,
|
||||
currency: self.currency.to_owned(),
|
||||
declared_date: self.declared_date,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper
|
||||
/// (for example `|code, date| mapping.resolve("qm", code, date)`).
|
||||
#[inline]
|
||||
pub fn try_map_key<K, F>(self, map_key: F) -> Option<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
map_key(self.qm_search_code, self.ex_date)
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key before allocating `currency` and pairs it with [`DividendEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_dividend_event<K, F>(
|
||||
self,
|
||||
prev_close: Option<f64>,
|
||||
prev_close_currency: Option<String>,
|
||||
map_key: F,
|
||||
) -> Option<(K, DividendEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_dividend_event(prev_close, prev_close_currency)))
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key before allocating `currency` and pairs it with
|
||||
/// [`DividendActionEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_dividend_action_event<K, F>(
|
||||
self,
|
||||
map_key: F,
|
||||
) -> Option<(K, DividendActionEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_dividend_action_event()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed errors returned while decoding raw `qmSplits` or `qmDividends` BSON documents or
|
||||
/// length-prefixed buffers.
|
||||
///
|
||||
/// Every field-level error names the offending BSON field in both its structure and `Display`
|
||||
/// output; no input path panics.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BsonQmActionError {
|
||||
/// A required field was absent from the document.
|
||||
MissingField { field: &'static str },
|
||||
/// A required string field was empty or contained only whitespace.
|
||||
EmptyField { field: &'static str },
|
||||
/// A decoded field had an unexpected BSON element type.
|
||||
WrongType {
|
||||
field: &'static str,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// A date field was not a valid strict `YYYY-MM-DD` Gregorian date or BSON `DateTime`
|
||||
/// overflowed `i32` epoch days.
|
||||
MalformedDate { field: &'static str },
|
||||
/// A numeric field was non-finite (`NaN`, `±inf`) or violated its domain bound (`> 0` for
|
||||
/// `splitratio`, `>= 0` for dividend cash).
|
||||
InvalidNumber { field: &'static str, value: f64 },
|
||||
/// Buffer ended before a complete 4-byte length prefix or declared document body.
|
||||
TruncatedDocument {
|
||||
offset: usize,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
|
||||
/// document slice).
|
||||
CorruptDocumentLength { offset: usize, declared_len: i32 },
|
||||
/// Underlying BSON framing or element bytes were malformed.
|
||||
CorruptBson { offset: usize, detail: String },
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonQmActionError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingField { field } => {
|
||||
write!(f, "qm action BSON missing required field '{field}'")
|
||||
}
|
||||
Self::EmptyField { field } => {
|
||||
write!(f, "qm action BSON field '{field}' must not be empty or blank")
|
||||
}
|
||||
Self::WrongType { field, actual } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' has unexpected BSON type {actual:?}"
|
||||
)
|
||||
}
|
||||
Self::MalformedDate { field } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' is not a valid YYYY-MM-DD date or in-range DateTime"
|
||||
)
|
||||
}
|
||||
Self::InvalidNumber { field, value } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' has invalid numeric value {value}"
|
||||
)
|
||||
}
|
||||
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 BsonQmActionError {}
|
||||
|
||||
#[inline]
|
||||
fn map_framing_error(err: BsonEodPriceError) -> BsonQmActionError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonQmActionError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonQmActionError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => {
|
||||
BsonQmActionError::CorruptBson { offset, detail }
|
||||
}
|
||||
BsonEodPriceError::MissingField { field } => BsonQmActionError::MissingField { field },
|
||||
BsonEodPriceError::EmptyField { field } => BsonQmActionError::EmptyField { field },
|
||||
BsonEodPriceError::WrongType { field, actual } => {
|
||||
BsonQmActionError::WrongType { field, actual }
|
||||
}
|
||||
BsonEodPriceError::MalformedDate { field } => BsonQmActionError::MalformedDate { field },
|
||||
BsonEodPriceError::InvalidNumber { field, value } => {
|
||||
BsonQmActionError::InvalidNumber { field, value }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-batch decode and rejection accounting for [`decode_qm_split_buffer`] and
|
||||
/// [`decode_qm_dividend_buffer`].
|
||||
///
|
||||
/// Conservation invariant: `decoded + rejected_total() == docs_in`.
|
||||
/// `split_noop_ratio_one` counts decoded `qmSplits` documents with `ratio == 1.0` (a subset of
|
||||
/// `decoded`, never added to `rejected_total()`).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonQmActionDecodeStats {
|
||||
pub docs_in: usize,
|
||||
pub decoded: usize,
|
||||
/// Decoded `qmSplits` rows with `splitratio == 1.0` (subset of `decoded`).
|
||||
pub split_noop_ratio_one: usize,
|
||||
pub rejected_missing_field: usize,
|
||||
pub rejected_empty_field: usize,
|
||||
pub rejected_wrong_type: usize,
|
||||
pub rejected_malformed_date: usize,
|
||||
pub rejected_invalid_number: usize,
|
||||
pub rejected_corrupt_document: usize,
|
||||
}
|
||||
|
||||
impl BsonQmActionDecodeStats {
|
||||
/// Total number of rejected documents across all error categories.
|
||||
#[inline]
|
||||
pub fn rejected_total(&self) -> usize {
|
||||
self.rejected_missing_field
|
||||
+ self.rejected_empty_field
|
||||
+ self.rejected_wrong_type
|
||||
+ self.rejected_malformed_date
|
||||
+ self.rejected_invalid_number
|
||||
+ self.rejected_corrupt_document
|
||||
}
|
||||
|
||||
/// Increments the rejection counter corresponding to `err`.
|
||||
#[inline]
|
||||
pub fn record_error(&mut self, err: &BsonQmActionError) {
|
||||
match err {
|
||||
BsonQmActionError::MissingField { .. } => self.rejected_missing_field += 1,
|
||||
BsonQmActionError::EmptyField { .. } => self.rejected_empty_field += 1,
|
||||
BsonQmActionError::WrongType { .. } => self.rejected_wrong_type += 1,
|
||||
BsonQmActionError::MalformedDate { .. } => self.rejected_malformed_date += 1,
|
||||
BsonQmActionError::InvalidNumber { .. } => self.rejected_invalid_number += 1,
|
||||
BsonQmActionError::TruncatedDocument { .. }
|
||||
| BsonQmActionError::CorruptDocumentLength { .. }
|
||||
| BsonQmActionError::CorruptBson { .. } => self.rejected_corrupt_document += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_in += other.docs_in;
|
||||
self.decoded += other.decoded;
|
||||
self.split_noop_ratio_one += other.split_noop_ratio_one;
|
||||
self.rejected_missing_field += other.rejected_missing_field;
|
||||
self.rejected_empty_field += other.rejected_empty_field;
|
||||
self.rejected_wrong_type += other.rejected_wrong_type;
|
||||
self.rejected_malformed_date += other.rejected_malformed_date;
|
||||
self.rejected_invalid_number += other.rejected_invalid_number;
|
||||
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonQmActionDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_element_value<'a>(
|
||||
field: &'static str,
|
||||
elem: RawElement<'a>,
|
||||
offset: usize,
|
||||
) -> Result<RawBsonRef<'a>, BsonQmActionError> {
|
||||
elem.value().map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: format!("field '{field}': {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_non_empty_str<'a>(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'a>,
|
||||
) -> Result<&'a str, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
return Err(BsonQmActionError::EmptyField { field });
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_required_date(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<i32, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
parse_ymd_strict_days(s).ok_or(BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
RawBsonRef::DateTime(dt) => {
|
||||
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
|
||||
i32::try_from(days).map_err(|_| BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_optional_date(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<Option<i32>, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Null => Ok(None),
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
parse_ymd_strict_days(s)
|
||||
.map(Some)
|
||||
.ok_or(BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
RawBsonRef::DateTime(dt) => {
|
||||
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
|
||||
i32::try_from(days)
|
||||
.map(Some)
|
||||
.map_err(|_| BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_positive_number(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v <= 0.0 {
|
||||
return Err(BsonQmActionError::InvalidNumber { field, value: v });
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v <= 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: f64::from(v),
|
||||
});
|
||||
}
|
||||
Ok(f64::from(v))
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v <= 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: v as f64,
|
||||
});
|
||||
}
|
||||
Ok(v as f64)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_non_negative_number(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v < 0.0 {
|
||||
return Err(BsonQmActionError::InvalidNumber { field, value: v });
|
||||
}
|
||||
if v == 0.0 {
|
||||
Ok(0.0)
|
||||
} else {
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: f64::from(v),
|
||||
});
|
||||
}
|
||||
Ok(f64::from(v))
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: v as f64,
|
||||
});
|
||||
}
|
||||
Ok(v as f64)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_qm_split_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
let mut qm_search_code: Option<&'a str> = None;
|
||||
let mut ex_date: Option<i32> = None;
|
||||
let mut ratio: Option<f64> = None;
|
||||
let mut declared_date: Option<i32> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
|
||||
if key == FIELD_QM_SEARCH_CODE {
|
||||
let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?;
|
||||
qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?);
|
||||
} else if key == FIELD_DATE {
|
||||
let val = decode_element_value(FIELD_DATE, elem, offset)?;
|
||||
ex_date = Some(decode_required_date(FIELD_DATE, val)?);
|
||||
} else if key == FIELD_SPLIT_RATIO {
|
||||
let val = decode_element_value(FIELD_SPLIT_RATIO, elem, offset)?;
|
||||
ratio = Some(decode_positive_number(FIELD_SPLIT_RATIO, val)?);
|
||||
} else if key == FIELD_DECLARED {
|
||||
let val = decode_element_value(FIELD_DECLARED, elem, offset)?;
|
||||
declared_date = decode_optional_date(FIELD_DECLARED, val)?;
|
||||
}
|
||||
// `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
let Some(qm_search_code) = qm_search_code else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
};
|
||||
let Some(ex_date) = ex_date else {
|
||||
return Err(BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
};
|
||||
let Some(ratio) = ratio else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
});
|
||||
};
|
||||
|
||||
Ok(RawQmSplit {
|
||||
qm_search_code,
|
||||
ex_date,
|
||||
ratio,
|
||||
declared_date,
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_qm_dividend_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
let mut qm_search_code: Option<&'a str> = None;
|
||||
let mut ex_date: Option<i32> = None;
|
||||
let mut cash: Option<f64> = None;
|
||||
let mut currency: Option<&'a str> = None;
|
||||
let mut declared_date: Option<i32> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
|
||||
if key == FIELD_QM_SEARCH_CODE {
|
||||
let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?;
|
||||
qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?);
|
||||
} else if key == FIELD_DATE {
|
||||
let val = decode_element_value(FIELD_DATE, elem, offset)?;
|
||||
ex_date = Some(decode_required_date(FIELD_DATE, val)?);
|
||||
} else if key == FIELD_DIVIDEND_CASH {
|
||||
let val = decode_element_value(FIELD_DIVIDEND_CASH, elem, offset)?;
|
||||
cash = Some(decode_non_negative_number(FIELD_DIVIDEND_CASH, val)?);
|
||||
} else if key == FIELD_DIVIDEND_CURRENCY {
|
||||
let val = decode_element_value(FIELD_DIVIDEND_CURRENCY, elem, offset)?;
|
||||
currency = Some(decode_non_empty_str(FIELD_DIVIDEND_CURRENCY, val)?);
|
||||
} else if key == FIELD_DECLARED {
|
||||
let val = decode_element_value(FIELD_DECLARED, elem, offset)?;
|
||||
declared_date = decode_optional_date(FIELD_DECLARED, val)?;
|
||||
}
|
||||
// `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
let Some(qm_search_code) = qm_search_code else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
};
|
||||
let Some(ex_date) = ex_date else {
|
||||
return Err(BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
};
|
||||
let Some(cash) = cash else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
});
|
||||
};
|
||||
let Some(currency) = currency else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CURRENCY,
|
||||
});
|
||||
};
|
||||
|
||||
Ok(RawQmDividend {
|
||||
qm_search_code,
|
||||
ex_date,
|
||||
cash,
|
||||
currency,
|
||||
declared_date,
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `qmSplits` MongoDB document in one forward pass
|
||||
/// without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_qm_split_doc<'a>(doc: &'a RawDocument) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
decode_qm_split_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed [`RawQmSplit`].
|
||||
pub fn decode_qm_split_bytes<'a>(bytes: &'a [u8]) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_qm_split_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `qmDividends` MongoDB document in one forward
|
||||
/// pass without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_qm_dividend_doc<'a>(
|
||||
doc: &'a RawDocument,
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
decode_qm_dividend_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawQmDividend`].
|
||||
pub fn decode_qm_dividend_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_qm_dividend_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_split_doc`], invoking
|
||||
/// `on_split` for every valid document (including `splitratio == 1.0`, counted in
|
||||
/// `stats.split_noop_ratio_one`) and `on_error(byte_offset, err)` for every rejected document
|
||||
/// without aborting the stream on per-document errors.
|
||||
///
|
||||
/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`.
|
||||
pub fn decode_qm_split_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_split: F,
|
||||
mut on_error: E,
|
||||
) -> BsonQmActionDecodeStats
|
||||
where
|
||||
F: FnMut(RawQmSplit<'a>),
|
||||
E: FnMut(usize, BsonQmActionError),
|
||||
{
|
||||
let mut stats = BsonQmActionDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
stats.docs_in += 1;
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => match decode_qm_split_doc_at(doc, doc_offset) {
|
||||
Ok(split) => {
|
||||
stats.decoded += 1;
|
||||
if split.ratio == 1.0 {
|
||||
stats.split_noop_ratio_one += 1;
|
||||
}
|
||||
on_split(split);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
},
|
||||
Err((doc_offset, err)) => {
|
||||
let mapped = map_framing_error(err);
|
||||
stats.record_error(&mapped);
|
||||
on_error(doc_offset, mapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_dividend_doc`], invoking
|
||||
/// `on_dividend` for every valid document and `on_error(byte_offset, err)` for every rejected
|
||||
/// document without aborting the stream on per-document errors.
|
||||
///
|
||||
/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`.
|
||||
pub fn decode_qm_dividend_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_dividend: F,
|
||||
mut on_error: E,
|
||||
) -> BsonQmActionDecodeStats
|
||||
where
|
||||
F: FnMut(RawQmDividend<'a>),
|
||||
E: FnMut(usize, BsonQmActionError),
|
||||
{
|
||||
let mut stats = BsonQmActionDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
stats.docs_in += 1;
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => match decode_qm_dividend_doc_at(doc, doc_offset) {
|
||||
Ok(dividend) => {
|
||||
stats.decoded += 1;
|
||||
on_dividend(dividend);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
},
|
||||
Err((doc_offset, err)) => {
|
||||
let mapped = map_framing_error(err);
|
||||
stats.record_error(&mapped);
|
||||
on_error(doc_offset, mapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_qm_actions_tests.rs"]
|
||||
mod tests;
|
||||
883
tools/curate-etl/src/bson_qm_actions_tests.rs
Normal file
883
tools/curate-etl/src/bson_qm_actions_tests.rs
Normal file
|
|
@ -0,0 +1,883 @@
|
|||
use bson::oid::ObjectId;
|
||||
use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf};
|
||||
use bson::spec::ElementType;
|
||||
use bson::DateTime;
|
||||
|
||||
use super::*;
|
||||
use crate::corporate_actions::{build_corporate_actions, CorporateActionKind, KnownAtSource};
|
||||
use crate::curate_adj::curate_adj_factors;
|
||||
use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable};
|
||||
use crate::split::{ymd_to_epoch_days, SplitTable};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
fn make_split_doc(code: &str, date: &str, ratio: f64, declared: Option<&str>) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
if let Some(decl) = declared {
|
||||
doc.append(cstr!("declared"), decl);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
fn make_dividend_doc(
|
||||
code: &str,
|
||||
date: &str,
|
||||
cash: f64,
|
||||
currency: &str,
|
||||
declared: Option<&str>,
|
||||
) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), currency);
|
||||
if let Some(decl) = declared {
|
||||
doc.append(cstr!("declared"), decl);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_realistic_qm_split_and_dividend_docs_and_ignores_extra_and_usd_fx_rate() {
|
||||
let mut nested = RawDocumentBuf::new();
|
||||
nested.append(cstr!("provider"), "quotemedia");
|
||||
nested.append(cstr!("version"), 1_i32);
|
||||
|
||||
let mut tags = RawArrayBuf::new();
|
||||
tags.push("ca");
|
||||
tags.push("equity");
|
||||
|
||||
// Realistic qmSplits document with extra metadata and bogus usdFxRate.
|
||||
let mut split_doc = RawDocumentBuf::new();
|
||||
split_doc.append(
|
||||
cstr!("_id"),
|
||||
ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
|
||||
);
|
||||
split_doc.append(cstr!("symbol"), "NVDA");
|
||||
split_doc.append(cstr!("exchange"), "NASDAQ");
|
||||
split_doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
split_doc.append(cstr!("date"), "2024-06-10");
|
||||
split_doc.append(cstr!("declared"), "2024-05-22");
|
||||
split_doc.append(cstr!("splitratio"), 10.0_f64);
|
||||
split_doc.append(cstr!("usdFxRate"), "bogus-ignored-type");
|
||||
split_doc.append(
|
||||
cstr!("reportDate"),
|
||||
DateTime::from_millis(i64::from(day(2024, 6, 10)) * MILLIS_PER_DAY),
|
||||
);
|
||||
split_doc.append(cstr!("created_at"), DateTime::from_millis(1_718_000_000_000));
|
||||
split_doc.append(cstr!("updated_at"), DateTime::from_millis(1_718_000_060_000));
|
||||
split_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
split_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let split = decode_qm_split_doc(&split_doc).unwrap();
|
||||
assert_eq!(split.qm_search_code, "NVDA");
|
||||
assert_eq!(split.ex_date, day(2024, 6, 10));
|
||||
assert_eq!(split.ratio.to_bits(), 10.0_f64.to_bits());
|
||||
assert_eq!(split.declared_date, Some(day(2024, 5, 22)));
|
||||
assert_eq!(decode_qm_split_bytes(split_doc.as_bytes()).unwrap(), split);
|
||||
|
||||
// Realistic qmDividends document with bogus usdFxRate: 1 on CAD row.
|
||||
let mut div_doc = RawDocumentBuf::new();
|
||||
div_doc.append(
|
||||
cstr!("_id"),
|
||||
ObjectId::from_bytes([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]),
|
||||
);
|
||||
div_doc.append(cstr!("symbol"), "RY");
|
||||
div_doc.append(cstr!("exchange"), "TSX");
|
||||
div_doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
div_doc.append(cstr!("date"), "2024-11-15");
|
||||
div_doc.append(cstr!("declared"), "2024-10-30");
|
||||
div_doc.append(cstr!("amount"), 1.42_f64);
|
||||
div_doc.append(cstr!("currency"), "CAD");
|
||||
div_doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
div_doc.append(
|
||||
cstr!("reportDate"),
|
||||
DateTime::from_millis(i64::from(day(2024, 11, 15)) * MILLIS_PER_DAY),
|
||||
);
|
||||
div_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
div_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let div = decode_qm_dividend_doc(&div_doc).unwrap();
|
||||
assert_eq!(div.qm_search_code, "RY:CA");
|
||||
assert_eq!(div.ex_date, day(2024, 11, 15));
|
||||
assert_eq!(div.cash.to_bits(), 1.42_f64.to_bits());
|
||||
assert_eq!(div.currency, "CAD");
|
||||
assert_eq!(div.declared_date, Some(day(2024, 10, 30)));
|
||||
assert_eq!(decode_qm_dividend_bytes(div_doc.as_bytes()).unwrap(), div);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_date_and_declared_as_string_and_datetime_including_pre_1970_and_leap_day() {
|
||||
// Pre-1970 mid-day: 1969-12-31T12:34:56.789Z must floor to epoch day -1 (not 0).
|
||||
let pre_1970_ex_ms: i64 = -MILLIS_PER_DAY + (12 * 3600 + 34 * 60 + 56) * 1000 + 789;
|
||||
let pre_1970_decl_ms: i64 = -10 * MILLIS_PER_DAY + 43_200_000;
|
||||
|
||||
let mut split_dt = RawDocumentBuf::new();
|
||||
split_dt.append(cstr!("qmSearchCode"), "IBM");
|
||||
split_dt.append(cstr!("date"), DateTime::from_millis(pre_1970_ex_ms));
|
||||
split_dt.append(cstr!("declared"), DateTime::from_millis(pre_1970_decl_ms));
|
||||
split_dt.append(cstr!("splitratio"), 2_i32);
|
||||
|
||||
let split = decode_qm_split_doc(&split_dt).unwrap();
|
||||
assert_eq!(split.ex_date, -1);
|
||||
assert_eq!(split.declared_date, Some(-10));
|
||||
assert_eq!(split.ratio, 2.0);
|
||||
|
||||
// Leap day string + DateTime declared.
|
||||
let mut div_leap = RawDocumentBuf::new();
|
||||
div_leap.append(cstr!("qmSearchCode"), "TD:CA");
|
||||
div_leap.append(cstr!("date"), "2024-02-29");
|
||||
div_leap.append(
|
||||
cstr!("declared"),
|
||||
DateTime::from_millis(i64::from(day(2024, 2, 1)) * MILLIS_PER_DAY + 36_000_000),
|
||||
);
|
||||
div_leap.append(cstr!("amount"), 1.02_f64);
|
||||
div_leap.append(cstr!("currency"), "CAD");
|
||||
|
||||
let div = decode_qm_dividend_doc(&div_leap).unwrap();
|
||||
assert_eq!(div.ex_date, day(2024, 2, 29));
|
||||
assert_eq!(div.declared_date, Some(day(2024, 2, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_double_int32_int64_numerics_and_normalizes_negative_zero_cash() {
|
||||
// Splits: Double, Int32, Int64.
|
||||
for (val, expected) in [
|
||||
(RawBsonRef::Double(0.05), 0.05_f64),
|
||||
(RawBsonRef::Int32(4), 4.0_f64),
|
||||
(RawBsonRef::Int64(10), 10.0_f64),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "TEST");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), val);
|
||||
let decoded = decode_qm_split_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.ratio.to_bits(), expected.to_bits());
|
||||
}
|
||||
|
||||
// Dividends: Double, Int32, Int64, 0, and -0.0 -> +0.0.
|
||||
for (val, expected) in [
|
||||
(RawBsonRef::Double(0.25), 0.25_f64),
|
||||
(RawBsonRef::Double(-0.0), 0.0_f64),
|
||||
(RawBsonRef::Double(0.0), 0.0_f64),
|
||||
(RawBsonRef::Int32(0), 0.0_f64),
|
||||
(RawBsonRef::Int32(2), 2.0_f64),
|
||||
(RawBsonRef::Int64(0), 0.0_f64),
|
||||
(RawBsonRef::Int64(5), 5.0_f64),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "TEST");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), val);
|
||||
doc.append(cstr!("currency"), "USD");
|
||||
let decoded = decode_qm_dividend_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.cash.to_bits(), expected.to_bits());
|
||||
assert!(!decoded.cash.is_sign_negative());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_optional_declared_missing_null_empty_malformed_and_wrong_type() {
|
||||
// Missing declared -> None.
|
||||
let s_missing = make_split_doc("AAPL", "2020-08-31", 4.0, None);
|
||||
assert_eq!(decode_qm_split_doc(&s_missing).unwrap().declared_date, None);
|
||||
|
||||
// Null declared -> None.
|
||||
let mut s_null = make_split_doc("AAPL", "2020-08-31", 4.0, None);
|
||||
s_null.append(cstr!("declared"), RawBsonRef::Null);
|
||||
assert_eq!(decode_qm_split_doc(&s_null).unwrap().declared_date, None);
|
||||
|
||||
// Empty and whitespace-only declared -> None.
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let d_blank = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", Some(blank));
|
||||
assert_eq!(
|
||||
decode_qm_dividend_doc(&d_blank).unwrap().declared_date,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
// Malformed declared -> MalformedDate naming "declared".
|
||||
let s_bad = make_split_doc("AAPL", "2020-08-31", 4.0, Some("2023-02-29"));
|
||||
let err = decode_qm_split_doc(&s_bad).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MalformedDate {
|
||||
field: FIELD_DECLARED
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DECLARED));
|
||||
|
||||
// Wrong type on declared -> WrongType naming "declared".
|
||||
let mut d_wrong = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None);
|
||||
d_wrong.append(cstr!("declared"), 20240801_i32);
|
||||
let err = decode_qm_dividend_doc(&d_wrong).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DECLARED,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DECLARED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_ratio_one_is_decoded_not_dropped_and_counted_as_noop() {
|
||||
let mut buf = Vec::new();
|
||||
for val in [
|
||||
RawBsonRef::Double(1.0),
|
||||
RawBsonRef::Int32(1),
|
||||
RawBsonRef::Int64(1),
|
||||
RawBsonRef::Double(2.0),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NOOP");
|
||||
doc.append(cstr!("date"), "2024-03-15");
|
||||
doc.append(cstr!("splitratio"), val);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
}
|
||||
|
||||
let mut decoded_ratios = Vec::new();
|
||||
let stats = decode_qm_split_buffer(
|
||||
&buf,
|
||||
|s| decoded_ratios.push(s.ratio),
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
assert_eq!(decoded_ratios, vec![1.0, 1.0, 1.0, 2.0]);
|
||||
assert_eq!(stats.docs_in, 4);
|
||||
assert_eq!(stats.decoded, 4);
|
||||
assert_eq!(stats.split_noop_ratio_one, 3);
|
||||
assert_eq!(stats.rejected_total(), 0);
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_every_error_variant_and_names_offending_field() {
|
||||
// 1. Missing required fields on splits.
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
|
||||
// 2. Missing required fields on dividends.
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
doc.append(cstr!("currency"), "USD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CASH
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CURRENCY
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 3. Empty / whitespace-only string fields.
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let s = make_split_doc(blank, "2024-06-10", 2.0, None);
|
||||
let err = decode_qm_split_doc(&s).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::EmptyField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
|
||||
let d = make_dividend_doc("RY:CA", "2024-06-10", 0.5, blank, None);
|
||||
let err = decode_qm_dividend_doc(&d).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::EmptyField {
|
||||
field: FIELD_DIVIDEND_CURRENCY
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 4. Wrong BSON types (including string-encoded numerics).
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), 123_i32);
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), 20240610_i32);
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DATE,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), "10.0");
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
actual: ElementType::String,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), "1.42");
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
actual: ElementType::String,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 1.42_f64);
|
||||
doc.append(cstr!("currency"), true);
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DIVIDEND_CURRENCY,
|
||||
actual: ElementType::Boolean,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 5. Malformed dates (bad calendar date, bad format, and DateTime overflowing i32 days).
|
||||
for bad_date in ["2023-02-29", "2024/06/10", "2024-6-10", "not-a-date"] {
|
||||
let doc = make_split_doc("NVDA", bad_date, 2.0, None);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), DateTime::from_millis(i64::MAX));
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE });
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("declared"), DateTime::from_millis(i64::MIN));
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MalformedDate {
|
||||
field: FIELD_DECLARED
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 6. Invalid numeric values for splitratio (<= 0 or non-finite).
|
||||
for bad_ratio in [
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Double(0.0),
|
||||
RawBsonRef::Double(-0.0),
|
||||
RawBsonRef::Double(-2.0),
|
||||
RawBsonRef::Int32(0),
|
||||
RawBsonRef::Int32(-1),
|
||||
RawBsonRef::Int64(0),
|
||||
RawBsonRef::Int64(-5),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), bad_ratio);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected InvalidNumber for {bad_ratio:?}, got {err:?}"
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
|
||||
// 7. Invalid numeric values for dividend cash (< 0 or non-finite).
|
||||
for bad_cash in [
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Double(-0.01),
|
||||
RawBsonRef::Int32(-1),
|
||||
RawBsonRef::Int64(-10),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), bad_cash);
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected InvalidNumber for {bad_cash:?}, got {err:?}"
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
|
||||
// 8. Truncated and corrupt documents (zero panics).
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&[]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 0,
|
||||
declared_len: None
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_dividend_bytes(&[1, 2, 3]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 3,
|
||||
declared_len: None
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&4_i32.to_le_bytes()),
|
||||
Err(BsonQmActionError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: 4
|
||||
})
|
||||
));
|
||||
let valid_bytes = make_split_doc("NVDA", "2024-06-10", 10.0, None)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&valid_bytes[..valid_bytes.len() - 1]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
declared_len: Some(_),
|
||||
..
|
||||
})
|
||||
));
|
||||
let mut with_trailing = valid_bytes.clone();
|
||||
with_trailing.push(0);
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&with_trailing),
|
||||
Err(BsonQmActionError::CorruptDocumentLength { offset: 0, .. })
|
||||
));
|
||||
let mut bad_terminator = valid_bytes;
|
||||
*bad_terminator.last_mut().unwrap() = 0xFF;
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&bad_terminator),
|
||||
Err(BsonQmActionError::CorruptBson { offset: 0, .. })
|
||||
));
|
||||
|
||||
// Invalid UTF-8 inside a known string field (`qmSearchCode`).
|
||||
let mut invalid_utf8_doc: Vec<u8> = Vec::new();
|
||||
// Placeholder 4-byte length.
|
||||
invalid_utf8_doc.extend_from_slice(&0_i32.to_le_bytes());
|
||||
invalid_utf8_doc.push(0x02); // UTF-8 String element
|
||||
invalid_utf8_doc.extend_from_slice(b"qmSearchCode\0");
|
||||
invalid_utf8_doc.extend_from_slice(&3_i32.to_le_bytes()); // 2 bytes + NUL
|
||||
invalid_utf8_doc.extend_from_slice(&[0xFF, 0xFE, 0x00]);
|
||||
invalid_utf8_doc.push(0x00); // doc terminator
|
||||
let total_len = invalid_utf8_doc.len() as i32;
|
||||
invalid_utf8_doc[0..4].copy_from_slice(&total_len.to_le_bytes());
|
||||
let err = decode_qm_split_bytes(&invalid_utf8_doc).unwrap_err();
|
||||
assert!(matches!(err, BsonQmActionError::CorruptBson { offset: 0, .. }));
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffer_decoders_survive_per_doc_errors_and_reconcile_stats_for_both_collections() {
|
||||
// 1. qmSplits mixed valid/invalid buffer.
|
||||
let s1 = make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22"));
|
||||
let s_noop = make_split_doc("NOOP", "2024-06-11", 1.0, None);
|
||||
let mut s_missing = RawDocumentBuf::new();
|
||||
s_missing.append(cstr!("qmSearchCode"), "MISS");
|
||||
s_missing.append(cstr!("date"), "2024-06-12");
|
||||
let s_empty = make_split_doc(" ", "2024-06-13", 2.0, None);
|
||||
let mut s_wrong = RawDocumentBuf::new();
|
||||
s_wrong.append(cstr!("qmSearchCode"), "WRNG");
|
||||
s_wrong.append(cstr!("date"), "2024-06-14");
|
||||
s_wrong.append(cstr!("splitratio"), "2.0");
|
||||
let s_bad_date = make_split_doc("DATE", "2023-02-29", 2.0, None);
|
||||
let s_bad_num = make_split_doc("NUM", "2024-06-15", 0.0, None);
|
||||
let mut s_corrupt = make_split_doc("CORR", "2024-06-16", 2.0, None)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
*s_corrupt.last_mut().unwrap() = 0xAA;
|
||||
let s2 = make_split_doc("NEXM:CA", "2025-06-18", 0.05, None);
|
||||
|
||||
let mut split_buf = Vec::new();
|
||||
split_buf.extend_from_slice(s1.as_bytes());
|
||||
split_buf.extend_from_slice(s_noop.as_bytes());
|
||||
split_buf.extend_from_slice(s_missing.as_bytes());
|
||||
split_buf.extend_from_slice(s_empty.as_bytes());
|
||||
split_buf.extend_from_slice(s_wrong.as_bytes());
|
||||
split_buf.extend_from_slice(s_bad_date.as_bytes());
|
||||
split_buf.extend_from_slice(s_bad_num.as_bytes());
|
||||
split_buf.extend_from_slice(&s_corrupt);
|
||||
split_buf.extend_from_slice(s2.as_bytes());
|
||||
|
||||
let mut split_codes = Vec::new();
|
||||
let mut split_errors = Vec::new();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| split_codes.push(s.qm_search_code.to_owned()),
|
||||
|off, err| split_errors.push((off, err)),
|
||||
);
|
||||
|
||||
assert_eq!(split_codes, vec!["NVDA", "NOOP", "NEXM:CA"]);
|
||||
assert_eq!(split_errors.len(), 6);
|
||||
assert_eq!(split_stats.docs_in, 9);
|
||||
assert_eq!(split_stats.decoded, 3);
|
||||
assert_eq!(split_stats.split_noop_ratio_one, 1);
|
||||
assert_eq!(split_stats.rejected_missing_field, 1);
|
||||
assert_eq!(split_stats.rejected_empty_field, 1);
|
||||
assert_eq!(split_stats.rejected_wrong_type, 1);
|
||||
assert_eq!(split_stats.rejected_malformed_date, 1);
|
||||
assert_eq!(split_stats.rejected_invalid_number, 1);
|
||||
assert_eq!(split_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(
|
||||
split_stats.decoded + split_stats.rejected_total(),
|
||||
split_stats.docs_in
|
||||
);
|
||||
|
||||
// 2. qmDividends mixed valid/invalid buffer ending with a corrupt length prefix.
|
||||
let d1 = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30"));
|
||||
let mut d_missing = RawDocumentBuf::new();
|
||||
d_missing.append(cstr!("qmSearchCode"), "MISS");
|
||||
d_missing.append(cstr!("date"), "2024-11-15");
|
||||
d_missing.append(cstr!("amount"), 0.5_f64);
|
||||
let d_empty = make_dividend_doc("RY:CA", "2024-11-15", 0.5, " ", None);
|
||||
let mut d_wrong = RawDocumentBuf::new();
|
||||
d_wrong.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_wrong.append(cstr!("date"), "2024-11-15");
|
||||
d_wrong.append(cstr!("amount"), "0.5");
|
||||
d_wrong.append(cstr!("currency"), "CAD");
|
||||
let d_bad_date = make_dividend_doc("RY:CA", "2024-11-15", 0.5, "CAD", Some("bad"));
|
||||
let d_bad_num = make_dividend_doc("RY:CA", "2024-11-15", -0.1, "CAD", None);
|
||||
let d2 = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None);
|
||||
|
||||
let mut div_buf = Vec::new();
|
||||
div_buf.extend_from_slice(d1.as_bytes());
|
||||
div_buf.extend_from_slice(d_missing.as_bytes());
|
||||
div_buf.extend_from_slice(d_empty.as_bytes());
|
||||
div_buf.extend_from_slice(d_wrong.as_bytes());
|
||||
div_buf.extend_from_slice(d_bad_date.as_bytes());
|
||||
div_buf.extend_from_slice(d_bad_num.as_bytes());
|
||||
div_buf.extend_from_slice(d2.as_bytes());
|
||||
// Trailing corrupt length < 5 stops cleanly.
|
||||
div_buf.extend_from_slice(&2_i32.to_le_bytes());
|
||||
div_buf.extend_from_slice(d2.as_bytes());
|
||||
|
||||
let mut div_codes = Vec::new();
|
||||
let mut div_errors = Vec::new();
|
||||
let div_stats = decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| div_codes.push(d.qm_search_code.to_owned()),
|
||||
|off, err| div_errors.push((off, err)),
|
||||
);
|
||||
|
||||
assert_eq!(div_codes, vec!["RY:CA", "AAPL"]);
|
||||
assert_eq!(div_errors.len(), 6);
|
||||
assert_eq!(div_stats.docs_in, 8);
|
||||
assert_eq!(div_stats.decoded, 2);
|
||||
assert_eq!(div_stats.split_noop_ratio_one, 0);
|
||||
assert_eq!(div_stats.rejected_missing_field, 1);
|
||||
assert_eq!(div_stats.rejected_empty_field, 1);
|
||||
assert_eq!(div_stats.rejected_wrong_type, 1);
|
||||
assert_eq!(div_stats.rejected_malformed_date, 1);
|
||||
assert_eq!(div_stats.rejected_invalid_number, 1);
|
||||
assert_eq!(div_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(
|
||||
div_stats.decoded + div_stats.rejected_total(),
|
||||
div_stats.docs_in
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_events_feed_split_table_curate_adj_factors_and_corporate_actions_unchanged() {
|
||||
// 1. SplitTable interoperability (NVDA 10:1 forward, NEXM:CA 1:20 reverse, 1:1 no-op).
|
||||
let mut split_buf = Vec::new();
|
||||
split_buf.extend_from_slice(
|
||||
make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22")).as_bytes(),
|
||||
);
|
||||
split_buf.extend_from_slice(make_split_doc("NVDA", "2024-07-01", 1.0, None).as_bytes());
|
||||
split_buf.extend_from_slice(make_split_doc("NEXM:CA", "2025-06-18", 0.05, None).as_bytes());
|
||||
split_buf.extend_from_slice(make_split_doc("UNMAPPED", "2024-06-10", 2.0, None).as_bytes());
|
||||
|
||||
let mut div_buf = Vec::new();
|
||||
let mut ry_div = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30"));
|
||||
ry_div.append(cstr!("usdFxRate"), 1_i32); // bogus usdFxRate must have zero effect
|
||||
div_buf.extend_from_slice(ry_div.as_bytes());
|
||||
let mut unmapped_div = make_dividend_doc("UNMAPPED", "2024-11-15", 0.50, "USD", None);
|
||||
unmapped_div.append(cstr!("usdFxRate"), 999.0_f64);
|
||||
div_buf.extend_from_slice(unmapped_div.as_bytes());
|
||||
|
||||
let mut source_splits = Vec::new();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| source_splits.push((s.qm_search_code.to_owned(), s.to_split_event())),
|
||||
|_, err| panic!("unexpected split decode error: {err}"),
|
||||
);
|
||||
assert_eq!(split_stats.split_noop_ratio_one, 1);
|
||||
|
||||
let table = SplitTable::from_events(source_splits.iter().cloned()).unwrap();
|
||||
assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 7)), 10.0);
|
||||
assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 10)), 1.0);
|
||||
assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 17)), 0.05);
|
||||
assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 18)), 1.0);
|
||||
|
||||
// 2. ProviderMappingTable + curate_adj_factors interoperability.
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "NVDA".to_string(),
|
||||
listing_id: 101,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "NEXM:CA".to_string(),
|
||||
listing_id: 202,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "RY:CA".to_string(),
|
||||
listing_id: 303,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let mut source_divs = Vec::new();
|
||||
decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| {
|
||||
source_divs.push((
|
||||
d.qm_search_code.to_owned(),
|
||||
d.to_dividend_event(Some(142.0), Some("CAD".to_string())),
|
||||
));
|
||||
},
|
||||
|_, err| panic!("unexpected dividend decode error: {err}"),
|
||||
);
|
||||
|
||||
let curated = curate_adj_factors(&mapping, "qm", source_splits, source_divs).unwrap();
|
||||
// 1:1 NVDA split dropped by builder; UNMAPPED split & dividend dropped by mapping.
|
||||
assert_eq!(curated.rows.len(), 3);
|
||||
assert_eq!(curated.stats.builder.split_noops_dropped, 1);
|
||||
assert_eq!(curated.stats.splits_dropped_unmapped, 1);
|
||||
assert_eq!(curated.stats.dividends_dropped_unmapped, 1);
|
||||
|
||||
// Row 0: listing 101 (NVDA) 10:1 split
|
||||
assert_eq!(curated.rows[0].listing_id, 101);
|
||||
assert_eq!(curated.rows[0].ex_date, day(2024, 6, 10));
|
||||
assert_eq!(curated.rows[0].split_factor, 10.0);
|
||||
assert_eq!(curated.rows[0].cum_split_factor, 10.0);
|
||||
|
||||
// Row 1: listing 202 (NEXM:CA) 1:20 reverse split
|
||||
assert_eq!(curated.rows[1].listing_id, 202);
|
||||
assert_eq!(curated.rows[1].ex_date, day(2025, 6, 18));
|
||||
assert_eq!(curated.rows[1].split_factor, 0.05);
|
||||
|
||||
// Row 2: listing 303 (RY:CA) CAD dividend with usdFxRate ignored
|
||||
assert_eq!(curated.rows[2].listing_id, 303);
|
||||
assert_eq!(curated.rows[2].ex_date, day(2024, 11, 15));
|
||||
assert_eq!(curated.rows[2].div_cash, 1.42);
|
||||
assert_eq!(curated.rows[2].div_currency.as_deref(), Some("CAD"));
|
||||
let expected_div_factor = 142.0 / (142.0 - 1.42);
|
||||
assert!((curated.rows[2].cum_total_factor - expected_div_factor).abs() < 1e-12);
|
||||
|
||||
// 3. try_map_key / try_into_*_action_event -> build_corporate_actions.
|
||||
let mut mapped_split_actions = Vec::new();
|
||||
decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| {
|
||||
if let Some(pair) =
|
||||
s.try_into_split_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
mapped_split_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
let mut mapped_div_actions = Vec::new();
|
||||
decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| {
|
||||
if let Some(pair) =
|
||||
d.try_into_dividend_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
mapped_div_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
// Also verify try_into_split_event & try_into_dividend_event filter unmapped keys.
|
||||
let unmapped_split_doc = make_split_doc("UNMAPPED", "2024-06-10", 2.0, None);
|
||||
let unmapped_split = decode_qm_split_doc(&unmapped_split_doc).unwrap();
|
||||
assert_eq!(
|
||||
unmapped_split.try_into_split_event(|code, date| mapping.resolve("qm", code, date)),
|
||||
None
|
||||
);
|
||||
let mapped_div = decode_qm_dividend_doc(&ry_div).unwrap();
|
||||
let (lid, div_ev) = mapped_div
|
||||
.try_into_dividend_event(Some(142.0), Some("CAD".to_string()), |code, date| {
|
||||
mapping.resolve("qm", code, date)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(lid, 303);
|
||||
assert_eq!(div_ev.currency, "CAD");
|
||||
|
||||
let ca = build_corporate_actions(
|
||||
mapped_split_actions,
|
||||
mapped_div_actions,
|
||||
std::iter::empty(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(ca.rows.len(), 3);
|
||||
assert_eq!(ca.stats.split_noops_dropped, 1);
|
||||
|
||||
// NVDA split has declared_date -> DeclaredDate.
|
||||
assert_eq!(ca.rows[0].key, 101);
|
||||
assert_eq!(ca.rows[0].kind, CorporateActionKind::Split);
|
||||
assert_eq!(ca.rows[0].declared_date, Some(day(2024, 5, 22)));
|
||||
assert_eq!(ca.rows[0].known_at_source, KnownAtSource::DeclaredDate);
|
||||
|
||||
// NEXM split has no declared_date -> ExDateFallback.
|
||||
assert_eq!(ca.rows[1].key, 202);
|
||||
assert_eq!(ca.rows[1].kind, CorporateActionKind::Split);
|
||||
assert_eq!(ca.rows[1].declared_date, None);
|
||||
assert_eq!(ca.rows[1].known_at_source, KnownAtSource::ExDateFallback);
|
||||
|
||||
// RY:CA dividend has declared_date -> DeclaredDate.
|
||||
assert_eq!(ca.rows[2].key, 303);
|
||||
assert_eq!(ca.rows[2].kind, CorporateActionKind::Dividend);
|
||||
assert_eq!(ca.rows[2].cash_amount, Some(1.42));
|
||||
assert_eq!(ca.rows[2].currency.as_deref(), Some("CAD"));
|
||||
assert_eq!(ca.rows[2].declared_date, Some(day(2024, 10, 30)));
|
||||
assert_eq!(ca.rows[2].known_at_source, KnownAtSource::DeclaredDate);
|
||||
}
|
||||
661
tools/curate-etl/src/bson_stream.rs
Normal file
661
tools/curate-etl/src/bson_stream.rs
Normal file
|
|
@ -0,0 +1,661 @@
|
|||
//! Bounded-memory streaming reader for concatenated raw BSON (`M1.2y`).
|
||||
//!
|
||||
//! Reads length-prefixed raw BSON documents from any [`std::io::Read`] source (files, stdin pipes,
|
||||
//! or future cursor adapters) into a single reused byte buffer with a fixed memory ceiling,
|
||||
//! framing only complete documents into [`RawBsonChunk`] slices that can be passed directly to the
|
||||
//! existing zero-copy decoders (`decode_eod_price_buffer`, `decode_qm_split_buffer`,
|
||||
//! `decode_qm_dividend_buffer`).
|
||||
//!
|
||||
//! # Callback Lifetime Bound (`for<'a>`)
|
||||
//!
|
||||
//! Because [`RawBsonChunkReader`] reuses one internal byte buffer across chunks, borrowed zero-copy
|
||||
//! document views ([`RawEodDailyBar<'a>`], [`RawQmSplit<'a>`], [`RawQmDividend<'a>`]) only remain
|
||||
//! valid for the duration of the chunk in which they were decoded. The streaming decode helpers
|
||||
//! ([`decode_eod_price_stream`], [`decode_qm_split_stream`], [`decode_qm_dividend_stream`], and
|
||||
//! their `*_chunks` counterparts) therefore require higher-ranked callbacks
|
||||
//! (`F: for<'a> FnMut(RawEodDailyBar<'a>)`, etc.) so closures cannot escape borrowed slices past a
|
||||
//! chunk boundary. Callers should map or intern borrowed keys (e.g. via
|
||||
//! `ProviderMappingTable::resolve`) or copy only the retained fields inside the callback.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
|
||||
use crate::bson_eod_prices::{
|
||||
decode_eod_price_buffer, BsonEodDecodeStats, BsonEodPriceError, RawEodDailyBar,
|
||||
};
|
||||
use crate::bson_qm_actions::{
|
||||
decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, BsonQmActionError,
|
||||
RawQmDividend, RawQmSplit,
|
||||
};
|
||||
|
||||
/// Default chunk buffer capacity: 8 MiB.
|
||||
pub const DEFAULT_CHUNK_CAPACITY_BYTES: usize = 8 * 1024 * 1024;
|
||||
/// Default maximum allowed BSON document size: 16 MiB (MongoDB limit) + 16 KiB headroom.
|
||||
pub const DEFAULT_MAX_DOC_BYTES: usize = 16 * 1024 * 1024 + 16 * 1024;
|
||||
/// Minimum valid length-prefixed BSON document size (4-byte length prefix + trailing `0x00`).
|
||||
pub const MIN_BSON_DOC_BYTES: usize = 5;
|
||||
|
||||
/// Configuration options for [`RawBsonChunkReader`] and the `decode_*_stream` helpers.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BsonStreamOptions {
|
||||
/// Initial reusable buffer size in bytes (capped at `max_doc_bytes`). Must be `> 0`.
|
||||
pub chunk_capacity_bytes: usize,
|
||||
/// Hard upper bound on any single BSON document's declared byte length. Must be `>= 5`.
|
||||
pub max_doc_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for BsonStreamOptions {
|
||||
#[inline]
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
chunk_capacity_bytes: DEFAULT_CHUNK_CAPACITY_BYTES,
|
||||
max_doc_bytes: DEFAULT_MAX_DOC_BYTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BsonStreamOptions {
|
||||
/// Validates option invariants, rejecting `chunk_capacity_bytes == 0` and `max_doc_bytes < 5`.
|
||||
#[inline]
|
||||
pub fn validate(&self) -> Result<(), BsonStreamError> {
|
||||
if self.chunk_capacity_bytes == 0 {
|
||||
return Err(BsonStreamError::InvalidChunkCapacity);
|
||||
}
|
||||
if self.max_doc_bytes < MIN_BSON_DOC_BYTES {
|
||||
return Err(BsonStreamError::InvalidMaxDocBytes);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Terminal errors returned by [`RawBsonChunkReader`] and the `decode_*_stream` helpers.
|
||||
///
|
||||
/// Every stream-level framing or I/O error carries the absolute byte `offset` of the offending
|
||||
/// document in the underlying stream.
|
||||
#[derive(Debug)]
|
||||
pub enum BsonStreamError {
|
||||
/// `BsonStreamOptions::chunk_capacity_bytes` was `0`.
|
||||
InvalidChunkCapacity,
|
||||
/// `BsonStreamOptions::max_doc_bytes` was `< 5`.
|
||||
InvalidMaxDocBytes,
|
||||
/// Declared 4-byte little-endian BSON document length was `< 5` or `> max_doc_bytes`.
|
||||
CorruptDocumentLength {
|
||||
offset: u64,
|
||||
declared_len: i32,
|
||||
max_doc_bytes: usize,
|
||||
},
|
||||
/// Stream reached EOF mid-header (`declared_len == None`) or mid-document (`Some(len)`).
|
||||
TruncatedDocument {
|
||||
offset: u64,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
/// Underlying [`std::io::Read`] failed with a non-`Interrupted` error.
|
||||
Io { offset: u64, source: io::Error },
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonStreamError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidChunkCapacity => {
|
||||
write!(f, "invalid BSON stream chunk_capacity_bytes: must be > 0")
|
||||
}
|
||||
Self::InvalidMaxDocBytes => {
|
||||
write!(
|
||||
f,
|
||||
"invalid BSON stream max_doc_bytes: must be >= {MIN_BSON_DOC_BYTES}"
|
||||
)
|
||||
}
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
max_doc_bytes,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON document length {declared_len} at stream offset {offset} (valid range: {MIN_BSON_DOC_BYTES}..={max_doc_bytes})"
|
||||
),
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => match declared_len {
|
||||
Some(len) => write!(
|
||||
f,
|
||||
"truncated BSON document at stream offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
|
||||
),
|
||||
None => write!(
|
||||
f,
|
||||
"truncated BSON document header at stream offset {offset}: only {remaining} bytes remaining"
|
||||
),
|
||||
},
|
||||
Self::Io { offset, source } => {
|
||||
write!(
|
||||
f,
|
||||
"I/O error reading BSON stream at offset {offset}: {source}"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for BsonStreamError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::Io { source, .. } => Some(source),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A borrowed chunk of complete, length-prefixed raw BSON documents from [`RawBsonChunkReader`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct RawBsonChunk<'a> {
|
||||
/// Contiguous bytes containing one or more complete length-prefixed BSON documents.
|
||||
pub bytes: &'a [u8],
|
||||
/// Absolute byte offset of `bytes[0]` from the start of the underlying stream.
|
||||
pub start_offset: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum StickyError {
|
||||
CorruptDocumentLength {
|
||||
offset: u64,
|
||||
declared_len: i32,
|
||||
max_doc_bytes: usize,
|
||||
},
|
||||
TruncatedDocument {
|
||||
offset: u64,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
Io {
|
||||
offset: u64,
|
||||
kind: io::ErrorKind,
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl StickyError {
|
||||
fn to_error(&self) -> BsonStreamError {
|
||||
match self {
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
max_doc_bytes,
|
||||
} => BsonStreamError::CorruptDocumentLength {
|
||||
offset: *offset,
|
||||
declared_len: *declared_len,
|
||||
max_doc_bytes: *max_doc_bytes,
|
||||
},
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonStreamError::TruncatedDocument {
|
||||
offset: *offset,
|
||||
remaining: *remaining,
|
||||
declared_len: *declared_len,
|
||||
},
|
||||
Self::Io {
|
||||
offset,
|
||||
kind,
|
||||
message,
|
||||
} => BsonStreamError::Io {
|
||||
offset: *offset,
|
||||
source: io::Error::new(*kind, message.clone()),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum TerminalState {
|
||||
Active,
|
||||
Eof,
|
||||
Failed(StickyError),
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_i32_le(bytes: &[u8]) -> i32 {
|
||||
i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
|
||||
}
|
||||
|
||||
/// Bounded-memory chunked reader for concatenated length-prefixed raw BSON documents.
|
||||
///
|
||||
/// Reuses a single internal byte buffer across all calls to [`Self::next_chunk`], carrying any
|
||||
/// trailing partial document to the front of the buffer before the next fill. The initial
|
||||
/// allocation is capped at `min(options.chunk_capacity_bytes, options.max_doc_bytes)`; the buffer
|
||||
/// grows only when a single document exceeds the current buffer length (or to 4 bytes when
|
||||
/// `chunk_capacity_bytes < 4`), and never beyond `options.max_doc_bytes`.
|
||||
pub struct RawBsonChunkReader<R: io::Read> {
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
buf: Vec<u8>,
|
||||
filled: usize,
|
||||
consumed: usize,
|
||||
buf_start_offset: u64,
|
||||
bytes_read: u64,
|
||||
docs_framed: u64,
|
||||
eof_reached: bool,
|
||||
pending_io_err: Option<io::Error>,
|
||||
terminal: TerminalState,
|
||||
}
|
||||
|
||||
impl<R: io::Read> RawBsonChunkReader<R> {
|
||||
/// Creates a new chunk reader with [`BsonStreamOptions::default`].
|
||||
pub fn new(reader: R) -> Self {
|
||||
let options = BsonStreamOptions::default();
|
||||
let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes);
|
||||
Self {
|
||||
reader,
|
||||
options,
|
||||
buf: vec![0u8; initial_cap],
|
||||
filled: 0,
|
||||
consumed: 0,
|
||||
buf_start_offset: 0,
|
||||
bytes_read: 0,
|
||||
docs_framed: 0,
|
||||
eof_reached: false,
|
||||
pending_io_err: None,
|
||||
terminal: TerminalState::Active,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new chunk reader with explicit [`BsonStreamOptions`], validating them up front.
|
||||
pub fn with_options(reader: R, options: BsonStreamOptions) -> Result<Self, BsonStreamError> {
|
||||
options.validate()?;
|
||||
let initial_cap = options.chunk_capacity_bytes.min(options.max_doc_bytes);
|
||||
Ok(Self {
|
||||
reader,
|
||||
options,
|
||||
buf: vec![0u8; initial_cap],
|
||||
filled: 0,
|
||||
consumed: 0,
|
||||
buf_start_offset: 0,
|
||||
bytes_read: 0,
|
||||
docs_framed: 0,
|
||||
eof_reached: false,
|
||||
pending_io_err: None,
|
||||
terminal: TerminalState::Active,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the configured stream options.
|
||||
#[inline]
|
||||
pub fn options(&self) -> BsonStreamOptions {
|
||||
self.options
|
||||
}
|
||||
|
||||
/// Returns the current allocated capacity of the reusable internal buffer in bytes.
|
||||
#[inline]
|
||||
pub fn buffer_capacity(&self) -> usize {
|
||||
self.buf.capacity()
|
||||
}
|
||||
|
||||
/// Returns the total number of bytes read from the underlying reader so far.
|
||||
#[inline]
|
||||
pub fn bytes_read(&self) -> u64 {
|
||||
self.bytes_read
|
||||
}
|
||||
|
||||
/// Returns the total number of complete length-prefixed documents framed and yielded so far.
|
||||
#[inline]
|
||||
pub fn docs_framed(&self) -> u64 {
|
||||
self.docs_framed
|
||||
}
|
||||
|
||||
/// Consumes the chunk reader, returning the underlying [`std::io::Read`] source.
|
||||
#[inline]
|
||||
pub fn into_inner(self) -> R {
|
||||
self.reader
|
||||
}
|
||||
|
||||
/// Grows `self.buf` to exactly `target_len` without doubling past `max_doc_bytes`.
|
||||
fn grow_buf_exact(&mut self, target_len: usize) {
|
||||
debug_assert!(target_len <= self.options.max_doc_bytes);
|
||||
if target_len > self.buf.len() {
|
||||
if target_len > self.buf.capacity() {
|
||||
self.buf.reserve_exact(target_len - self.buf.len());
|
||||
}
|
||||
self.buf.resize(target_len, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads and frames the next chunk of complete length-prefixed BSON documents.
|
||||
///
|
||||
/// Returns `Ok(None)` at clean EOF. Any terminal framing or I/O error locks the reader into a
|
||||
/// failed state so subsequent calls continue returning an error without panicking or looping.
|
||||
pub fn next_chunk(&mut self) -> Result<Option<RawBsonChunk<'_>>, BsonStreamError> {
|
||||
match &self.terminal {
|
||||
TerminalState::Active => {}
|
||||
TerminalState::Eof => return Ok(None),
|
||||
TerminalState::Failed(err) => return Err(err.to_error()),
|
||||
}
|
||||
|
||||
// Compact bytes already yielded by the previous chunk.
|
||||
if self.consumed > 0 {
|
||||
if self.consumed < self.filled {
|
||||
self.buf.copy_within(self.consumed..self.filled, 0);
|
||||
}
|
||||
self.filled -= self.consumed;
|
||||
self.buf_start_offset += self.consumed as u64;
|
||||
self.consumed = 0;
|
||||
}
|
||||
|
||||
let mut chunk_end = 0usize;
|
||||
let mut chunk_docs = 0u64;
|
||||
loop {
|
||||
// Incrementally frame complete documents as bytes arrive so a corrupt length prefix
|
||||
// stops the fill loop immediately without issuing further reads.
|
||||
let mut saw_corrupt_len = false;
|
||||
while self.filled - chunk_end >= 4 {
|
||||
let declared_len = read_i32_le(&self.buf[chunk_end..chunk_end + 4]);
|
||||
if declared_len < MIN_BSON_DOC_BYTES as i32
|
||||
|| (declared_len as usize) > self.options.max_doc_bytes
|
||||
{
|
||||
if chunk_end == 0 {
|
||||
let err = StickyError::CorruptDocumentLength {
|
||||
offset: self.buf_start_offset,
|
||||
declared_len,
|
||||
max_doc_bytes: self.options.max_doc_bytes,
|
||||
};
|
||||
self.terminal = TerminalState::Failed(err.clone());
|
||||
return Err(err.to_error());
|
||||
}
|
||||
// Yield any complete preceding documents first; the next call will compact
|
||||
// this corrupt header to index 0 and surface `CorruptDocumentLength`.
|
||||
saw_corrupt_len = true;
|
||||
break;
|
||||
}
|
||||
let doc_len = declared_len as usize;
|
||||
if chunk_end == 0
|
||||
&& doc_len > self.buf.len()
|
||||
&& !self.eof_reached
|
||||
&& self.pending_io_err.is_none()
|
||||
{
|
||||
self.grow_buf_exact(doc_len);
|
||||
}
|
||||
if doc_len > self.filled - chunk_end {
|
||||
break;
|
||||
}
|
||||
chunk_end += doc_len;
|
||||
chunk_docs += 1;
|
||||
}
|
||||
|
||||
if saw_corrupt_len || self.eof_reached || self.pending_io_err.is_some() {
|
||||
break;
|
||||
}
|
||||
|
||||
if self.filled == self.buf.len() {
|
||||
if self.filled < 4 {
|
||||
// `chunk_capacity_bytes` was in `1..=3`; grow to 4 bytes (always <= max_doc_bytes).
|
||||
self.grow_buf_exact(4);
|
||||
} else {
|
||||
// Buffer is full and the leading document fit in `self.buf.len()`, so at least
|
||||
// one complete document is ready to yield.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
match self.reader.read(&mut self.buf[self.filled..]) {
|
||||
Ok(0) => {
|
||||
self.eof_reached = true;
|
||||
break;
|
||||
}
|
||||
Ok(n) => {
|
||||
self.filled += n;
|
||||
self.bytes_read += n as u64;
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(err) => {
|
||||
self.pending_io_err = Some(err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if chunk_end > 0 {
|
||||
self.consumed = chunk_end;
|
||||
self.docs_framed += chunk_docs;
|
||||
return Ok(Some(RawBsonChunk {
|
||||
bytes: &self.buf[..chunk_end],
|
||||
start_offset: self.buf_start_offset,
|
||||
}));
|
||||
}
|
||||
|
||||
// No complete document could be framed; surface pending I/O error, clean EOF, or truncation.
|
||||
if let Some(source) = self.pending_io_err.take() {
|
||||
let offset = self.buf_start_offset;
|
||||
self.terminal = TerminalState::Failed(StickyError::Io {
|
||||
offset,
|
||||
kind: source.kind(),
|
||||
message: source.to_string(),
|
||||
});
|
||||
return Err(BsonStreamError::Io { offset, source });
|
||||
}
|
||||
|
||||
if self.filled == 0 {
|
||||
self.terminal = TerminalState::Eof;
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let declared_len = if self.filled >= 4 {
|
||||
Some(read_i32_le(&self.buf[0..4]))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let err = StickyError::TruncatedDocument {
|
||||
offset: self.buf_start_offset,
|
||||
remaining: self.filled,
|
||||
declared_len,
|
||||
};
|
||||
self.terminal = TerminalState::Failed(err.clone());
|
||||
Err(err.to_error())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rebase_offset(base: u64, local: usize) -> usize {
|
||||
let abs = base.saturating_add(local as u64);
|
||||
usize::try_from(abs).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rebase_eod_error(base: u64, err: BsonEodPriceError) -> BsonEodPriceError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonEodPriceError::TruncatedDocument {
|
||||
offset: rebase_offset(base, offset),
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonEodPriceError::CorruptDocumentLength {
|
||||
offset: rebase_offset(base, offset),
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => BsonEodPriceError::CorruptBson {
|
||||
offset: rebase_offset(base, offset),
|
||||
detail,
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rebase_qm_error(base: u64, err: BsonQmActionError) -> BsonQmActionError {
|
||||
match err {
|
||||
BsonQmActionError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonQmActionError::TruncatedDocument {
|
||||
offset: rebase_offset(base, offset),
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonQmActionError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonQmActionError::CorruptDocumentLength {
|
||||
offset: rebase_offset(base, offset),
|
||||
declared_len,
|
||||
},
|
||||
BsonQmActionError::CorruptBson { offset, detail } => BsonQmActionError::CorruptBson {
|
||||
offset: rebase_offset(base, offset),
|
||||
detail,
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_price_buffer`],
|
||||
/// accumulating [`BsonEodDecodeStats`] and rebasing per-document error offsets to absolute stream
|
||||
/// byte offsets.
|
||||
pub fn decode_eod_price_chunks<R, F, E>(
|
||||
reader: &mut RawBsonChunkReader<R>,
|
||||
mut on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> Result<BsonEodDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawEodDailyBar<'a>),
|
||||
E: FnMut(u64, BsonEodPriceError),
|
||||
{
|
||||
let mut total = BsonEodDecodeStats::default();
|
||||
while let Some(chunk) = reader.next_chunk()? {
|
||||
let base = chunk.start_offset;
|
||||
let chunk_stats = decode_eod_price_buffer(
|
||||
chunk.bytes,
|
||||
&mut on_bar,
|
||||
|local_offset, err| {
|
||||
let abs_offset = base + local_offset as u64;
|
||||
on_error(abs_offset, rebase_eod_error(base, err));
|
||||
},
|
||||
);
|
||||
total += chunk_stats;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Streams a concatenated raw BSON `eodPrices` [`std::io::Read`] source through
|
||||
/// [`decode_eod_price_buffer`] with bounded memory.
|
||||
///
|
||||
/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset
|
||||
/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`.
|
||||
pub fn decode_eod_price_stream<R, F, E>(
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
on_bar: F,
|
||||
on_error: E,
|
||||
) -> Result<BsonEodDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawEodDailyBar<'a>),
|
||||
E: FnMut(u64, BsonEodPriceError),
|
||||
{
|
||||
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
|
||||
decode_eod_price_chunks(&mut chunk_reader, on_bar, on_error)
|
||||
}
|
||||
|
||||
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_split_buffer`],
|
||||
/// accumulating [`BsonQmActionDecodeStats`] and rebasing per-document error offsets to absolute
|
||||
/// stream byte offsets.
|
||||
pub fn decode_qm_split_chunks<R, F, E>(
|
||||
reader: &mut RawBsonChunkReader<R>,
|
||||
mut on_split: F,
|
||||
mut on_error: E,
|
||||
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawQmSplit<'a>),
|
||||
E: FnMut(u64, BsonQmActionError),
|
||||
{
|
||||
let mut total = BsonQmActionDecodeStats::default();
|
||||
while let Some(chunk) = reader.next_chunk()? {
|
||||
let base = chunk.start_offset;
|
||||
let chunk_stats = decode_qm_split_buffer(
|
||||
chunk.bytes,
|
||||
&mut on_split,
|
||||
|local_offset, err| {
|
||||
let abs_offset = base + local_offset as u64;
|
||||
on_error(abs_offset, rebase_qm_error(base, err));
|
||||
},
|
||||
);
|
||||
total += chunk_stats;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Streams a concatenated raw BSON `qmSplits` [`std::io::Read`] source through
|
||||
/// [`decode_qm_split_buffer`] with bounded memory.
|
||||
pub fn decode_qm_split_stream<R, F, E>(
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
on_split: F,
|
||||
on_error: E,
|
||||
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawQmSplit<'a>),
|
||||
E: FnMut(u64, BsonQmActionError),
|
||||
{
|
||||
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
|
||||
decode_qm_split_chunks(&mut chunk_reader, on_split, on_error)
|
||||
}
|
||||
|
||||
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_dividend_buffer`],
|
||||
/// accumulating [`BsonQmActionDecodeStats`] and rebasing per-document error offsets to absolute
|
||||
/// stream byte offsets.
|
||||
pub fn decode_qm_dividend_chunks<R, F, E>(
|
||||
reader: &mut RawBsonChunkReader<R>,
|
||||
mut on_dividend: F,
|
||||
mut on_error: E,
|
||||
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawQmDividend<'a>),
|
||||
E: FnMut(u64, BsonQmActionError),
|
||||
{
|
||||
let mut total = BsonQmActionDecodeStats::default();
|
||||
while let Some(chunk) = reader.next_chunk()? {
|
||||
let base = chunk.start_offset;
|
||||
let chunk_stats = decode_qm_dividend_buffer(
|
||||
chunk.bytes,
|
||||
&mut on_dividend,
|
||||
|local_offset, err| {
|
||||
let abs_offset = base + local_offset as u64;
|
||||
on_error(abs_offset, rebase_qm_error(base, err));
|
||||
},
|
||||
);
|
||||
total += chunk_stats;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Streams a concatenated raw BSON `qmDividends` [`std::io::Read`] source through
|
||||
/// [`decode_qm_dividend_buffer`] with bounded memory.
|
||||
pub fn decode_qm_dividend_stream<R, F, E>(
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
on_dividend: F,
|
||||
on_error: E,
|
||||
) -> Result<BsonQmActionDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawQmDividend<'a>),
|
||||
E: FnMut(u64, BsonQmActionError),
|
||||
{
|
||||
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
|
||||
decode_qm_dividend_chunks(&mut chunk_reader, on_dividend, on_error)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_stream_tests.rs"]
|
||||
mod tests;
|
||||
1724
tools/curate-etl/src/bson_stream_tests.rs
Normal file
1724
tools/curate-etl/src/bson_stream_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -5,10 +5,11 @@
|
|||
|
||||
use crate::bench::{
|
||||
DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS,
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_BARS_BENCH_ROWS, DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_EVENTS_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS,
|
||||
DEFAULT_CURATE_SHORTS_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS,
|
||||
DEFAULT_BSON_STREAM_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
DEFAULT_CURATE_ADJ_BENCH_EVENTS, DEFAULT_CURATE_BARS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_CURATE_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_SHORTS_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,
|
||||
|
|
@ -35,10 +36,13 @@ pub enum CliAction {
|
|||
BenchParquetAdj(usize),
|
||||
BenchParquetCorporateActions(usize),
|
||||
BenchBsonEodPrices(usize),
|
||||
BenchBsonQmActions(usize),
|
||||
BenchBsonStream(usize),
|
||||
BenchCurateBars(usize),
|
||||
BenchCurateShorts(usize),
|
||||
BenchCurateEvents(usize),
|
||||
BenchCurateFx(usize),
|
||||
BenchCurateAdj(usize),
|
||||
BenchCurateCorporateActions(usize),
|
||||
}
|
||||
|
||||
|
|
@ -65,10 +69,13 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-parquet-adj [rows] Run fixed-seed adj_factors Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_ADJ_BENCH_ROWS})\n\
|
||||
{name} bench-parquet-corporate-actions [rows] Run fixed-seed corporate_actions Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS})\n\
|
||||
{name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\
|
||||
{name} bench-bson-qm-actions [rows] Run fixed-seed qmSplits/qmDividends raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS})\n\
|
||||
{name} bench-bson-stream [rows] Run fixed-seed eodPrices raw BSON stream vs buffer decode benchmark (default: {DEFAULT_BSON_STREAM_BENCH_ROWS})\n\
|
||||
{name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_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-fx [rows] Run fixed-seed fx_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_FX_BENCH_ROWS})\n\
|
||||
{name} bench-curate-adj [events] Run fixed-seed adj_factors curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_ADJ_BENCH_EVENTS})\n\
|
||||
{name} bench-curate-corporate-actions [events] Run fixed-seed corporate_actions curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS})"
|
||||
)
|
||||
}
|
||||
|
|
@ -94,10 +101,13 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-parquet-adj [rows]\n\
|
||||
{name} bench-parquet-corporate-actions [rows]\n\
|
||||
{name} bench-bson-eod-prices [rows]\n\
|
||||
{name} bench-bson-qm-actions [rows]\n\
|
||||
{name} bench-bson-stream [rows]\n\
|
||||
{name} bench-curate-bars [rows]\n\
|
||||
{name} bench-curate-shorts [rows]\n\
|
||||
{name} bench-curate-events [rows]\n\
|
||||
{name} bench-curate-fx [rows]\n\
|
||||
{name} bench-curate-adj [events]\n\
|
||||
{name} bench-curate-corporate-actions [events]"
|
||||
)
|
||||
}
|
||||
|
|
@ -263,6 +273,28 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["bench-bson-eod-prices", _, ..] => {
|
||||
Err("too many arguments for bench-bson-eod-prices".to_string())
|
||||
}
|
||||
["bench-bson-qm-actions"] => Ok(CliAction::BenchBsonQmActions(
|
||||
DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS,
|
||||
)),
|
||||
["bench-bson-qm-actions", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchBsonQmActions(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-bson-qm-actions", _, ..] => {
|
||||
Err("too many arguments for bench-bson-qm-actions".to_string())
|
||||
}
|
||||
["bench-bson-stream"] => Ok(CliAction::BenchBsonStream(DEFAULT_BSON_STREAM_BENCH_ROWS)),
|
||||
["bench-bson-stream", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchBsonStream(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-bson-stream", _, ..] => {
|
||||
Err("too many arguments for bench-bson-stream".to_string())
|
||||
}
|
||||
["bench-curate-bars"] => Ok(CliAction::BenchCurateBars(DEFAULT_CURATE_BARS_BENCH_ROWS)),
|
||||
["bench-curate-bars", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateBars(n)),
|
||||
|
|
@ -305,6 +337,14 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
)),
|
||||
},
|
||||
["bench-curate-fx", _, ..] => Err("too many arguments for bench-curate-fx".to_string()),
|
||||
["bench-curate-adj"] => Ok(CliAction::BenchCurateAdj(DEFAULT_CURATE_ADJ_BENCH_EVENTS)),
|
||||
["bench-curate-adj", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateAdj(n)),
|
||||
_ => Err(format!(
|
||||
"invalid event count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-curate-adj", _, ..] => Err("too many arguments for bench-curate-adj".to_string()),
|
||||
["bench-curate-corporate-actions"] => Ok(CliAction::BenchCurateCorporateActions(
|
||||
DEFAULT_CURATE_CORPORATE_ACTIONS_BENCH_EVENTS,
|
||||
)),
|
||||
|
|
@ -604,6 +644,40 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-bson-eod-prices", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_bson_qm_actions_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-qm-actions"])),
|
||||
Ok(CliAction::BenchBsonQmActions(
|
||||
DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-qm-actions", "250000"])),
|
||||
Ok(CliAction::BenchBsonQmActions(250_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-qm-actions", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_bson_stream_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-stream"])),
|
||||
Ok(CliAction::BenchBsonStream(DEFAULT_BSON_STREAM_BENCH_ROWS))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-bson-stream", "250000"])),
|
||||
Ok(CliAction::BenchBsonStream(250_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-bson-stream", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-stream", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-stream", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-bson-stream", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_strings_mention_all_benchmarks() {
|
||||
let full = format_usage("curate-etl", "0.1.0");
|
||||
|
|
@ -622,10 +696,13 @@ mod tests {
|
|||
assert!(full.contains("bench-parquet-adj"));
|
||||
assert!(full.contains("bench-parquet-corporate-actions"));
|
||||
assert!(full.contains("bench-bson-eod-prices"));
|
||||
assert!(full.contains("bench-bson-qm-actions"));
|
||||
assert!(full.contains("bench-bson-stream"));
|
||||
assert!(full.contains("bench-curate-bars"));
|
||||
assert!(full.contains("bench-curate-shorts"));
|
||||
assert!(full.contains("bench-curate-events"));
|
||||
assert!(full.contains("bench-curate-fx"));
|
||||
assert!(full.contains("bench-curate-adj"));
|
||||
assert!(full.contains("bench-curate-corporate-actions"));
|
||||
|
||||
let short = format_usage_stderr("curate-etl");
|
||||
|
|
@ -644,10 +721,13 @@ mod tests {
|
|||
assert!(short.contains("bench-parquet-adj"));
|
||||
assert!(short.contains("bench-parquet-corporate-actions"));
|
||||
assert!(short.contains("bench-bson-eod-prices"));
|
||||
assert!(short.contains("bench-bson-qm-actions"));
|
||||
assert!(short.contains("bench-bson-stream"));
|
||||
assert!(short.contains("bench-curate-bars"));
|
||||
assert!(short.contains("bench-curate-shorts"));
|
||||
assert!(short.contains("bench-curate-events"));
|
||||
assert!(short.contains("bench-curate-fx"));
|
||||
assert!(short.contains("bench-curate-adj"));
|
||||
assert!(short.contains("bench-curate-corporate-actions"));
|
||||
}
|
||||
|
||||
|
|
@ -719,6 +799,22 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-curate-fx", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_curate_adj_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-adj"])),
|
||||
Ok(CliAction::BenchCurateAdj(DEFAULT_CURATE_ADJ_BENCH_EVENTS))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-curate-adj", "100000"])),
|
||||
Ok(CliAction::BenchCurateAdj(100_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-curate-adj", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_curate_corporate_actions_args() {
|
||||
assert_eq!(
|
||||
|
|
|
|||
1944
tools/curate-etl/src/curate_adj.rs
Normal file
1944
tools/curate-etl/src/curate_adj.rs
Normal file
File diff suppressed because it is too large
Load diff
2312
tools/curate-etl/src/curate_adj_tests.rs
Normal file
2312
tools/curate-etl/src/curate_adj_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -4,6 +4,8 @@ pub mod adj;
|
|||
pub mod bars;
|
||||
pub mod bench;
|
||||
pub mod bson_eod_prices;
|
||||
pub mod bson_qm_actions;
|
||||
pub mod bson_stream;
|
||||
pub mod cli;
|
||||
pub mod corporate_actions;
|
||||
pub mod events;
|
||||
|
|
@ -32,6 +34,18 @@ pub use bson_eod_prices::{
|
|||
decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs,
|
||||
BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar,
|
||||
};
|
||||
pub use bson_qm_actions::{
|
||||
decode_qm_dividend_buffer, decode_qm_dividend_bytes, decode_qm_dividend_doc,
|
||||
decode_qm_split_buffer, decode_qm_split_bytes, decode_qm_split_doc, BsonQmActionDecodeStats,
|
||||
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_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, BsonStreamError,
|
||||
BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES,
|
||||
DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||
};
|
||||
pub use corporate_actions::{
|
||||
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionRow,
|
||||
CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent,
|
||||
|
|
@ -122,6 +136,15 @@ pub use curate_fx::{
|
|||
FX_1D_MICROS_PER_DAY, FX_1D_TS_OFFSET_MICROS_FROM_DAY_START,
|
||||
};
|
||||
|
||||
pub mod curate_adj;
|
||||
pub use curate_adj::{
|
||||
adj_factors_for_bar, curate_adj_factors, curate_adj_factors_as_of,
|
||||
curate_and_write_adj_factors, curate_and_write_adj_factors_as_of, read_adj_factors_dataset,
|
||||
read_adj_factors_dataset_as_of, AdjFactorsSnapshot, AdjPointInTimeFence, AdjSnapshotKind,
|
||||
CurateAdjError, CurateAdjFactorsOutput, CurateAdjFactorsStats, CurateAdjFactorsWriteReport,
|
||||
CurateAdjReadError, CurateAdjWriteError, ADJ_SNAPSHOT_FORMAT_VERSION,
|
||||
};
|
||||
|
||||
pub mod curate_corporate_actions;
|
||||
pub use curate_corporate_actions::{
|
||||
curate_and_write_corporate_actions, curate_corporate_actions, CurateCorporateActionsError,
|
||||
|
|
|
|||
|
|
@ -5,12 +5,13 @@ use std::process::ExitCode;
|
|||
|
||||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark,
|
||||
run_corporate_actions_benchmark, run_curate_bars_benchmark,
|
||||
run_curate_corporate_actions_benchmark, run_curate_events_benchmark, run_curate_fx_benchmark,
|
||||
run_curate_shorts_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,
|
||||
run_bson_qm_actions_benchmark, run_bson_stream_benchmark, run_corporate_actions_benchmark,
|
||||
run_curate_adj_benchmark, run_curate_bars_benchmark, run_curate_corporate_actions_benchmark,
|
||||
run_curate_events_benchmark, run_curate_fx_benchmark, run_curate_shorts_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,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
|
||||
|
|
@ -504,6 +505,82 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchBsonQmActions(rows)) => {
|
||||
let report = run_bson_qm_actions_benchmark(rows);
|
||||
println!("curate-etl bench-bson-qm-actions");
|
||||
println!(
|
||||
" input: rows={} splits={} dividends={} bytes={}",
|
||||
report.rows, report.split_rows, report.dividend_rows, report.bytes
|
||||
);
|
||||
println!(
|
||||
" splits: decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})",
|
||||
report.split_stats.decoded,
|
||||
report.split_stats.split_noop_ratio_one,
|
||||
report.split_stats.rejected_total(),
|
||||
report.split_stats.rejected_missing_field,
|
||||
report.split_stats.rejected_empty_field,
|
||||
report.split_stats.rejected_wrong_type,
|
||||
report.split_stats.rejected_malformed_date,
|
||||
report.split_stats.rejected_invalid_number,
|
||||
report.split_stats.rejected_corrupt_document
|
||||
);
|
||||
println!(
|
||||
" dividends: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})",
|
||||
report.dividend_stats.decoded,
|
||||
report.dividend_stats.rejected_total(),
|
||||
report.dividend_stats.rejected_missing_field,
|
||||
report.dividend_stats.rejected_empty_field,
|
||||
report.dividend_stats.rejected_wrong_type,
|
||||
report.dividend_stats.rejected_malformed_date,
|
||||
report.dividend_stats.rejected_invalid_number,
|
||||
report.dividend_stats.rejected_corrupt_document
|
||||
);
|
||||
println!(
|
||||
" perf: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s latency={:.2} ns/doc checksum=0x{:016x}",
|
||||
report.elapsed_ms,
|
||||
report.docs_per_sec,
|
||||
report.mb_per_sec,
|
||||
report.ns_per_doc,
|
||||
report.checksum
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchBsonStream(rows)) => {
|
||||
let report = match run_bson_stream_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: bson-stream benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
println!("curate-etl bench-bson-stream");
|
||||
println!(" input: rows={} bytes={}", report.rows, report.bytes);
|
||||
println!(
|
||||
" decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={}) checksum=0x{:016x}",
|
||||
report.stats.decoded,
|
||||
report.stats.rejected_total(),
|
||||
report.stats.rejected_missing_field,
|
||||
report.stats.rejected_empty_field,
|
||||
report.stats.rejected_wrong_type,
|
||||
report.stats.rejected_malformed_date,
|
||||
report.stats.rejected_invalid_number,
|
||||
report.stats.rejected_corrupt_document,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" buffer: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MiB/s",
|
||||
report.buffer_elapsed_ms, report.buffer_rows_per_sec, report.buffer_mib_per_sec
|
||||
);
|
||||
println!(
|
||||
" stream: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MiB/s ratio={:.3}x peak_buffer_capacity={} bytes",
|
||||
report.stream_elapsed_ms,
|
||||
report.stream_rows_per_sec,
|
||||
report.stream_mib_per_sec,
|
||||
report.stream_to_buffer_ratio,
|
||||
report.peak_buffer_capacity
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateBars(rows)) => {
|
||||
let report = match run_curate_bars_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
@ -759,6 +836,67 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateAdj(events)) => {
|
||||
let report = match run_curate_adj_benchmark(events) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-adj benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.events > 0 {
|
||||
(report.rows_out as f64 / report.events as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-adj");
|
||||
println!(
|
||||
" input: events={} splits={} dividends={} keys={}",
|
||||
report.events, report.splits_in, report.dividends_in, report.key_count
|
||||
);
|
||||
println!(
|
||||
" builder: rows_out={} keys_out={} split_noops={} zero_div={} missing_prev_close={} currency_mismatch={} not_below_prev_close={}",
|
||||
report.stats.builder.rows_out,
|
||||
report.stats.builder.keys_out,
|
||||
report.stats.builder.split_noops_dropped,
|
||||
report.stats.builder.dividend_zero_cash_dropped,
|
||||
report.stats.builder.dividends_missing_prev_close,
|
||||
report.stats.builder.dividends_currency_mismatch,
|
||||
report.stats.builder.dividends_not_below_prev_close
|
||||
);
|
||||
println!(
|
||||
" stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum=0x{:016x}",
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out,
|
||||
report.stage_elapsed_ms,
|
||||
report.stage_events_per_sec,
|
||||
report.stage_ns_per_event,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s",
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows,
|
||||
report.parquet_elapsed_ms,
|
||||
report.parquet_rows_per_sec
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} events/s",
|
||||
report.total_elapsed_ms, report.total_events_per_sec
|
||||
);
|
||||
println!(
|
||||
" curate: splits_unmapped={} divs_unmapped={} splits_coll_collapsed={} divs_coll_collapsed={} coll_collapsed={}",
|
||||
report.stats.splits_dropped_unmapped,
|
||||
report.stats.dividends_dropped_unmapped,
|
||||
report.stats.splits_collision_collapsed,
|
||||
report.stats.dividends_collision_collapsed,
|
||||
report.stats.listing_collision_collapsed
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateCorporateActions(events)) => {
|
||||
let report = match run_curate_corporate_actions_benchmark(events) {
|
||||
Ok(report) => report,
|
||||
|
|
|
|||
205
tools/curate-etl/tests/bson_qm_actions_contract.rs
Normal file
205
tools/curate-etl/tests/bson_qm_actions_contract.rs
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
//! Public-API integration contract test for `qmSplits` and `qmDividends` raw BSON decoders (`M1.2w`).
|
||||
|
||||
use bson::raw::{cstr, RawBsonRef, RawDocumentBuf};
|
||||
use bson::DateTime;
|
||||
use curate_etl::{
|
||||
build_corporate_actions, curate_adj_factors, decode_qm_dividend_buffer,
|
||||
decode_qm_dividend_bytes, decode_qm_dividend_doc, decode_qm_split_buffer,
|
||||
decode_qm_split_bytes, decode_qm_split_doc, ymd_to_epoch_days, BsonQmActionError,
|
||||
CorporateActionKind, KnownAtSource, ProviderMappingRow, ProviderMappingTable, SplitTable,
|
||||
FIELD_DATE, FIELD_DECLARED, FIELD_DIVIDEND_CASH, FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE,
|
||||
FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE,
|
||||
};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_field_constants_and_single_doc_decoders_match_contract() {
|
||||
assert_eq!(FIELD_QM_SEARCH_CODE, "qmSearchCode");
|
||||
assert_eq!(FIELD_DATE, "date");
|
||||
assert_eq!(FIELD_DECLARED, "declared");
|
||||
assert_eq!(FIELD_SPLIT_RATIO, "splitratio");
|
||||
assert_eq!(FIELD_USD_FX_RATE, "usdFxRate");
|
||||
assert_eq!(FIELD_DIVIDEND_CASH, "amount");
|
||||
assert_eq!(FIELD_DIVIDEND_CURRENCY, "currency");
|
||||
|
||||
let mut split_doc = RawDocumentBuf::new();
|
||||
split_doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
split_doc.append(cstr!("date"), "2024-06-10");
|
||||
split_doc.append(cstr!("declared"), "2024-05-22");
|
||||
split_doc.append(cstr!("splitratio"), 10_i32);
|
||||
split_doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
|
||||
let split = decode_qm_split_doc(&split_doc).unwrap();
|
||||
assert_eq!(decode_qm_split_bytes(split_doc.as_bytes()).unwrap(), split);
|
||||
assert_eq!(split.qm_search_code, "NVDA");
|
||||
assert_eq!(split.ex_date, day(2024, 6, 10));
|
||||
assert_eq!(split.ratio, 10.0);
|
||||
assert_eq!(split.declared_date, Some(day(2024, 5, 22)));
|
||||
|
||||
let mut div_doc = RawDocumentBuf::new();
|
||||
div_doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
div_doc.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(day(2024, 11, 15)) * 86_400_000),
|
||||
);
|
||||
div_doc.append(cstr!("declared"), RawBsonRef::Null);
|
||||
div_doc.append(cstr!("amount"), 1.42_f64);
|
||||
div_doc.append(cstr!("currency"), "CAD");
|
||||
div_doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
|
||||
let div = decode_qm_dividend_doc(&div_doc).unwrap();
|
||||
assert_eq!(decode_qm_dividend_bytes(div_doc.as_bytes()).unwrap(), div);
|
||||
assert_eq!(div.qm_search_code, "RY:CA");
|
||||
assert_eq!(div.ex_date, day(2024, 11, 15));
|
||||
assert_eq!(div.cash, 1.42);
|
||||
assert_eq!(div.currency, "CAD");
|
||||
assert_eq!(div.declared_date, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_buffer_decoders_reconcile_and_feed_all_downstream_builders() {
|
||||
let mut split_buf = Vec::new();
|
||||
|
||||
let mut s_nvda = RawDocumentBuf::new();
|
||||
s_nvda.append(cstr!("qmSearchCode"), "NVDA");
|
||||
s_nvda.append(cstr!("date"), "2024-06-10");
|
||||
s_nvda.append(cstr!("declared"), "2024-05-22");
|
||||
s_nvda.append(cstr!("splitratio"), 10.0_f64);
|
||||
split_buf.extend_from_slice(s_nvda.as_bytes());
|
||||
|
||||
let mut s_noop = RawDocumentBuf::new();
|
||||
s_noop.append(cstr!("qmSearchCode"), "NVDA");
|
||||
s_noop.append(cstr!("date"), "2024-07-01");
|
||||
s_noop.append(cstr!("splitratio"), 1_i64);
|
||||
split_buf.extend_from_slice(s_noop.as_bytes());
|
||||
|
||||
let mut s_bad = RawDocumentBuf::new();
|
||||
s_bad.append(cstr!("qmSearchCode"), "NVDA");
|
||||
s_bad.append(cstr!("date"), "2024-07-02");
|
||||
s_bad.append(cstr!("splitratio"), -3.0_f64);
|
||||
split_buf.extend_from_slice(s_bad.as_bytes());
|
||||
|
||||
let mut div_buf = Vec::new();
|
||||
|
||||
let mut d_ry = RawDocumentBuf::new();
|
||||
d_ry.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_ry.append(cstr!("date"), "2024-11-15");
|
||||
d_ry.append(cstr!("declared"), "2024-10-30");
|
||||
d_ry.append(cstr!("amount"), 1.42_f64);
|
||||
d_ry.append(cstr!("currency"), "CAD");
|
||||
d_ry.append(cstr!("usdFxRate"), 1_i32);
|
||||
div_buf.extend_from_slice(d_ry.as_bytes());
|
||||
|
||||
let mut d_bad = RawDocumentBuf::new();
|
||||
d_bad.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_bad.append(cstr!("date"), "2023-02-29");
|
||||
d_bad.append(cstr!("amount"), 1.0_f64);
|
||||
d_bad.append(cstr!("currency"), "CAD");
|
||||
div_buf.extend_from_slice(d_bad.as_bytes());
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "NVDA".to_string(),
|
||||
listing_id: 101,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "RY:CA".to_string(),
|
||||
listing_id: 303,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let mut split_events = Vec::new();
|
||||
let mut split_actions = Vec::new();
|
||||
let mut split_errs = Vec::new();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| {
|
||||
split_events.push((s.qm_search_code.to_owned(), s.to_split_event()));
|
||||
if let Some(pair) =
|
||||
s.try_into_split_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
split_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| split_errs.push(err),
|
||||
);
|
||||
|
||||
assert_eq!(split_stats.docs_in, 3);
|
||||
assert_eq!(split_stats.decoded, 2);
|
||||
assert_eq!(split_stats.split_noop_ratio_one, 1);
|
||||
assert_eq!(split_stats.rejected_invalid_number, 1);
|
||||
assert_eq!(
|
||||
split_stats.decoded + split_stats.rejected_total(),
|
||||
split_stats.docs_in
|
||||
);
|
||||
assert!(matches!(
|
||||
split_errs.as_slice(),
|
||||
[BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
..
|
||||
}]
|
||||
));
|
||||
|
||||
let mut div_events = Vec::new();
|
||||
let mut div_actions = Vec::new();
|
||||
let mut div_errs = Vec::new();
|
||||
let div_stats = decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| {
|
||||
div_events.push((
|
||||
d.qm_search_code.to_owned(),
|
||||
d.to_dividend_event(Some(142.0), Some("CAD".to_string())),
|
||||
));
|
||||
if let Some(pair) =
|
||||
d.try_into_dividend_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
div_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| div_errs.push(err),
|
||||
);
|
||||
|
||||
assert_eq!(div_stats.docs_in, 2);
|
||||
assert_eq!(div_stats.decoded, 1);
|
||||
assert_eq!(div_stats.rejected_malformed_date, 1);
|
||||
assert_eq!(
|
||||
div_stats.decoded + div_stats.rejected_total(),
|
||||
div_stats.docs_in
|
||||
);
|
||||
assert!(matches!(
|
||||
div_errs.as_slice(),
|
||||
[BsonQmActionError::MalformedDate { field: FIELD_DATE }]
|
||||
));
|
||||
|
||||
// Feed SplitTable.
|
||||
let split_table = SplitTable::from_events(split_events.iter().cloned()).unwrap();
|
||||
assert_eq!(split_table.cum_factor_after("NVDA", day(2024, 6, 7)), 10.0);
|
||||
|
||||
// Feed curate_adj_factors.
|
||||
let adj = curate_adj_factors(&mapping, "qm", split_events, div_events).unwrap();
|
||||
assert_eq!(adj.rows.len(), 2);
|
||||
assert_eq!(adj.stats.builder.split_noops_dropped, 1);
|
||||
assert_eq!(adj.rows[0].listing_id, 101);
|
||||
assert_eq!(adj.rows[0].split_factor, 10.0);
|
||||
assert_eq!(adj.rows[1].listing_id, 303);
|
||||
assert_eq!(adj.rows[1].div_cash, 1.42);
|
||||
assert_eq!(adj.rows[1].div_currency.as_deref(), Some("CAD"));
|
||||
|
||||
// Feed build_corporate_actions.
|
||||
let ca = build_corporate_actions(split_actions, div_actions, std::iter::empty()).unwrap();
|
||||
assert_eq!(ca.rows.len(), 2);
|
||||
assert_eq!(ca.rows[0].kind, CorporateActionKind::Split);
|
||||
assert_eq!(ca.rows[0].known_at_source, KnownAtSource::DeclaredDate);
|
||||
assert_eq!(ca.rows[1].kind, CorporateActionKind::Dividend);
|
||||
assert_eq!(ca.rows[1].known_at_source, KnownAtSource::DeclaredDate);
|
||||
}
|
||||
520
tools/curate-etl/tests/bson_qm_actions_qa_contract.rs
Normal file
520
tools/curate-etl/tests/bson_qm_actions_qa_contract.rs
Normal file
|
|
@ -0,0 +1,520 @@
|
|||
//! QA contract tests for the public `qmSplits` / `qmDividends` raw BSON decoders (T-107 / M1.2w).
|
||||
//!
|
||||
//! Covers gaps left by `src/bson_qm_actions_tests.rs` and `tests/bson_qm_actions_contract.rs`,
|
||||
//! using only the public API:
|
||||
//! - zero-copy: `qm_search_code` / `currency` borrow from the input buffer;
|
||||
//! - field-order independence, case-sensitive keys, nested look-alike keys ignored;
|
||||
//! - `usdFxRate` / unknown fields with corrupt payloads are skipped without decoding, while the
|
||||
//! same corruption inside a known field is a typed `CorruptBson` naming that field;
|
||||
//! - `DateTime` day boundaries (last ms of a day, -1 ms before epoch);
|
||||
//! - `split_noop_ratio_one` counts exactly `1.0`, not near-one ratios;
|
||||
//! - error callbacks receive the exact byte offset of the rejected document; empty buffer,
|
||||
//! truncated tail after good docs, `i32::MAX` declared length;
|
||||
//! - seeded byte-mutation fuzz for both collections: never panics, always reconciles, and every
|
||||
//! streamed row equals the single-document decode of the same bytes;
|
||||
//! - benchmark guard: synthetic docs actually decode (rejections stay near the injected ~0.5%),
|
||||
//! so a field-constant change cannot silently turn the benchmark into a rejection-path timing;
|
||||
//! - `bench-bson-qm-actions` binary: identical checksum across two runs, invalid args exit 1.
|
||||
|
||||
use std::process::{Command, Output};
|
||||
|
||||
use bson::raw::{cstr, RawBsonRef, RawDocumentBuf};
|
||||
use bson::DateTime;
|
||||
use curate_etl::bench::run_bson_qm_actions_benchmark;
|
||||
use curate_etl::{
|
||||
decode_qm_dividend_buffer, decode_qm_dividend_bytes, decode_qm_dividend_doc,
|
||||
decode_qm_split_buffer, decode_qm_split_bytes, decode_qm_split_doc, iter_raw_bson_docs,
|
||||
ymd_to_epoch_days, BsonQmActionError, RawQmDividend, RawQmSplit, FIELD_DIVIDEND_CASH,
|
||||
FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO,
|
||||
};
|
||||
|
||||
const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
fn split_doc(code: &str, date: &str, ratio: f64) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("_id"), "ignored");
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
doc
|
||||
}
|
||||
|
||||
fn dividend_doc(code: &str, date: &str, cash: f64, currency: &str) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("_id"), "ignored");
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("declared"), "2024-05-01");
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), currency);
|
||||
doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
doc
|
||||
}
|
||||
|
||||
fn ptr_within(s: &str, buf: &[u8]) -> bool {
|
||||
let range = buf.as_ptr_range();
|
||||
let p = s.as_ptr();
|
||||
range.contains(&p) && (p as usize + s.len()) <= range.end as usize
|
||||
}
|
||||
|
||||
/// Overwrites the first occurrence of `needle` in `bytes` with `replacement` (same length).
|
||||
fn patch(bytes: &mut [u8], needle: &[u8], replacement: &[u8]) {
|
||||
assert_eq!(needle.len(), replacement.len());
|
||||
let pos = bytes
|
||||
.windows(needle.len())
|
||||
.position(|w| w == needle)
|
||||
.expect("needle present");
|
||||
bytes[pos..pos + needle.len()].copy_from_slice(replacement);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_strings_borrow_directly_from_the_input_buffer() {
|
||||
let s = split_doc("NVDA", "2024-06-10", 10.0);
|
||||
let split = decode_qm_split_bytes(s.as_bytes()).unwrap();
|
||||
assert!(ptr_within(split.qm_search_code, s.as_bytes()));
|
||||
|
||||
let d = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD");
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(d.as_bytes());
|
||||
let mut seen = Vec::new();
|
||||
decode_qm_dividend_buffer(&buf, |div| seen.push(div), |_, e| panic!("{e}"));
|
||||
assert_eq!(seen.len(), 1);
|
||||
assert!(ptr_within(seen[0].qm_search_code, &buf));
|
||||
assert!(ptr_within(seen[0].currency, &buf));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_order_is_irrelevant_keys_are_case_sensitive_and_nested_lookalikes_are_ignored() {
|
||||
// Reverse field order decodes identically.
|
||||
let mut rev = RawDocumentBuf::new();
|
||||
rev.append(cstr!("usdFxRate"), 1.0_f64);
|
||||
rev.append(cstr!("currency"), "CAD");
|
||||
rev.append(cstr!("amount"), 1.42_f64);
|
||||
rev.append(cstr!("declared"), "2024-05-01");
|
||||
rev.append(cstr!("date"), "2024-11-15");
|
||||
rev.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
let fwd = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD");
|
||||
assert_eq!(
|
||||
decode_qm_dividend_doc(&rev).unwrap(),
|
||||
decode_qm_dividend_doc(&fwd).unwrap()
|
||||
);
|
||||
|
||||
// Differently-cased keys are unknown fields, so the required field is missing.
|
||||
let mut cased = RawDocumentBuf::new();
|
||||
cased.append(cstr!("QmSearchCode"), "NVDA");
|
||||
cased.append(cstr!("date"), "2024-06-10");
|
||||
cased.append(cstr!("splitratio"), 10.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_split_doc(&cased).unwrap_err(),
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
let mut cased_ratio = RawDocumentBuf::new();
|
||||
cased_ratio.append(cstr!("qmSearchCode"), "NVDA");
|
||||
cased_ratio.append(cstr!("date"), "2024-06-10");
|
||||
cased_ratio.append(cstr!("splitRatio"), 10.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_split_doc(&cased_ratio).unwrap_err(),
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO
|
||||
}
|
||||
);
|
||||
|
||||
// A nested sub-document carrying look-alike keys must neither satisfy nor poison the decode.
|
||||
let mut nested = RawDocumentBuf::new();
|
||||
nested.append(cstr!("splitratio"), -99.0_f64);
|
||||
nested.append(cstr!("amount"), "bad");
|
||||
nested.append(cstr!("currency"), 7_i32);
|
||||
nested.append(cstr!("date"), "not-a-date");
|
||||
let mut outer = split_doc("NVDA", "2024-06-10", 10.0);
|
||||
outer.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref()));
|
||||
let split = decode_qm_split_doc(&outer).unwrap();
|
||||
assert_eq!(split.ratio, 10.0);
|
||||
|
||||
let mut outer_div = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD");
|
||||
outer_div.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref()));
|
||||
let div = decode_qm_dividend_doc(&outer_div).unwrap();
|
||||
assert_eq!((div.cash, div.currency), (1.42, "CAD"));
|
||||
|
||||
let mut only_nested = RawDocumentBuf::new();
|
||||
only_nested.append(cstr!("qmSearchCode"), "NVDA");
|
||||
only_nested.append(cstr!("date"), "2024-06-10");
|
||||
only_nested.append(cstr!("raw"), RawBsonRef::Document(nested.as_ref()));
|
||||
assert_eq!(
|
||||
decode_qm_split_doc(&only_nested).unwrap_err(),
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_payload_in_ignored_field_is_skipped_but_in_known_field_names_that_field() {
|
||||
// Unknown field / `usdFxRate` with invalid UTF-8 string bytes: framing is valid, payload is
|
||||
// never decoded.
|
||||
let mut d = dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD");
|
||||
d.append(cstr!("zzExtra"), "XYZW");
|
||||
let mut bytes = d.as_bytes().to_vec();
|
||||
patch(&mut bytes, b"XYZW", &[0xFF, 0xFE, 0xFD, 0xFC]);
|
||||
let div = decode_qm_dividend_bytes(&bytes).unwrap();
|
||||
assert_eq!(div.currency, "CAD");
|
||||
|
||||
let mut s = split_doc("NVDA", "2024-06-10", 10.0);
|
||||
s.append(cstr!("usdFxRate"), "QQQQ");
|
||||
let mut bytes = s.as_bytes().to_vec();
|
||||
patch(&mut bytes, b"QQQQ", &[0xC3, 0x28, 0xA0, 0xA1]);
|
||||
assert_eq!(decode_qm_split_bytes(&bytes).unwrap().ratio, 10.0);
|
||||
|
||||
// Same corruption inside `currency` is a typed CorruptBson naming the field (no panic).
|
||||
let d = dividend_doc("RY:CA", "2024-11-15", 1.42, "QQQ");
|
||||
let mut bytes = d.as_bytes().to_vec();
|
||||
patch(&mut bytes, b"QQQ", &[0xFF, 0xFE, 0xFD]);
|
||||
match decode_qm_dividend_bytes(&bytes).unwrap_err() {
|
||||
BsonQmActionError::CorruptBson { offset, detail } => {
|
||||
assert_eq!(offset, 0);
|
||||
assert!(detail.contains(FIELD_DIVIDEND_CURRENCY), "{detail}");
|
||||
}
|
||||
other => panic!("expected CorruptBson, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn datetime_dates_floor_to_utc_day_at_boundaries() {
|
||||
let cases = [
|
||||
(-1_i64, -1_i32),
|
||||
(0, 0),
|
||||
(-MILLIS_PER_DAY, -1),
|
||||
(-MILLIS_PER_DAY - 1, -2),
|
||||
(
|
||||
i64::from(day(2024, 6, 10)) * MILLIS_PER_DAY + MILLIS_PER_DAY - 1,
|
||||
day(2024, 6, 10),
|
||||
),
|
||||
(
|
||||
i64::from(day(2024, 6, 11)) * MILLIS_PER_DAY,
|
||||
day(2024, 6, 11),
|
||||
),
|
||||
];
|
||||
for (ms, expected) in cases {
|
||||
let mut s = RawDocumentBuf::new();
|
||||
s.append(cstr!("qmSearchCode"), "IBM");
|
||||
s.append(cstr!("date"), DateTime::from_millis(ms));
|
||||
s.append(cstr!("declared"), DateTime::from_millis(ms));
|
||||
s.append(cstr!("splitratio"), 2_i64);
|
||||
let split = decode_qm_split_doc(&s).unwrap();
|
||||
assert_eq!(split.ex_date, expected, "ms={ms}");
|
||||
assert_eq!(split.declared_date, Some(expected), "ms={ms}");
|
||||
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("qmSearchCode"), "IBM");
|
||||
d.append(cstr!("date"), DateTime::from_millis(ms));
|
||||
d.append(cstr!("amount"), 1_i32);
|
||||
d.append(cstr!("currency"), "USD");
|
||||
assert_eq!(
|
||||
decode_qm_dividend_doc(&d).unwrap().ex_date,
|
||||
expected,
|
||||
"ms={ms}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noop_counter_counts_only_exact_ratio_one() {
|
||||
let mut buf = Vec::new();
|
||||
for ratio in [1.0, 1.000_000_000_1, 0.999_999_999_9, 1.0, 2.0] {
|
||||
buf.extend_from_slice(split_doc("X", "2024-03-15", ratio).as_bytes());
|
||||
}
|
||||
let mut n = 0;
|
||||
let stats = decode_qm_split_buffer(&buf, |_| n += 1, |_, e| panic!("{e}"));
|
||||
assert_eq!(n, 5);
|
||||
assert_eq!(stats.decoded, 5);
|
||||
assert_eq!(stats.split_noop_ratio_one, 2);
|
||||
assert_eq!(stats.rejected_total(), 0);
|
||||
|
||||
// Dividends never touch the split no-op counter.
|
||||
let d = dividend_doc("X", "2024-03-15", 1.0, "USD");
|
||||
let stats = decode_qm_dividend_buffer(d.as_bytes(), |_| {}, |_, e| panic!("{e}"));
|
||||
assert_eq!(stats.split_noop_ratio_one, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_callbacks_report_exact_offsets_and_framing_failures_stop_cleanly() {
|
||||
// Empty buffer: nothing in, nothing out.
|
||||
let stats = decode_qm_split_buffer(&[], |_| panic!(), |_, _| panic!());
|
||||
assert_eq!(stats, Default::default());
|
||||
let stats = decode_qm_dividend_buffer(&[], |_| panic!(), |_, _| panic!());
|
||||
assert_eq!(stats, Default::default());
|
||||
|
||||
let good = dividend_doc("A", "2024-06-10", 0.5, "USD");
|
||||
let bad_cash = dividend_doc("B", "2024-06-10", -0.5, "USD");
|
||||
let bad_date = dividend_doc("C", "2024-13-01", 0.5, "USD");
|
||||
let mut buf = Vec::new();
|
||||
let mut expected_err_offsets = Vec::new();
|
||||
buf.extend_from_slice(good.as_bytes());
|
||||
expected_err_offsets.push(buf.len());
|
||||
buf.extend_from_slice(bad_cash.as_bytes());
|
||||
expected_err_offsets.push(buf.len());
|
||||
buf.extend_from_slice(bad_date.as_bytes());
|
||||
buf.extend_from_slice(good.as_bytes());
|
||||
// Truncated tail: declares a full doc but only half is present.
|
||||
expected_err_offsets.push(buf.len());
|
||||
let tail_start = buf.len();
|
||||
buf.extend_from_slice(&good.as_bytes()[..good.as_bytes().len() / 2]);
|
||||
|
||||
let mut errs = Vec::new();
|
||||
let mut codes = Vec::new();
|
||||
let stats = decode_qm_dividend_buffer(
|
||||
&buf,
|
||||
|d: RawQmDividend<'_>| codes.push(d.qm_search_code),
|
||||
|off, e| errs.push((off, e)),
|
||||
);
|
||||
assert_eq!(codes, vec!["A", "A"]);
|
||||
assert_eq!(
|
||||
errs.iter().map(|(o, _)| *o).collect::<Vec<_>>(),
|
||||
expected_err_offsets
|
||||
);
|
||||
assert!(matches!(
|
||||
errs[0].1,
|
||||
BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert!(matches!(
|
||||
errs[2].1,
|
||||
BsonQmActionError::TruncatedDocument {
|
||||
offset,
|
||||
declared_len: Some(_),
|
||||
..
|
||||
} if offset == tail_start
|
||||
));
|
||||
assert_eq!(stats.docs_in, 5);
|
||||
assert_eq!(stats.decoded, 2);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
|
||||
// i32::MAX declared length after a good split doc terminates without panicking.
|
||||
let mut buf = split_doc("S", "2024-06-10", 2.0).as_bytes().to_vec();
|
||||
let bad_at = buf.len();
|
||||
buf.extend_from_slice(&i32::MAX.to_le_bytes());
|
||||
buf.extend_from_slice(&[0u8; 8]);
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_qm_split_buffer(&buf, |_| {}, |off, e| errs.push((off, e)));
|
||||
assert_eq!(stats.docs_in, 2);
|
||||
assert_eq!(stats.decoded, 1);
|
||||
assert_eq!(errs.len(), 1);
|
||||
assert_eq!(errs[0].0, bad_at);
|
||||
assert!(matches!(
|
||||
errs[0].1,
|
||||
BsonQmActionError::TruncatedDocument { .. }
|
||||
));
|
||||
|
||||
// Single-doc decoder: trailing bytes are rejected as a length mismatch, not silently ignored.
|
||||
let mut trailing = split_doc("S", "2024-06-10", 2.0).as_bytes().to_vec();
|
||||
trailing.push(0);
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&trailing).unwrap_err(),
|
||||
BsonQmActionError::CorruptDocumentLength { .. }
|
||||
));
|
||||
}
|
||||
|
||||
/// `std`-only SplitMix64 so the fuzz corpus is fixed across runs.
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
}
|
||||
|
||||
fn mutate(rng: &mut SplitMix64, base: &[u8]) -> Vec<u8> {
|
||||
let mut buf = base.to_vec();
|
||||
let flips = 1 + (rng.next() % 4) as usize;
|
||||
for _ in 0..flips {
|
||||
let pos = (rng.next() as usize) % buf.len();
|
||||
buf[pos] = rng.next() as u8;
|
||||
}
|
||||
if rng.next() % 4 == 0 {
|
||||
let cut = (rng.next() as usize) % buf.len();
|
||||
buf.truncate(cut);
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
fn framed_slices(buf: &[u8]) -> Vec<(usize, usize)> {
|
||||
let mut out = Vec::new();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
if let Ok((off, doc)) = item {
|
||||
out.push((off, doc.as_bytes().len()));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_byte_mutation_fuzz_never_panics_and_always_reconciles_for_both_collections() {
|
||||
let mut split_base = Vec::new();
|
||||
let mut div_base = Vec::new();
|
||||
for i in 0..8 {
|
||||
let code = format!("Q{i}:CA");
|
||||
split_base.extend_from_slice(split_doc(&code, "2024-06-07", 1.0 + i as f64).as_bytes());
|
||||
div_base
|
||||
.extend_from_slice(dividend_doc(&code, "2024-06-07", 0.1 * i as f64, "CAD").as_bytes());
|
||||
}
|
||||
|
||||
let split_key = |s: &RawQmSplit<'_>| {
|
||||
(
|
||||
s.qm_search_code.to_string(),
|
||||
s.ex_date,
|
||||
s.ratio.to_bits(),
|
||||
s.declared_date,
|
||||
)
|
||||
};
|
||||
let div_key = |d: &RawQmDividend<'_>| {
|
||||
(
|
||||
d.qm_search_code.to_string(),
|
||||
d.ex_date,
|
||||
d.cash.to_bits(),
|
||||
d.currency.to_string(),
|
||||
d.declared_date,
|
||||
)
|
||||
};
|
||||
|
||||
let mut rng = SplitMix64(0x0B50_7E57_0A11_0107);
|
||||
for _ in 0..2_000 {
|
||||
let buf = mutate(&mut rng, &split_base);
|
||||
let mut rows = Vec::new();
|
||||
let stats = decode_qm_split_buffer(&buf, |s| rows.push(s), |_, _| {});
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
assert_eq!(stats.decoded, rows.len());
|
||||
assert_eq!(
|
||||
stats.split_noop_ratio_one,
|
||||
rows.iter().filter(|s| s.ratio == 1.0).count()
|
||||
);
|
||||
let expected: Vec<_> = framed_slices(&buf)
|
||||
.into_iter()
|
||||
.filter_map(|(o, l)| decode_qm_split_bytes(&buf[o..o + l]).ok())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
rows.iter().map(split_key).collect::<Vec<_>>(),
|
||||
expected.iter().map(split_key).collect::<Vec<_>>()
|
||||
);
|
||||
for s in &rows {
|
||||
assert!(s.ratio.is_finite() && s.ratio > 0.0);
|
||||
assert!(!s.qm_search_code.trim().is_empty());
|
||||
}
|
||||
|
||||
let buf = mutate(&mut rng, &div_base);
|
||||
let mut rows = Vec::new();
|
||||
let stats = decode_qm_dividend_buffer(&buf, |d| rows.push(d), |_, _| {});
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
assert_eq!(stats.decoded, rows.len());
|
||||
assert_eq!(stats.split_noop_ratio_one, 0);
|
||||
let expected: Vec<_> = framed_slices(&buf)
|
||||
.into_iter()
|
||||
.filter_map(|(o, l)| decode_qm_dividend_bytes(&buf[o..o + l]).ok())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
rows.iter().map(div_key).collect::<Vec<_>>(),
|
||||
expected.iter().map(div_key).collect::<Vec<_>>()
|
||||
);
|
||||
for d in &rows {
|
||||
assert!(d.cash.is_finite() && d.cash >= 0.0 && !d.cash.is_sign_negative());
|
||||
assert!(!d.currency.trim().is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn benchmark_corpus_mostly_decodes_so_it_times_the_happy_path() {
|
||||
let report = run_bson_qm_actions_benchmark(20_000);
|
||||
let s = report.split_stats;
|
||||
let d = report.dividend_stats;
|
||||
assert_eq!(s.docs_in + d.docs_in, 20_000);
|
||||
// Injected errors are ~0.5% per collection; allow generous headroom but fail if a renamed
|
||||
// field constant makes the corpus reject en masse.
|
||||
assert!(
|
||||
s.rejected_total() * 50 < s.docs_in,
|
||||
"split rejections too high: {s:?}"
|
||||
);
|
||||
assert!(
|
||||
d.rejected_total() * 50 < d.docs_in,
|
||||
"dividend rejections too high: {d:?}"
|
||||
);
|
||||
assert_eq!(s.rejected_corrupt_document + d.rejected_corrupt_document, 0);
|
||||
}
|
||||
|
||||
fn run_bin(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("spawn curate-etl binary")
|
||||
}
|
||||
|
||||
fn stable_output(out: &Output) -> String {
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let checksum = text
|
||||
.split_whitespace()
|
||||
.find(|t| t.starts_with("checksum=0x"))
|
||||
.unwrap_or_else(|| panic!("no checksum in output: {text}"));
|
||||
let stats: Vec<&str> = text
|
||||
.lines()
|
||||
.map(str::trim_start)
|
||||
.filter(|l| {
|
||||
l.starts_with("input:") || l.starts_with("splits:") || l.starts_with("dividends:")
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(stats.len(), 3, "missing stats lines: {text}");
|
||||
format!("{checksum} {}", stats.join(" | "))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_binary_prints_identical_checksum_and_stats_across_runs() {
|
||||
let a = run_bin(&["bench-bson-qm-actions", "5000"]);
|
||||
let b = run_bin(&["bench-bson-qm-actions", "5000"]);
|
||||
assert!(a.status.success(), "{}", String::from_utf8_lossy(&a.stderr));
|
||||
assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr));
|
||||
|
||||
let text = String::from_utf8_lossy(&a.stdout);
|
||||
assert!(text.contains("rows=5000"), "{text}");
|
||||
for needle in [
|
||||
"elapsed=",
|
||||
"docs/s",
|
||||
"MB/s",
|
||||
"noop_ratio_one=",
|
||||
"checksum=0x",
|
||||
] {
|
||||
assert!(text.contains(needle), "missing {needle}: {text}");
|
||||
}
|
||||
assert_eq!(stable_output(&a), stable_output(&b));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_binary_rejects_invalid_row_counts_and_is_listed_in_usage() {
|
||||
for args in [
|
||||
&["bench-bson-qm-actions", "0"][..],
|
||||
&["bench-bson-qm-actions", "-5"][..],
|
||||
&["bench-bson-qm-actions", "abc"][..],
|
||||
&["bench-bson-qm-actions", "10", "20"][..],
|
||||
] {
|
||||
let out = run_bin(args);
|
||||
assert_eq!(out.status.code(), Some(1), "{args:?}");
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(err.contains("error:"), "{args:?}: {err}");
|
||||
assert!(out.stdout.is_empty(), "{args:?} wrote to stdout");
|
||||
}
|
||||
|
||||
let out = run_bin(&["--help"]);
|
||||
assert!(out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("bench-bson-qm-actions"));
|
||||
}
|
||||
273
tools/curate-etl/tests/bson_stream_qa_contract.rs
Normal file
273
tools/curate-etl/tests/bson_stream_qa_contract.rs
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
//! QA contract tests for the public `bson_stream` API (T-109 / M1.2y).
|
||||
//!
|
||||
//! Covers gaps left by `src/bson_stream_tests.rs`, using only the public crate API:
|
||||
//! - seeded byte-mutation fuzz: for every mutated `eodPrices` stream the streamed decode never
|
||||
//! panics, yields exactly the buffer decoder's rows and per-document errors in order, and a
|
||||
//! buffer framing error maps to a stream `Err` at the same absolute offset;
|
||||
//! - `RawBsonChunkReader::new` (default options) frames a multi-document stream end to end;
|
||||
//! - `decode_*_chunks` resumed on a reader that already failed returns the sticky error at once;
|
||||
//! - `BsonStreamError` `Display` names the offset and `source()` exposes the original I/O error;
|
||||
//! - `bench-bson-stream` binary: completes on a small row count with a ratio and peak buffer
|
||||
//! line, identical checksum across two runs, invalid args exit non-zero.
|
||||
|
||||
use std::error::Error as _;
|
||||
use std::io::{self, Cursor, Read};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
use bson::raw::{cstr, RawDocumentBuf};
|
||||
use curate_etl::{
|
||||
decode_eod_price_buffer, decode_eod_price_chunks, decode_eod_price_stream,
|
||||
decode_qm_split_chunks, BsonEodPriceError, BsonStreamError, BsonStreamOptions,
|
||||
RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES,
|
||||
};
|
||||
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next_u64(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reader returning seeded pseudo-random short reads of 1..=97 bytes.
|
||||
struct JitterReader<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
rng: SplitMix64,
|
||||
}
|
||||
|
||||
impl Read for JitterReader<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let remaining = self.data.len() - self.pos;
|
||||
if remaining == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let step = (self.rng.next_u64() % 97) as usize + 1;
|
||||
let take = remaining.min(step).min(buf.len());
|
||||
buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]);
|
||||
self.pos += take;
|
||||
Ok(take)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reader that yields its data once and then fails every subsequent read.
|
||||
struct FailAfterData {
|
||||
data: Vec<u8>,
|
||||
pos: usize,
|
||||
reads_after_fail: usize,
|
||||
}
|
||||
|
||||
impl Read for FailAfterData {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if self.pos == self.data.len() {
|
||||
self.reads_after_fail += 1;
|
||||
return Err(io::Error::new(io::ErrorKind::ConnectionReset, "cursor dropped"));
|
||||
}
|
||||
let take = (self.data.len() - self.pos).min(buf.len());
|
||||
buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]);
|
||||
self.pos += take;
|
||||
Ok(take)
|
||||
}
|
||||
}
|
||||
|
||||
fn eod_doc(code: &str, day: u32, close: f64) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("eodSearchCode"), code);
|
||||
doc.append(cstr!("date"), format!("2024-06-{day:02}"));
|
||||
doc.append(cstr!("open"), close - 0.5);
|
||||
doc.append(cstr!("high"), close + 1.0);
|
||||
doc.append(cstr!("low"), close - 1.0);
|
||||
doc.append(cstr!("close"), close);
|
||||
doc.append(cstr!("volume"), 1_000_i64 + day as i64);
|
||||
doc.append(cstr!("exchange"), "TSX");
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
fn eod_fixture(count: usize) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for i in 0..count {
|
||||
out.extend_from_slice(&eod_doc(&format!("Q{i:03}.TO"), 1 + (i % 28) as u32, 10.0 + i as f64));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
type Row = (String, i32, u64, u64);
|
||||
|
||||
fn buffer_decode(bytes: &[u8]) -> (Vec<Row>, Vec<(u64, String)>) {
|
||||
let mut rows = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
decode_eod_price_buffer(
|
||||
bytes,
|
||||
|b| rows.push((b.eod_search_code.to_owned(), b.session_date, b.close.to_bits(), b.adj_volume.to_bits())),
|
||||
|off, e| errs.push((off as u64, format!("{e:?}"))),
|
||||
);
|
||||
(rows, errs)
|
||||
}
|
||||
|
||||
fn is_framing_error(debug: &str) -> bool {
|
||||
debug.starts_with("CorruptDocumentLength") || debug.starts_with("TruncatedDocument")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_mutation_fuzz_stream_matches_buffer_rows_errors_and_framing_offset() {
|
||||
let clean = eod_fixture(24);
|
||||
let mut rng = SplitMix64(0x5EED_B50E);
|
||||
let mut framing_cases = 0usize;
|
||||
let mut ok_cases = 0usize;
|
||||
|
||||
for case in 0..400u64 {
|
||||
let mut bytes = clean.clone();
|
||||
let flips = 1 + (rng.next_u64() % 4) as usize;
|
||||
for _ in 0..flips {
|
||||
let idx = (rng.next_u64() as usize) % bytes.len();
|
||||
bytes[idx] = rng.next_u64() as u8;
|
||||
}
|
||||
if rng.next_u64() % 5 == 0 {
|
||||
let cut = (rng.next_u64() as usize) % bytes.len();
|
||||
bytes.truncate(cut);
|
||||
}
|
||||
|
||||
let (exp_rows, mut exp_errs) = buffer_decode(&bytes);
|
||||
let exp_framing = match exp_errs.last() {
|
||||
Some((off, dbg)) if is_framing_error(dbg) => {
|
||||
let off = *off;
|
||||
exp_errs.pop();
|
||||
Some(off)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let cap = [1usize, 4, 37, 256, 4096][(case % 5) as usize];
|
||||
let mut rows = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
let result = decode_eod_price_stream(
|
||||
JitterReader { data: &bytes, pos: 0, rng: SplitMix64(case) },
|
||||
BsonStreamOptions { chunk_capacity_bytes: cap, max_doc_bytes: 1 << 20 },
|
||||
|b| rows.push((b.eod_search_code.to_owned(), b.session_date, b.close.to_bits(), b.adj_volume.to_bits())),
|
||||
|off, e: BsonEodPriceError| errs.push((off, format!("{e:?}"))),
|
||||
);
|
||||
|
||||
assert_eq!(rows, exp_rows, "case={case} cap={cap}: rows diverge");
|
||||
assert_eq!(errs, exp_errs, "case={case} cap={cap}: per-doc errors diverge");
|
||||
match (exp_framing, result) {
|
||||
(None, Ok(stats)) => {
|
||||
ok_cases += 1;
|
||||
assert_eq!(stats.decoded, exp_rows.len(), "case={case}");
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in, "case={case}");
|
||||
}
|
||||
(Some(off), Err(BsonStreamError::CorruptDocumentLength { offset, .. }))
|
||||
| (Some(off), Err(BsonStreamError::TruncatedDocument { offset, .. })) => {
|
||||
framing_cases += 1;
|
||||
assert_eq!(offset, off, "case={case} cap={cap}: framing offset");
|
||||
}
|
||||
(exp, got) => panic!("case={case} cap={cap}: expected framing={exp:?}, got {got:?}"),
|
||||
}
|
||||
}
|
||||
// The sweep must exercise both outcomes, or it proves nothing.
|
||||
assert!(framing_cases >= 20, "framing_cases={framing_cases}");
|
||||
assert!(ok_cases >= 20, "ok_cases={ok_cases}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_reader_frames_whole_stream_with_default_capacity() {
|
||||
let input = eod_fixture(50);
|
||||
let mut reader = RawBsonChunkReader::new(JitterReader { data: &input, pos: 0, rng: SplitMix64(7) });
|
||||
let mut joined = Vec::new();
|
||||
while let Some(chunk) = reader.next_chunk().expect("valid stream") {
|
||||
assert_eq!(chunk.start_offset, joined.len() as u64);
|
||||
joined.extend_from_slice(chunk.bytes);
|
||||
}
|
||||
assert_eq!(joined, input);
|
||||
assert_eq!(reader.docs_framed(), 50);
|
||||
assert_eq!(reader.bytes_read(), input.len() as u64);
|
||||
assert_eq!(reader.buffer_capacity(), DEFAULT_CHUNK_CAPACITY_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_helpers_on_failed_reader_return_sticky_error_without_rereading() {
|
||||
let input = eod_fixture(3);
|
||||
let len = input.len() as u64;
|
||||
let mut reader = RawBsonChunkReader::with_options(
|
||||
FailAfterData { data: input, pos: 0, reads_after_fail: 0 },
|
||||
BsonStreamOptions { chunk_capacity_bytes: 64, max_doc_bytes: 4096 },
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut bars = 0usize;
|
||||
let err = decode_eod_price_chunks(&mut reader, |_| bars += 1, |_, _| panic!("no per-doc errors"))
|
||||
.expect_err("I/O failure must surface");
|
||||
assert_eq!(bars, 3, "all complete docs delivered before the I/O error");
|
||||
let BsonStreamError::Io { offset, ref source } = err else { panic!("expected Io, got {err:?}") };
|
||||
assert_eq!(offset, len);
|
||||
assert_eq!(source.kind(), io::ErrorKind::ConnectionReset);
|
||||
|
||||
// A different helper resumed on the same failed reader must fail immediately.
|
||||
let again = decode_qm_split_chunks(&mut reader, |_| panic!("no rows"), |_, _| panic!("no errors"))
|
||||
.expect_err("sticky error");
|
||||
assert!(matches!(again, BsonStreamError::Io { offset, .. } if offset == len));
|
||||
assert_eq!(reader.into_inner().reads_after_fail, 1, "source read exactly once after data");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_display_names_offset_and_io_source_is_exposed() {
|
||||
let mut bytes = eod_doc("A.TO", 3, 5.0);
|
||||
let first_len = bytes.len();
|
||||
bytes.extend_from_slice(&2_i32.to_le_bytes());
|
||||
let err = decode_eod_price_stream(Cursor::new(bytes), BsonStreamOptions::default(), |_| {}, |_, _| {})
|
||||
.expect_err("corrupt length");
|
||||
assert!(err.source().is_none());
|
||||
let text = err.to_string();
|
||||
assert!(text.contains(&format!("offset {first_len}")), "{text}");
|
||||
assert!(text.contains("length 2"), "{text}");
|
||||
|
||||
let io_err = decode_eod_price_stream(
|
||||
FailAfterData { data: Vec::new(), pos: 0, reads_after_fail: 0 },
|
||||
BsonStreamOptions::default(),
|
||||
|_| {},
|
||||
|_, _| {},
|
||||
)
|
||||
.expect_err("io");
|
||||
let src = io_err.source().expect("Io exposes source");
|
||||
assert!(src.to_string().contains("cursor dropped"), "{src}");
|
||||
assert!(io_err.to_string().contains("offset 0"), "{io_err}");
|
||||
|
||||
assert!(BsonStreamError::InvalidChunkCapacity.to_string().contains("chunk_capacity_bytes"));
|
||||
assert!(BsonStreamError::InvalidMaxDocBytes.to_string().contains("max_doc_bytes"));
|
||||
}
|
||||
|
||||
fn run_bin(args: &[&str]) -> Output {
|
||||
Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("spawn curate-etl binary")
|
||||
}
|
||||
|
||||
fn checksum_of(out: &Output) -> String {
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
text.split_whitespace()
|
||||
.find(|t| t.starts_with("checksum=0x"))
|
||||
.unwrap_or_else(|| panic!("no checksum in output: {text}"))
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_bson_stream_binary_is_deterministic_and_rejects_bad_args() {
|
||||
let a = run_bin(&["bench-bson-stream", "5000"]);
|
||||
let b = run_bin(&["bench-bson-stream", "5000"]);
|
||||
assert!(a.status.success(), "stderr: {}", String::from_utf8_lossy(&a.stderr));
|
||||
assert!(b.status.success());
|
||||
assert_eq!(checksum_of(&a), checksum_of(&b));
|
||||
let text = String::from_utf8_lossy(&a.stdout).to_lowercase();
|
||||
assert!(text.contains("rows=5000"), "{text}");
|
||||
assert!(text.contains("ratio"), "{text}");
|
||||
assert!(text.contains("peak_buffer_capacity"), "{text}");
|
||||
|
||||
for bad in [&["bench-bson-stream", "abc"][..], &["bench-bson-stream", "1", "2"][..]] {
|
||||
let out = run_bin(bad);
|
||||
assert!(!out.status.success(), "args {bad:?} must fail");
|
||||
}
|
||||
}
|
||||
418
tools/curate-etl/tests/curate_adj_qa_contract.rs
Normal file
418
tools/curate-etl/tests/curate_adj_qa_contract.rs
Normal file
|
|
@ -0,0 +1,418 @@
|
|||
//! QA contract tests for the public `adj_factors` curation stage (T-106 / M1.2v).
|
||||
//!
|
||||
//! Complements the in-crate `curate_adj_tests.rs` with checks against independent references
|
||||
//! built only from the public API:
|
||||
//! - seeded differential test: per-bar split factors across ticker renames, ticker reuse and
|
||||
//! unmapped gaps equal a naive per-listing product of later split ratios;
|
||||
//! - fenced publish → separate reopen equals the naive reference over only the events whose
|
||||
//! conservative `16:00 ET` known_at is `<= as_of`, and every reopened row honours the fence;
|
||||
//! - re-publishing a smaller fenced snapshot over a larger retrospective one leaves exactly one
|
||||
//! `part.parquet` whose footer carries the `stock_bot.adj_factors.*` keys and contract schema;
|
||||
//! - `bench-curate-adj` binary run: checksum/bytes/rows pinned to the README values, temp dir
|
||||
//! cleaned.
|
||||
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::fs::{self, File};
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use curate_etl::{
|
||||
adj_factors_for_bar, adj_factors_parquet_schema, curate_adj_factors,
|
||||
curate_and_write_adj_factors, curate_and_write_adj_factors_as_of, et_session_close_utc_micros,
|
||||
read_adj_factors_dataset, read_adj_factors_dataset_as_of, ymd_to_epoch_days,
|
||||
AdjFactorsWriteOptions, AdjPointInTimeFence, AdjSnapshotKind, CurateAdjReadError,
|
||||
DividendEvent, ProviderMappingRow, ProviderMappingTable, SplitEvent,
|
||||
};
|
||||
use parquet::file::reader::{FileReader, SerializedFileReader};
|
||||
|
||||
static SEQ: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> Self {
|
||||
let seq = SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"curate-etl-curate-adj-qa-{tag}-{}-{seq}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("create temp dir");
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n
|
||||
}
|
||||
}
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn map_row(key: &str, from: i32, to: Option<i32>, listing_id: i32) -> ProviderMappingRow {
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: key.to_string(),
|
||||
valid_from: from,
|
||||
valid_to: to,
|
||||
listing_id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Exactly representable ratios so the naive product is order-independent.
|
||||
const RATIOS: [f64; 6] = [2.0, 0.5, 4.0, 0.25, 3.0, 1.0];
|
||||
|
||||
struct Fixture {
|
||||
mapping: ProviderMappingTable,
|
||||
splits: Vec<(String, SplitEvent)>,
|
||||
/// Naive reference: listing_id -> (ex_date -> ratio) for every mapped split (incl. 1:1).
|
||||
reference: BTreeMap<i32, BTreeMap<i32, f64>>,
|
||||
min: i32,
|
||||
max: i32,
|
||||
}
|
||||
|
||||
/// Layout per listing group `g` (deterministic):
|
||||
/// - listing `3g+1`: single key `S{g}` for the whole span;
|
||||
/// - listing `3g+2`: key `OLD{g}` until 2012-12-31, renamed to `NEW{g}` from 2013-01-01;
|
||||
/// - key `RE{g}` maps to listing `3g+3` until 2015-06-30, unmapped through 2015, then to listing
|
||||
/// `100_000 + g` from 2016-01-01 (ticker reuse with a gap).
|
||||
fn seeded_fixture(seed: u64, groups: i32, events: usize) -> Fixture {
|
||||
let min = day(2000, 1, 1);
|
||||
let max = day(2025, 12, 31);
|
||||
let rename = day(2012, 12, 31);
|
||||
let reuse_old_end = day(2015, 6, 30);
|
||||
let reuse_new_start = day(2016, 1, 1);
|
||||
|
||||
let mut rows = Vec::new();
|
||||
for g in 0..groups {
|
||||
rows.push(map_row(&format!("S{g}"), min, None, 3 * g + 1));
|
||||
rows.push(map_row(&format!("OLD{g}"), min, Some(rename), 3 * g + 2));
|
||||
rows.push(map_row(&format!("NEW{g}"), rename + 1, None, 3 * g + 2));
|
||||
rows.push(map_row(
|
||||
&format!("RE{g}"),
|
||||
min,
|
||||
Some(reuse_old_end),
|
||||
3 * g + 3,
|
||||
));
|
||||
rows.push(map_row(
|
||||
&format!("RE{g}"),
|
||||
reuse_new_start,
|
||||
None,
|
||||
100_000 + g,
|
||||
));
|
||||
}
|
||||
let mapping = ProviderMappingTable::from_rows(rows).expect("valid mapping");
|
||||
|
||||
let mut rng = SplitMix64(seed);
|
||||
let mut seen: HashSet<(String, i32)> = HashSet::new();
|
||||
let mut splits = Vec::new();
|
||||
let mut reference: BTreeMap<i32, BTreeMap<i32, f64>> = BTreeMap::new();
|
||||
while splits.len() < events {
|
||||
let g = rng.below(groups as u64) as i32;
|
||||
let ex_date = min + rng.below((max - min + 1) as u64) as i32;
|
||||
let (key, listing) = match rng.below(4) {
|
||||
0 => (format!("S{g}"), Some(3 * g + 1)),
|
||||
1 if ex_date <= rename => (format!("OLD{g}"), Some(3 * g + 2)),
|
||||
1 => (format!("NEW{g}"), Some(3 * g + 2)),
|
||||
2 if ex_date <= reuse_old_end => (format!("RE{g}"), Some(3 * g + 3)),
|
||||
2 if ex_date < reuse_new_start => (format!("RE{g}"), None),
|
||||
2 => (format!("RE{g}"), Some(100_000 + g)),
|
||||
_ => (format!("UNMAPPED{g}"), None),
|
||||
};
|
||||
// One event per (key, ex_date): same-key same-day multiplication is the builder's own
|
||||
// contract and is covered in-crate.
|
||||
if !seen.insert((key.clone(), ex_date)) {
|
||||
continue;
|
||||
}
|
||||
let ratio = RATIOS[rng.below(RATIOS.len() as u64) as usize];
|
||||
if let Some(listing_id) = listing {
|
||||
reference
|
||||
.entry(listing_id)
|
||||
.or_default()
|
||||
.insert(ex_date, ratio);
|
||||
}
|
||||
splits.push((key, SplitEvent { ex_date, ratio }));
|
||||
}
|
||||
Fixture {
|
||||
mapping,
|
||||
splits,
|
||||
reference,
|
||||
min,
|
||||
max,
|
||||
}
|
||||
}
|
||||
|
||||
/// Product of every reference split ratio with `ex_date > bar_date` for `listing_id`.
|
||||
fn naive_factor(
|
||||
reference: &BTreeMap<i32, BTreeMap<i32, f64>>,
|
||||
listing_id: i32,
|
||||
bar_date: i32,
|
||||
admit: impl Fn(i32) -> bool,
|
||||
) -> f64 {
|
||||
reference.get(&listing_id).map_or(1.0, |events| {
|
||||
events
|
||||
.range(bar_date + 1..)
|
||||
.filter(|(ex, _)| admit(**ex))
|
||||
.map(|(_, r)| *r)
|
||||
.product()
|
||||
})
|
||||
}
|
||||
|
||||
const NO_DIVIDENDS: [(String, DividendEvent); 0] = [];
|
||||
|
||||
#[test]
|
||||
fn seeded_split_factors_match_naive_per_listing_reference_across_rename_reuse_and_gaps() {
|
||||
let fx = seeded_fixture(0xAD0A_115E_ED00, 40, 3_000);
|
||||
let out =
|
||||
curate_adj_factors(&fx.mapping, "qm", fx.splits.clone(), NO_DIVIDENDS).expect("curate");
|
||||
|
||||
assert_eq!(out.snapshot_kind, AdjSnapshotKind::RetrospectiveSnapshot);
|
||||
let mapped: usize = fx.reference.values().map(BTreeMap::len).sum();
|
||||
assert_eq!(out.stats.splits_in, fx.splits.len());
|
||||
assert_eq!(
|
||||
out.stats.splits_dropped_unmapped,
|
||||
fx.splits.len() - mapped,
|
||||
"unmapped count must equal events with no covering range"
|
||||
);
|
||||
assert_eq!(out.stats.splits_collision_collapsed, 0);
|
||||
assert_eq!(out.stats.builder.split_events_in, mapped);
|
||||
let noops = fx
|
||||
.reference
|
||||
.values()
|
||||
.flat_map(BTreeMap::values)
|
||||
.filter(|r| **r == 1.0)
|
||||
.count();
|
||||
assert_eq!(out.stats.builder.split_noops_dropped, noops);
|
||||
assert_eq!(out.stats.rows_out, mapped - noops);
|
||||
assert!(out.stats.splits_dropped_unmapped > 0 && noops > 0);
|
||||
|
||||
let mut rng = SplitMix64(0x0B5E_55ED);
|
||||
let listings: Vec<i32> = fx.reference.keys().copied().collect();
|
||||
for _ in 0..5_000 {
|
||||
let listing_id = listings[rng.below(listings.len() as u64) as usize];
|
||||
let bar = fx.min - 5 + rng.below((fx.max - fx.min + 10) as u64) as i32;
|
||||
let expected = naive_factor(&fx.reference, listing_id, bar, |_| true);
|
||||
let (split, _total) = adj_factors_for_bar(&out.rows, listing_id, bar);
|
||||
assert_eq!(
|
||||
split.to_bits(),
|
||||
expected.to_bits(),
|
||||
"listing {listing_id} bar {bar}: got {split}, expected {expected}"
|
||||
);
|
||||
}
|
||||
// Unknown listing never picks up another listing's chain.
|
||||
assert_eq!(adj_factors_for_bar(&out.rows, 99_999, fx.min), (1.0, 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fenced_publish_then_separate_reopen_matches_naive_filtered_reference() {
|
||||
let fx = seeded_fixture(0xFE11_CE00, 25, 2_000);
|
||||
let tmp = TempDir::new("fenced-reopen");
|
||||
// As of 2018-03-14 12:00 UTC: an ex-date of 2018-03-14 (close 20:00 UTC) is still unknown.
|
||||
let as_of = et_session_close_utc_micros(day(2018, 3, 14)).unwrap() - 8 * 3_600_000_000;
|
||||
let fence = AdjPointInTimeFence::as_of(as_of);
|
||||
|
||||
let report = curate_and_write_adj_factors_as_of(
|
||||
&tmp.0,
|
||||
&fx.mapping,
|
||||
"qm",
|
||||
fx.splits.clone(),
|
||||
NO_DIVIDENDS,
|
||||
fence,
|
||||
AdjFactorsWriteOptions {
|
||||
row_group_rows: 11,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("fenced publish");
|
||||
assert_eq!(
|
||||
report.snapshot_kind,
|
||||
AdjSnapshotKind::PointInTimeFenced(fence)
|
||||
);
|
||||
assert!(report.curate_stats.splits_dropped_fenced > 0);
|
||||
|
||||
// Separate read step: only the published artifact is consulted.
|
||||
let snap = read_adj_factors_dataset_as_of(&tmp.0, fence).expect("reopen");
|
||||
assert_eq!(
|
||||
snap.snapshot_kind,
|
||||
AdjSnapshotKind::PointInTimeFenced(fence)
|
||||
);
|
||||
assert_eq!(snap.rows.len(), report.write_stats.rows_written);
|
||||
for row in &snap.rows {
|
||||
assert!(row.known_at_micros <= as_of, "row beyond as_of: {row:?}");
|
||||
}
|
||||
for w in snap.rows.windows(2) {
|
||||
assert!((w[0].listing_id, w[0].ex_date) < (w[1].listing_id, w[1].ex_date));
|
||||
}
|
||||
|
||||
let admitted = |ex: i32| et_session_close_utc_micros(ex).unwrap() <= as_of;
|
||||
let mut rng = SplitMix64(0xA5_0F);
|
||||
let listings: Vec<i32> = fx.reference.keys().copied().collect();
|
||||
for _ in 0..3_000 {
|
||||
let listing_id = listings[rng.below(listings.len() as u64) as usize];
|
||||
let bar = fx.min + rng.below((day(2018, 3, 14) - fx.min) as u64) as i32;
|
||||
let expected = naive_factor(&fx.reference, listing_id, bar, admitted);
|
||||
let (split, _) = snap.factors_for_bar(listing_id, bar);
|
||||
assert_eq!(
|
||||
split.to_bits(),
|
||||
expected.to_bits(),
|
||||
"listing {listing_id} bar {bar} as_of {as_of}"
|
||||
);
|
||||
}
|
||||
|
||||
// A neighbouring fence one microsecond later is a different artifact and must be refused.
|
||||
let other = AdjPointInTimeFence::as_of(as_of + 1);
|
||||
assert!(matches!(
|
||||
read_adj_factors_dataset_as_of(&tmp.0, other),
|
||||
Err(CurateAdjReadError::IncompatibleFence { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smaller_fenced_republish_supersedes_larger_retrospective_snapshot_in_one_file() {
|
||||
let fx = seeded_fixture(0x5_0BE5, 30, 2_500);
|
||||
let tmp = TempDir::new("republish");
|
||||
|
||||
let retro = curate_and_write_adj_factors(
|
||||
&tmp.0,
|
||||
&fx.mapping,
|
||||
"qm",
|
||||
fx.splits.clone(),
|
||||
NO_DIVIDENDS,
|
||||
AdjFactorsWriteOptions::default(),
|
||||
)
|
||||
.expect("retrospective publish");
|
||||
let fence = AdjPointInTimeFence::as_of_with_vault_cutoff(
|
||||
et_session_close_utc_micros(day(2024, 6, 28)).unwrap(),
|
||||
et_session_close_utc_micros(day(2005, 1, 3)).unwrap(),
|
||||
);
|
||||
assert!(matches!(
|
||||
read_adj_factors_dataset_as_of(&tmp.0, fence),
|
||||
Err(CurateAdjReadError::RetrospectiveSnapshotRejected { .. })
|
||||
));
|
||||
|
||||
let fenced = curate_and_write_adj_factors_as_of(
|
||||
&tmp.0,
|
||||
&fx.mapping,
|
||||
"qm",
|
||||
fx.splits.clone(),
|
||||
NO_DIVIDENDS,
|
||||
fence,
|
||||
AdjFactorsWriteOptions::default(),
|
||||
)
|
||||
.expect("fenced publish");
|
||||
assert!(fenced.write_stats.rows_written < retro.write_stats.rows_written);
|
||||
|
||||
let names: Vec<String> = fs::read_dir(tmp.0.join("adj_factors"))
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
assert_eq!(names, vec!["part.parquet".to_string()]);
|
||||
|
||||
// Vault cutoff wins over the later as_of: every row is strictly before the vault boundary.
|
||||
let snap = read_adj_factors_dataset(&tmp.0).expect("reopen");
|
||||
assert_eq!(
|
||||
snap.snapshot_kind,
|
||||
AdjSnapshotKind::PointInTimeFenced(fence)
|
||||
);
|
||||
assert_eq!(snap.rows.len(), fenced.write_stats.rows_written);
|
||||
let vault = fence.vault_cutoff_micros.unwrap();
|
||||
assert!(snap.rows.iter().all(|r| r.known_at_micros < vault));
|
||||
|
||||
// A generic Parquet reader sees the contract schema and the bound footer keys.
|
||||
let path = tmp.0.join("adj_factors").join("part.parquet");
|
||||
let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap();
|
||||
let file_meta = reader.metadata().file_metadata();
|
||||
assert_eq!(
|
||||
file_meta.schema(),
|
||||
adj_factors_parquet_schema().unwrap().as_ref()
|
||||
);
|
||||
assert_eq!(file_meta.num_rows() as usize, snap.rows.len());
|
||||
let kv: BTreeMap<String, Option<String>> = file_meta
|
||||
.key_value_metadata()
|
||||
.expect("footer key_value_metadata")
|
||||
.iter()
|
||||
.map(|kv| (kv.key.clone(), kv.value.clone()))
|
||||
.filter(|(k, _)| k.starts_with("stock_bot.adj_factors."))
|
||||
.collect();
|
||||
let get = |k: &str| kv[&format!("stock_bot.adj_factors.{k}")].as_deref();
|
||||
assert_eq!(kv.len(), 6, "{kv:?}");
|
||||
assert_eq!(get("format_version"), Some("1"));
|
||||
assert_eq!(get("snapshot_kind"), Some("point_in_time_fenced"));
|
||||
assert_eq!(
|
||||
get("as_of_micros"),
|
||||
Some(fence.as_of_micros.unwrap().to_string().as_str())
|
||||
);
|
||||
assert_eq!(get("vault_cutoff_micros"), Some(vault.to_string().as_str()));
|
||||
assert_eq!(
|
||||
get("rows_written"),
|
||||
Some(snap.rows.len().to_string().as_str())
|
||||
);
|
||||
}
|
||||
|
||||
fn field<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
|
||||
text.split_whitespace()
|
||||
.find(|t| t.starts_with(prefix))
|
||||
.map(|t| &t[prefix.len()..])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bench_curate_adj_default_run_matches_readme_values_and_cleans_temp_dir() {
|
||||
let tmp = TempDir::new("bench-tmpdir");
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.arg("bench-curate-adj")
|
||||
.env("TMPDIR", &tmp.0)
|
||||
.output()
|
||||
.expect("run curate-etl");
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"stderr: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
|
||||
// Values recorded in tools/curate-etl/README.md (`bench-curate-adj`, default 1,000,000).
|
||||
assert_eq!(field(&stdout, "events="), Some("1000000"), "{stdout}");
|
||||
assert_eq!(field(&stdout, "splits="), Some("40221"), "{stdout}");
|
||||
assert_eq!(field(&stdout, "dividends="), Some("959779"), "{stdout}");
|
||||
assert_eq!(
|
||||
field(&stdout, "checksum="),
|
||||
Some("0x024ec73a1afe7e6b"),
|
||||
"{stdout}"
|
||||
);
|
||||
assert_eq!(field(&stdout, "bytes="), Some("11872037"), "{stdout}");
|
||||
assert_eq!(
|
||||
field(&stdout, "read_back_rows="),
|
||||
Some("946414"),
|
||||
"{stdout}"
|
||||
);
|
||||
assert_eq!(field(&stdout, "rows_out="), Some("946414"), "{stdout}");
|
||||
assert_eq!(field(&stdout, "coll_collapsed="), Some("4930"), "{stdout}");
|
||||
|
||||
let leftovers: Vec<_> = fs::read_dir(&tmp.0)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name())
|
||||
.collect();
|
||||
assert!(
|
||||
leftovers.is_empty(),
|
||||
"bench left temp entries: {leftovers:?}"
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue