T-118: M1.2ah — tools/curate-etl: wire the qmPrices.sharevolume cross-check into curate-bars-1d (zero-copy qmPrices decoder + optional --qm-prices file, re-keyed via provider_mapping) with end-to-end tests and local benchmark (no new crates, no MongoDB connection)
This commit is contained in:
parent
ae00abcee4
commit
87fad608b0
15 changed files with 2151 additions and 46 deletions
|
|
@ -313,7 +313,7 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/sto
|
|||
--te-symbol USDCAD
|
||||
```
|
||||
3. **Run `tools/curate-etl` commands (`curate-bars-1d` first, then the remaining datasets):**
|
||||
- `curate-etl curate-bars-1d` (`--eod-prices ./tmp/raw-bson/eodPrices.bson`, `--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--curate-inputs ./tmp/curate-inputs`, `--out ./tmp/curated` — writes `./tmp/curated/bars_1d/year=YYYY/part.parquet`)
|
||||
- `curate-etl curate-bars-1d` (`--eod-prices ./tmp/raw-bson/eodPrices.bson`, `--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-prices ./tmp/raw-bson/qmPrices.bson`, `--curate-inputs ./tmp/curate-inputs`, `--out ./tmp/curated` — writes `./tmp/curated/bars_1d/year=YYYY/part.parquet` and prints read-only `qmPrices.sharevolume` cross-check stats)
|
||||
- `curate-etl curate-adj-factors` (`--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-dividends ./tmp/raw-bson/qmDividends.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--bars-1d ./tmp/curated/bars_1d`, `--out ./tmp/curated`)
|
||||
- `curate-etl curate-corporate-actions` (`--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-dividends ./tmp/raw-bson/qmDividends.bson`, `--curate-inputs ./tmp/curate-inputs`, `--out ./tmp/curated`)
|
||||
- `curate-etl curate-fx-1d` (`--eod-prices ./tmp/raw-bson-fx/eodPrices.bson`, `--te-market-data ./tmp/raw-bson-fx/teMarketData.bson`, `--out ./tmp/curated`)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# `curate-etl`
|
||||
|
||||
Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, and the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command.
|
||||
Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, and the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`.
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -453,7 +453,7 @@ Rules:
|
|||
- `iter_raw_bson_docs` walks concatenated 4-byte little-endian length-prefixed BSON documents (wire / `mongodump` layout), terminating cleanly on unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) while skipping validly framed corrupt documents (`CorruptBson`).
|
||||
- `decode_eod_price_buffer` reports and skips per-document errors without aborting the stream, reconciling `BsonEodDecodeStats` with `decoded + rejected_total() == docs_in`.
|
||||
5. **Deferred out of `M1.2o`:**
|
||||
- MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, and decoders for remaining collections (`qmPrices`, `eodIntraday1M`). (`qmSplits`/`qmDividends`, `teMarketData`, `ceoShorts`, and `qmFilings`/`qmEarnings` decoders are now implemented alongside all six M1 `curate-*` file-to-Parquet commands.)
|
||||
- MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, and decoders for remaining collections (`eodIntraday1M`). (`qmSplits`/`qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, and `qmFilings`/`qmEarnings` decoders are now implemented alongside all six M1 `curate-*` file-to-Parquet commands.)
|
||||
|
||||
## `qmSplits` / `qmDividends` Raw BSON Decoders (`M1.2w`)
|
||||
|
||||
|
|
@ -1012,9 +1012,9 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0c22a1a1
|
|||
- Parquet write: `elapsed=87.57 ms`, `throughput=5647404 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=371.89 ms`, `throughput=1398252 events/s`
|
||||
|
||||
## `curate-bars-1d` Command (`M1.2z`)
|
||||
## `curate-bars-1d` Command (`M1.2z` / `M1.2ah`)
|
||||
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_bars.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, `decode_qm_split_chunks`, `ProviderMappingTable`, `SplitTable`, and `curate_and_write_bars_1d` into `<out>/bars_1d/year=YYYY/part.parquet` with zero extra crates and no database connections.
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_bars.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, `decode_qm_split_chunks`, optional `decode_qm_price_chunks` (`src/bson_qm_prices.rs`), `ProviderMappingTable`, `SplitTable`, and `curate_and_write_bars_1d` into `<out>/bars_1d/year=YYYY/part.parquet` with zero extra crates and no database connections.
|
||||
|
||||
### Invocation
|
||||
|
||||
|
|
@ -1022,6 +1022,7 @@ End-to-end file-to-Parquet CLI command (`src/run_curate_bars.rs`) wiring `RawBso
|
|||
curate-etl curate-bars-1d \
|
||||
--eod-prices <path> # concatenated raw BSON (mongodump eodPrices.bson)
|
||||
--qm-splits <path> # concatenated raw BSON (mongodump qmSplits.bson)
|
||||
[--qm-prices <path>] # optional concatenated raw BSON (qmPrices.bson) for read-only sharevolume cross-check
|
||||
--curate-inputs <dir> # exporter output dir (pins <dir>/current once before opening TSVs)
|
||||
--out <dir> # dataset root -> bars_1d/year=YYYY/part.parquet
|
||||
[--rel-tolerance <f64>] # default: 0.01
|
||||
|
|
@ -1029,7 +1030,16 @@ curate-etl curate-bars-1d \
|
|||
|
||||
Instead of `--curate-inputs <dir>`, standalone TSV files may be passed directly with `--provider-mapping <path> --listing-currencies <path>` (mutually exclusive with `--curate-inputs`). When reading from a live exporter output directory, always prefer `--curate-inputs <dir>` so `curate-bars-1d` pins `<dir>/current` once before opening either TSV and cannot mix generations across a concurrent refresh.
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid/missing/duplicate flags exit non-zero with usage on stderr. Runtime errors (missing files, truncated or oversized BSON documents, malformed TSV lines, overlapping mapping ranges, conflicting cross-key QM splits, unwritable `--out`) print a single-line stderr message naming the offending path (and 1-based line number for TSV errors), exit non-zero, and leave no partial `bars_1d` files under `--out`.
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid/missing/duplicate flags exit non-zero with usage on stderr. Runtime errors (missing files, truncated or oversized BSON documents, malformed TSV lines, overlapping mapping ranges, conflicting cross-key QM splits, unwritable `--out`) print a single-line stderr message naming the offending path (and 1-based line number for TSV errors), exit non-zero, and leave no partial `bars_1d` files under `--out`. Volume cross-check mismatches never fail the run (exit code `0`) and never modify emitted Parquet bytes.
|
||||
|
||||
### `qmPrices` Raw BSON Decoder (`src/bson_qm_prices.rs`)
|
||||
|
||||
- **Empirical field contract** (`prices.action.ts:97-109`, `bar-spans.ts:19-24`, `sample-closes.ts:300-303`, `design/DATA-CONTRACTS.md` §1):
|
||||
- `qmSearchCode`: BSON UTF-8 `String` borrowed verbatim (never trimmed; empty/whitespace-only rejected as `EmptyField`).
|
||||
- `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` validated via `parse_ymd_strict_days` (BSON `Date` lives separately in `dateTime`; non-string `date` rejected as `WrongType`, bad format/calendar strings as `MalformedDate`).
|
||||
- `sharevolume`: BSON `Double`, `Int32`, or `Int64` converted to `f64`. Numeric domain validity (negative / non-finite) is passed through to `build_bars_1d` (`qm_invalid_volume_dropped`); missing, `Null`, or non-numeric types are rejected with counted reasons.
|
||||
- All extra fields (`_id`, `dateTime`, `unadjustedopen..unadjustedclose`, nested docs/arrays) are skipped without calling `elem.value()`.
|
||||
- **Accounting invariant:** `docs_in == decoded + rejected_total()` (`rejected_missing_field + rejected_empty_field + rejected_wrong_type + rejected_malformed_date + rejected_corrupt_document`).
|
||||
|
||||
### TSV Formats (strict, headerless, `\t`-separated)
|
||||
|
||||
|
|
@ -1040,23 +1050,30 @@ Both `--flag value` and `--flag=value` forms are accepted (in the separated `--f
|
|||
- Unique positive `listing_id` per row; non-blank currency code (`"USD"` and `"CAD"` are interned).
|
||||
- Both files accept `\n` or `\r\n` line endings and at most one trailing blank line. Header rows, wrong column counts, interior blank lines, multiple trailing blank lines, interior `\r`, and invalid UTF-8 are rejected with the 1-based line number.
|
||||
|
||||
### Split Re-Keying, Early Filter & Missing-Currency Policy
|
||||
### Split Re-Keying, `qmPrices` Re-Keying, Early Filter & Missing-Currency Policy
|
||||
|
||||
1. **Split re-keying (`qmSearchCode` → `eodSearchCode`):** Each decoded `qmSplits` row with `ratio != 1.0` resolves `("qm", qmSearchCode, ex_date) -> listing_id` via `ProviderMappingTable`. Before fanning out to `"eod"` partners, mapped splits are compacted by `(listing_id, ex_date)` using the same cross-key policy as `curate_adj_factors`: single-QM-key same-day groups pass through unchanged, multi-QM-key alias groups with bitwise-identical ratios collapse to one event (`splits_collision_collapsed`), and multi-QM-key groups with conflicting ratios fail closed (`ConflictingCrossKeySplit`). Surviving events are attached to every deduplicated `"eod"` `source_id` pointing at that `listing_id` (preventing ratio squaring when one `(listing_id, eod_source_id)` spans multiple date ranges). No ticker-text guessing is performed.
|
||||
2. **Early filter & key interning:** While streaming `eodPrices`, bars whose `eodSearchCode` has no `"eod"` range in `provider_mapping` are dropped before buffering (`bars_unmapped_source_dropped`). Retained bars share interned `Arc<str>` keys rather than allocating a `String` per bar.
|
||||
3. **Missing-currency behavior:** Delegated unchanged to `curate_bars_1d` — mapped listings absent from `--listing-currencies` (or blank) are dropped into `dropped_missing_currency` without failing the run.
|
||||
2. **Date-aware `qmPrices` volume re-keying (optional `--qm-prices`):** Each decoded `qmPrices` row resolves `("qm", qmSearchCode, session_date) -> listing_id` via `ProviderMappingTable`, then fans out only to `"eod"` `source_id`s whose mapping range covers `session_date` (reusing interned `Arc<str>` EOD keys; no ticker-text guessing, so reused EOD tickers never receive volumes from another occupant). Unmapped QM keys and QM rows whose `listing_id` has no date-covering `"eod"` partner are early-filtered before buffering into `qm_unmapped_qm` and `qm_no_eod_partner`. When `--qm-prices` is omitted, no reverse range index is built and `qm_volumes` stays empty.
|
||||
3. **Early filter & key interning:** While streaming `eodPrices`, bars whose `eodSearchCode` has no `"eod"` range in `provider_mapping` are dropped before buffering (`bars_unmapped_source_dropped`). Retained bars share interned `Arc<str>` keys rather than allocating a `String` per bar.
|
||||
4. **Missing-currency behavior:** Delegated unchanged to `curate_bars_1d` — mapped listings absent from `--listing-currencies` (or blank) are dropped into `dropped_missing_currency` without failing the run.
|
||||
|
||||
### Report Counters & Conservation Invariants
|
||||
|
||||
On success, `curate-bars-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `splits_bson`, `splits`, `filter`, `builder`, `curate`, `write`, ascending `years`, and `timing`):
|
||||
On success, `curate-bars-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `splits_bson`, `splits`, `filter`, `builder`, `curate`, `write`, ascending `years`, `qm_check: qm_prices=absent` when `--qm-prices` is omitted or `qm_bson` / `qm_rekey` / `qm_check` + up to `100` `qm_mismatch` lines when supplied, and `timing`):
|
||||
|
||||
- `splits_in == splits_applied + splits_collision_collapsed + splits_unmapped_qm + splits_no_eod_partner + splits_noop_dropped + splits_bson.rejected`
|
||||
- `eod_bson.docs_framed == eod_bson.docs_in == eod_bson.decoded + eod_bson.rejected`
|
||||
- `eod_bson.decoded == write.rows_written + bars_unmapped_source_dropped + builder.(invalid_ohlc + inconsistent_ohlc + invalid_vol + dup_collapsed + dup_conflict_dropped) + curate.(dropped_unmapped + dropped_missing_currency + dropped_ts_out_of_range + listing_collision_collapsed + listing_collision_dropped)`
|
||||
- When `--qm-prices` is provided:
|
||||
- `qm_bson.docs_framed == qm_bson.docs_in == qm_bson.decoded + qm_bson.rejected`
|
||||
- `qm_rekey.qm_in == qm_rekey.qm_attached + qm_rekey.qm_unmapped_qm + qm_rekey.qm_no_eod_partner + qm_bson.rejected`
|
||||
- `qm_rekey.qm_volumes_attached == qm_check.qm_rows_in`
|
||||
- `qm_check.volume_checked + qm_check.volume_unchecked == builder.rows_out`
|
||||
- `qm_check.volume_within_tolerance + qm_check.volume_mismatched == qm_check.volume_checked`
|
||||
|
||||
### `bench-curate-bars-cmd`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson`, `qmSplits.bson`, `provider_mapping.tsv`, and `listing_currencies.tsv` (covering unmapped source keys, ticker reuse gaps, missing currencies, pre-1976 out-of-range timestamps, cross-key EOD listing aliases with both identical collapses and conflicting drops, and cross-key QM split aliases) into a temp dir, timing decode / curate / write splits separately, verifying Parquet footer row counts, and cleaning up on drop:
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson`, `qmSplits.bson`, `qmPrices.bson` (matching `Double`/`Int32`/`Int64` `sharevolume` partners, unmapped QM keys, QM keys with no EOD partner, wrong-typed `sharevolume` rejects, and exact injected >1% divergences), `provider_mapping.tsv`, and `listing_currencies.tsv` into a temp dir, timing decode / qm decode+rekey / curate / write splits separately, verifying Parquet footer row counts, and cleaning up on drop:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd [rows]
|
||||
|
|
@ -1065,23 +1082,24 @@ cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd [rows]
|
|||
Measured locally (`2026-11-29`):
|
||||
|
||||
1. **1,000,000 rows** (`cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 1000000`):
|
||||
- Input: `rows=1000000`, `eod_bytes=161690000` (154.2 MiB), `splits_docs=2040`, `splits_bytes=188080`, `keys=2000`
|
||||
- Decode: `elapsed=206.25 ms`, `throughput=4848457 rows/s`, `scan=748.50 MB/s`, `unmapped_dropped=20000`, `buffered_bars=980000`, `buffered_bytes=67161784` (`68.5 bytes/bar`)
|
||||
- Curate: `elapsed=192.34 ms`, `throughput=5095195 rows/s`, `rows_out=938023` (`93.80%` retained), `listings_out=1941`, `unmapped=595`, `missing_curr=9500`, `ts_oor=1842`, `coll_collapsed=10000`, `coll_dropped=20000`
|
||||
- Write: `elapsed=466.67 ms`, `throughput=2010036 rows/s`, `write=52.52 MB/s`, `files=36`, `row_groups=36`, `bytes=25699104`, `read_back_rows=938023`
|
||||
- Total: `elapsed=865.26 ms`, `throughput=1155723 rows/s`, `throughput_mb=178.42 MB/s`, `splits_applied=1699`, `splits_coll_collapsed=40`, `splits_unmapped_qm=101`, `splits_no_eod_partner=100`, `splits_noop=100`
|
||||
- Input: `rows=1000000`, `eod_bytes=161690000` (154.2 MiB), `splits_docs=2040`, `splits_bytes=188080`, `qm_docs=222624`, `qm_bytes=20374624` (19.4 MiB), `keys=2000`
|
||||
- Decode (all inputs): `elapsed=234.52 ms`, `throughput=4264112 rows/s`, `scan=741.14 MB/s`, `unmapped_dropped=20000`, `buffered_bars=980000`, `buffered_bytes=67161784` (`68.5 bytes/bar`)
|
||||
- QM decode + rekey: `elapsed=31.49 ms`, `throughput=7070243 docs/s`, `scan=617.10 MB/s`, `attached=220124`, `unmapped=1000`, `no_eod_partner=1000`, `rejected=500`, `checked=220124`, `within_tol=217922`, `mismatched=2202 (injected=2202)`, `unchecked=759836`, `samples=100`
|
||||
- Curate: `elapsed=209.14 ms`, `throughput=4685933 rows/s`, `rows_out=938023` (`93.80%` retained), `listings_out=1941`, `unmapped=595`, `missing_curr=9500`, `ts_oor=1842`, `coll_collapsed=10000`, `coll_dropped=20000`
|
||||
- Write: `elapsed=462.20 ms`, `throughput=2029479 rows/s`, `write=53.03 MB/s`, `files=36`, `row_groups=36`, `bytes=25699104`, `read_back_rows=938023`
|
||||
- Total: `elapsed=905.85 ms`, `throughput=1103934 rows/s`, `throughput_mb=191.87 MB/s`, `splits_applied=1699`, `splits_coll_collapsed=40`, `splits_unmapped_qm=101`, `splits_no_eod_partner=100`, `splits_noop=100`
|
||||
2. **5,000,000 rows** (`cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 5000000`):
|
||||
- Input: `rows=5000000`, `eod_bytes=808449920` (771.0 MiB), `splits_docs=4080`, `splits_bytes=376160`, `keys=6000`
|
||||
- Decode: `elapsed=958.74 ms`, `throughput=5215176 rows/s`, `scan=804.55 MB/s`, `unmapped_dropped=99960`, `buffered_bars=4900040`, `buffered_bytes=537029672` (`109.6 bytes/bar`)
|
||||
- Curate: `elapsed=1029.67 ms`, `throughput=4758857 rows/s`, `rows_out=4691865` (`93.84%` retained), `listings_out=5822`, `unmapped=2879`, `missing_curr=48328`, `ts_oor=9132`, `coll_collapsed=49206`, `coll_dropped=98256`
|
||||
- Write: `elapsed=1318.31 ms`, `throughput=3558995 rows/s`, `write=74.91 MB/s`, `files=36`, `row_groups=36`, `bytes=103552480`, `read_back_rows=4691865`
|
||||
- Total: `elapsed=3306.72 ms`, `throughput=1512073 rows/s`, `throughput_mb=233.27 MB/s`, `splits_applied=3399`, `splits_coll_collapsed=80`, `splits_unmapped_qm=201`, `splits_no_eod_partner=200`, `splits_noop=200`
|
||||
- Input: `rows=5000000`, `eod_bytes=808449920` (771.0 MiB), `splits_docs=4080`, `splits_bytes=376160`, `qm_docs=1114364`, `qm_bytes=101988156` (97.3 MiB), `keys=6000`
|
||||
- Decode (all inputs): `elapsed=1130.24 ms`, `throughput=4423839 rows/s`, `scan=768.53 MB/s`, `unmapped_dropped=99960`, `buffered_bars=4900040`, `buffered_bytes=537029672` (`109.6 bytes/bar`)
|
||||
- QM decode + rekey: `elapsed=149.87 ms`, `throughput=7435584 docs/s`, `scan=648.99 MB/s`, `attached=1101864`, `unmapped=5000`, `no_eod_partner=5000`, `rejected=2500`, `checked=1101864`, `within_tol=1090845`, `mismatched=11019 (injected=11019)`, `unchecked=3797802`, `samples=100`
|
||||
- Curate: `elapsed=1096.29 ms`, `throughput=4469640 rows/s`, `rows_out=4691865` (`93.84%` retained), `listings_out=5822`, `unmapped=2879`, `missing_curr=48328`, `ts_oor=9132`, `coll_collapsed=49206`, `coll_dropped=98256`
|
||||
- Write: `elapsed=1248.49 ms`, `throughput=3758021 rows/s`, `write=79.10 MB/s`, `files=36`, `row_groups=36`, `bytes=103552480`, `read_back_rows=4691865`
|
||||
- Total: `elapsed=3475.03 ms`, `throughput=1438838 rows/s`, `throughput_mb=249.96 MB/s`, `splits_applied=3399`, `splits_coll_collapsed=80`, `splits_unmapped_qm=201`, `splits_no_eod_partner=200`, `splits_noop=200`
|
||||
|
||||
### Known Limits
|
||||
|
||||
- **Full in-RAM buffering of mapped bars:** `curate-bars-1d` buffers every mapped bar in `Vec<EodDailyBar<Arc<str>>>` before sorting (`64 B/bar` struct size; measured `68.5–109.6 B/bar` including `Vec` geometric growth headroom, plus ~200 B/row peak during `curate_bars_1d` while `built.rows` and `Bars1dParquetRow` briefly coexist). For the US+CA subset (~100–150M rows of the 846M-row `eodPrices` collection), this implies roughly **20–30 GiB peak RAM** (viable on a 64 GiB workstation, tight on 32 GiB); running all 846M global rows unsharded would exceed 160 GiB.
|
||||
- **Full in-RAM buffering of mapped bars (and optional QM volumes):** `curate-bars-1d` buffers every mapped bar in `Vec<EodDailyBar<Arc<str>>>` before sorting (`64 B/bar` struct size; measured `68.5–109.6 B/bar` including `Vec` geometric growth headroom, plus ~200 B/row peak during `curate_bars_1d` while `built.rows` and `Bars1dParquetRow` briefly coexist), plus `32 B/row` for mapped `QmRawVolume<Arc<str>>` when `--qm-prices` is supplied (~1.6 GiB worst case if all 51.5M QM rows map). For the US+CA subset (~100–150M rows of the 846M-row `eodPrices` collection), this implies roughly **20–30 GiB peak RAM** (viable on a 64 GiB workstation, tight on 32 GiB); running all 846M global rows unsharded would exceed 160 GiB.
|
||||
- **No `rayon` sharding or direct MongoDB cursors yet:** single-threaded file-to-file execution only; hash/key-sharded `rayon` streaming and direct MongoDB cursors are deferred to a follow-up.
|
||||
- **`qmPrices` volume cross-check not wired yet:** `qm_volumes` is passed as empty because `qmPrices` does not yet have its own raw BSON decoder.
|
||||
- **Ticker-reuse split keying caveat:** because `curate_bars_1d` takes `SplitTable<K>` keyed by `eodSearchCode` rather than `listing_id`, attaching a split to every `"eod"` `source_id` pointing at a `listing_id` means a later split on a reused `eodSearchCode` could affect an earlier listing that previously held that same `eodSearchCode`.
|
||||
- **Partition-level replacement on `--out` reuse:** `write_bars_1d_dataset` atomically replaces only the `bars_1d/year=YYYY/part.parquet` partitions emitted by the current run. Reusing an existing `--out` directory for a narrower year range leaves older year partitions intact on disk; use a fresh `--out` directory for a complete rebuild.
|
||||
|
||||
|
|
|
|||
|
|
@ -4944,6 +4944,8 @@ pub struct CurateBarsCmdBenchReport {
|
|||
pub eod_bytes_read: u64,
|
||||
pub splits_docs_framed: u64,
|
||||
pub splits_bytes_read: u64,
|
||||
pub qm_docs_framed: u64,
|
||||
pub qm_bytes_read: u64,
|
||||
pub bars_unmapped_source_dropped: usize,
|
||||
pub buffered_bars: usize,
|
||||
pub buffered_bar_bytes: usize,
|
||||
|
|
@ -4957,6 +4959,9 @@ pub struct CurateBarsCmdBenchReport {
|
|||
pub decode_elapsed_ms: f64,
|
||||
pub decode_rows_per_sec: f64,
|
||||
pub input_mb_per_sec: f64,
|
||||
pub qm_decode_rekey_elapsed_ms: f64,
|
||||
pub qm_decode_rekey_docs_per_sec: f64,
|
||||
pub qm_input_mb_per_sec: f64,
|
||||
pub curate_elapsed_ms: f64,
|
||||
pub curate_rows_per_sec: f64,
|
||||
pub write_elapsed_ms: f64,
|
||||
|
|
@ -4968,6 +4973,10 @@ pub struct CurateBarsCmdBenchReport {
|
|||
pub split_rekey: crate::run_curate_bars::SplitRekeyStats,
|
||||
pub eod_decode: BsonEodDecodeStats,
|
||||
pub splits_decode: BsonQmActionDecodeStats,
|
||||
pub qm_prices_decode: crate::bson_qm_prices::BsonQmPriceDecodeStats,
|
||||
pub qm_rekey: crate::run_curate_bars::QmVolumeRekeyStats,
|
||||
pub injected_mismatches: usize,
|
||||
pub mismatch_samples_out: usize,
|
||||
pub curate_stats: crate::curate_bars::CurateBars1dStats,
|
||||
}
|
||||
|
||||
|
|
@ -5038,6 +5047,7 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
|
||||
let eod_path = temp.path.join("eodPrices.bson");
|
||||
let splits_path = temp.path.join("qmSplits.bson");
|
||||
let qm_prices_path = temp.path.join("qmPrices.bson");
|
||||
let mapping_path = temp.path.join("provider_mapping.tsv");
|
||||
let currencies_path = temp.path.join("listing_currencies.tsv");
|
||||
let out_dir = temp.path.join("out");
|
||||
|
|
@ -5194,7 +5204,12 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
})?;
|
||||
}
|
||||
|
||||
// 2. Stream-write `qmSplits.bson`.
|
||||
// 2. Stream-write `qmSplits.bson` and track applied split events per key index so synthetic
|
||||
// `qmPrices.sharevolume` partners match un-adjusted EOD volumes except on exact injected
|
||||
// >1% divergences.
|
||||
let gap_start = ymd_to_epoch_days(2016, 7, 1).expect("valid gap start");
|
||||
let gap_end = ymd_to_epoch_days(2016, 12, 31).expect("valid gap end");
|
||||
let mut ref_split_events: Vec<(usize, SplitEvent)> = Vec::new();
|
||||
{
|
||||
let mut splits_w = BufWriter::with_capacity(
|
||||
256 * 1024,
|
||||
|
|
@ -5210,6 +5225,7 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
for i in 0..split_count {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
let date_idx = (rng.next_u64() as usize) % main_days.len();
|
||||
let ex_date = main_days[date_idx];
|
||||
let date_str = &main_strs[date_idx];
|
||||
let mut oid_bytes = [0u8; 12];
|
||||
oid_bytes[4..12].copy_from_slice(&(i as u64).to_be_bytes());
|
||||
|
|
@ -5245,6 +5261,11 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
doc.append(cstr!("date"), date_str.as_str());
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
|
||||
let in_reuse_gap = k % 50 == 1 && (gap_start..=gap_end).contains(&ex_date);
|
||||
if !in_reuse_gap {
|
||||
ref_split_events.push((k, SplitEvent { ex_date, ratio }));
|
||||
}
|
||||
|
||||
// Emit an identical split under the QM alias key `k + 2` to exercise
|
||||
// `splits_collision_collapsed` without introducing ratio conflicts.
|
||||
if k % 50 == 0 && k + 2 < mapped_keys {
|
||||
|
|
@ -5282,8 +5303,16 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
source,
|
||||
})?;
|
||||
}
|
||||
let ref_splits = SplitTable::<usize>::from_events(ref_split_events).map_err(|source| {
|
||||
CurateBarsCmdBenchError::Run(crate::run_curate_bars::RunCurateBarsError::SplitTable {
|
||||
path: splits_path.clone(),
|
||||
source,
|
||||
})
|
||||
})?;
|
||||
|
||||
// 3. Stream-write `eodPrices.bson` directly to disk (never buffered in a Vec<u8>).
|
||||
// 3. Stream-write `eodPrices.bson` and `qmPrices.bson` directly to disk.
|
||||
let mut injected_mismatches = 0usize;
|
||||
let mut qm_matched_emitted = 0usize;
|
||||
{
|
||||
let mut eod_w = BufWriter::with_capacity(
|
||||
512 * 1024,
|
||||
|
|
@ -5292,6 +5321,13 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
source,
|
||||
})?,
|
||||
);
|
||||
let mut qm_w = BufWriter::with_capacity(
|
||||
512 * 1024,
|
||||
File::create(&qm_prices_path).map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: qm_prices_path.clone(),
|
||||
source,
|
||||
})?,
|
||||
);
|
||||
let mapped_keys = key_count - (key_count / 50).max(1);
|
||||
let eod_codes: Vec<String> = (0..key_count)
|
||||
.map(|k| {
|
||||
|
|
@ -5303,6 +5339,12 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
}
|
||||
})
|
||||
.collect();
|
||||
let qm_codes: Vec<String> = (0..mapped_keys)
|
||||
.map(|k| {
|
||||
let suffix = if k % 4 == 0 { "TO" } else { "US" };
|
||||
format!("QM{k:05}:{suffix}")
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Per-key coprime-stride cursors over `main_days` so 5M rows stay unique per key.
|
||||
// Alias keys (`k % 50 == 2`) share the starting cursor of their base key (`k - 2`)
|
||||
|
|
@ -5398,19 +5440,107 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
path: eod_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
// Emit a synthetic `qmPrices` partner for 25% of unique non-alias, non-gap mapped bars.
|
||||
let is_clean_unique_main_bar = k < mapped_keys
|
||||
&& k % 50 != 0
|
||||
&& k % 50 != 1
|
||||
&& k % 50 != 2
|
||||
&& roll >= 22;
|
||||
if is_clean_unique_main_bar && i % 4 == 0 {
|
||||
qm_matched_emitted += 1;
|
||||
let factor = ref_splits.cum_factor_after(&k, epoch_day);
|
||||
let raw_vol = crate::split::unadjust_volume(volume_i64 as f64, factor);
|
||||
let mut qdoc = RawDocumentBuf::new();
|
||||
let mut qoid = [0u8; 12];
|
||||
qoid[0] = 2;
|
||||
qoid[4..12].copy_from_slice(&(i as u64).to_be_bytes());
|
||||
qdoc.append(cstr!("_id"), ObjectId::from_bytes(qoid));
|
||||
qdoc.append(cstr!("qmSearchCode"), qm_codes[k].as_str());
|
||||
qdoc.append(cstr!("date"), date_str.as_str());
|
||||
if qm_matched_emitted % 100 == 1 {
|
||||
// Exact injected >1% divergence (~4.76% relative diff).
|
||||
qdoc.append(cstr!("sharevolume"), raw_vol * 1.05);
|
||||
injected_mismatches += 1;
|
||||
} else {
|
||||
let rounded = raw_vol.round();
|
||||
let safe_int = rounded >= 1.0
|
||||
&& (rounded - raw_vol).abs() / raw_vol <= 0.005;
|
||||
if i % 12 == 4 && safe_int && rounded <= i32::MAX as f64 {
|
||||
qdoc.append(cstr!("sharevolume"), rounded as i32);
|
||||
} else if i % 12 == 8 && safe_int && rounded <= i64::MAX as f64 {
|
||||
qdoc.append(cstr!("sharevolume"), rounded as i64);
|
||||
} else {
|
||||
qdoc.append(cstr!("sharevolume"), raw_vol);
|
||||
}
|
||||
}
|
||||
qm_w.write_all(qdoc.as_bytes())
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: qm_prices_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
// Emit deterministic unmapped, no-EOD-partner, and wrong-typed `qmPrices` docs when rows > 0.
|
||||
if rows > 0 {
|
||||
let unmapped_n = (rows / 1_000).max(1);
|
||||
let no_partner_n = (rows / 1_000).max(1);
|
||||
let wrong_type_n = (rows / 2_000).max(1);
|
||||
|
||||
for j in 0..unmapped_n {
|
||||
let mut qdoc = RawDocumentBuf::new();
|
||||
qdoc.append(cstr!("qmSearchCode"), "QM_UNMAPPED:US");
|
||||
qdoc.append(cstr!("date"), main_strs[j % main_len].as_str());
|
||||
qdoc.append(cstr!("sharevolume"), 50_000_i32);
|
||||
qm_w.write_all(qdoc.as_bytes())
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: qm_prices_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
for j in 0..no_partner_n {
|
||||
let mut qdoc = RawDocumentBuf::new();
|
||||
qdoc.append(cstr!("qmSearchCode"), "QM_ONLY:US");
|
||||
qdoc.append(cstr!("date"), main_strs[j % main_len].as_str());
|
||||
qdoc.append(cstr!("sharevolume"), 75_000_i64);
|
||||
qm_w.write_all(qdoc.as_bytes())
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: qm_prices_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
for j in 0..wrong_type_n {
|
||||
let mut qdoc = RawDocumentBuf::new();
|
||||
qdoc.append(cstr!("qmSearchCode"), qm_codes[0].as_str());
|
||||
qdoc.append(cstr!("date"), main_strs[j % main_len].as_str());
|
||||
qdoc.append(cstr!("sharevolume"), "bad-volume");
|
||||
qm_w.write_all(qdoc.as_bytes())
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: qm_prices_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
eod_w
|
||||
.flush()
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: eod_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
qm_w.flush()
|
||||
.map_err(|source| CurateBarsCmdBenchError::FixtureIo {
|
||||
path: qm_prices_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
|
||||
// 4. Run the full command path file -> Parquet with decode / curate / write timing.
|
||||
let args = CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_path,
|
||||
qm_prices: Some(qm_prices_path),
|
||||
provider_mapping: mapping_path,
|
||||
listing_currencies: currencies_path,
|
||||
out_dir: out_dir.clone(),
|
||||
|
|
@ -5426,6 +5556,7 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
.map_err(CurateBarsCmdBenchError::Verify)?;
|
||||
|
||||
let decode_elapsed_ms = timed.decode_elapsed_secs * 1_000.0;
|
||||
let qm_decode_rekey_elapsed_ms = timed.qm_decode_rekey_elapsed_secs * 1_000.0;
|
||||
let curate_elapsed_ms = timed.curate_elapsed_secs * 1_000.0;
|
||||
let write_elapsed_ms = timed.write_elapsed_secs * 1_000.0;
|
||||
let total_elapsed_secs =
|
||||
|
|
@ -5433,18 +5564,29 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
let total_elapsed_ms = total_elapsed_secs * 1_000.0;
|
||||
|
||||
let (decode_rows_per_sec, _) = compute_rates(rows, timed.decode_elapsed_secs);
|
||||
let (qm_decode_rekey_docs_per_sec, _) = compute_rates(
|
||||
timed.report.qm_prices_docs_framed as usize,
|
||||
timed.qm_decode_rekey_elapsed_secs,
|
||||
);
|
||||
let (curate_rows_per_sec, _) =
|
||||
compute_rates(timed.report.buffered_bars, timed.curate_elapsed_secs);
|
||||
let (write_rows_per_sec, _) =
|
||||
compute_rates(timed.report.write_stats.rows_written, timed.write_elapsed_secs);
|
||||
let (total_rows_per_sec, _) = compute_rates(rows, total_elapsed_secs);
|
||||
|
||||
let total_input_bytes = timed.report.eod_bytes_read + timed.report.splits_bytes_read;
|
||||
let total_input_bytes = timed.report.eod_bytes_read
|
||||
+ timed.report.splits_bytes_read
|
||||
+ timed.report.qm_prices_bytes_read;
|
||||
let input_mb_per_sec = if timed.decode_elapsed_secs > 0.0 {
|
||||
(total_input_bytes as f64 / MIB) / timed.decode_elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let qm_input_mb_per_sec = if timed.qm_decode_rekey_elapsed_secs > 0.0 {
|
||||
(timed.report.qm_prices_bytes_read as f64 / MIB) / timed.qm_decode_rekey_elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let write_mb_per_sec = if timed.write_elapsed_secs > 0.0 {
|
||||
(timed.report.write_stats.bytes_written as f64 / MIB) / timed.write_elapsed_secs
|
||||
} else {
|
||||
|
|
@ -5468,6 +5610,8 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
eod_bytes_read: timed.report.eod_bytes_read,
|
||||
splits_docs_framed: timed.report.splits_docs_framed,
|
||||
splits_bytes_read: timed.report.splits_bytes_read,
|
||||
qm_docs_framed: timed.report.qm_prices_docs_framed,
|
||||
qm_bytes_read: timed.report.qm_prices_bytes_read,
|
||||
bars_unmapped_source_dropped: timed.report.bars_unmapped_source_dropped,
|
||||
buffered_bars: timed.report.buffered_bars,
|
||||
buffered_bar_bytes: timed.report.buffered_bar_bytes,
|
||||
|
|
@ -5481,6 +5625,9 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
decode_elapsed_ms,
|
||||
decode_rows_per_sec,
|
||||
input_mb_per_sec,
|
||||
qm_decode_rekey_elapsed_ms,
|
||||
qm_decode_rekey_docs_per_sec,
|
||||
qm_input_mb_per_sec,
|
||||
curate_elapsed_ms,
|
||||
curate_rows_per_sec,
|
||||
write_elapsed_ms,
|
||||
|
|
@ -5492,6 +5639,10 @@ fn run_curate_bars_cmd_benchmark_tracked(
|
|||
split_rekey: timed.report.split_rekey,
|
||||
eod_decode: timed.report.eod_decode,
|
||||
splits_decode: timed.report.splits_decode,
|
||||
qm_prices_decode: timed.report.qm_prices_decode,
|
||||
qm_rekey: timed.report.qm_rekey,
|
||||
injected_mismatches,
|
||||
mismatch_samples_out: timed.report.mismatch_samples.len(),
|
||||
curate_stats: timed.report.curate_stats,
|
||||
};
|
||||
|
||||
|
|
@ -11749,6 +11900,53 @@ mod tests {
|
|||
assert!(report.curate_stats.listing_collision_collapsed > 0);
|
||||
assert!(report.curate_stats.listing_collision_dropped > 0);
|
||||
assert!(report.curate_stats.dropped_missing_currency > 0);
|
||||
assert!(report.qm_docs_framed > 0);
|
||||
assert_eq!(
|
||||
report.qm_rekey.qm_in,
|
||||
report.qm_rekey.qm_attached
|
||||
+ report.qm_rekey.qm_unmapped_qm
|
||||
+ report.qm_rekey.qm_no_eod_partner
|
||||
+ report.qm_prices_decode.rejected_total()
|
||||
);
|
||||
assert!(report.qm_rekey.qm_attached > 0);
|
||||
assert!(report.qm_rekey.qm_unmapped_qm > 0);
|
||||
assert!(report.qm_rekey.qm_no_eod_partner > 0);
|
||||
assert!(report.qm_prices_decode.rejected_wrong_type > 0);
|
||||
assert_eq!(
|
||||
report.qm_rekey.qm_volumes_attached,
|
||||
report.curate_stats.builder.qm_rows_in
|
||||
);
|
||||
assert_eq!(
|
||||
report.curate_stats.builder.volume_checked
|
||||
+ report.curate_stats.builder.volume_unchecked,
|
||||
report.curate_stats.builder.rows_out
|
||||
);
|
||||
assert_eq!(
|
||||
report.curate_stats.builder.volume_within_tolerance
|
||||
+ report.curate_stats.builder.volume_mismatched,
|
||||
report.curate_stats.builder.volume_checked
|
||||
);
|
||||
assert!(report.injected_mismatches > 0);
|
||||
assert_eq!(
|
||||
report.curate_stats.builder.volume_mismatched,
|
||||
report.injected_mismatches
|
||||
);
|
||||
assert_eq!(
|
||||
report.mismatch_samples_out,
|
||||
report.injected_mismatches.min(crate::bars::MAX_MISMATCH_SAMPLES)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_cmd_benchmark_zero_rows_handles_cleanly() {
|
||||
let (report, dir) = run_curate_bars_cmd_benchmark_tracked(0).unwrap();
|
||||
assert!(!dir.exists(), "temp dir {} should be removed", dir.display());
|
||||
assert_eq!(report.rows, 0);
|
||||
assert_eq!(report.eod_docs_framed, 0);
|
||||
assert_eq!(report.qm_docs_framed, 0);
|
||||
assert_eq!(report.injected_mismatches, 0);
|
||||
assert_eq!(report.curate_stats.builder.volume_mismatched, 0);
|
||||
assert_eq!(report.mismatch_samples_out, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
458
tools/curate-etl/src/bson_qm_prices.rs
Normal file
458
tools/curate-etl/src/bson_qm_prices.rs
Normal file
|
|
@ -0,0 +1,458 @@
|
|||
//! Zero-copy raw BSON decoder for MongoDB `qmPrices` documents (`M1.2ah`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into
|
||||
//! borrowed [`RawQmPrice`] views without allocating a `String` or `bson::Document` per row.
|
||||
//! Callers convert borrowed views into [`crate::bars::QmRawVolume<K>`] via a caller-supplied key
|
||||
//! mapper (such as date-aware `provider_mapping` re-keying into interned `"eod"` keys).
|
||||
//!
|
||||
//! # Empirical Field Contract & Cited Sources
|
||||
//!
|
||||
//! - `apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts:97-109`: writes
|
||||
//! `...price` (the raw QuoteMedia EOD payload including `date` and `sharevolume`), `symbol`,
|
||||
//! `exchange`, `qmSearchCode`, and `dateTime: new Date(price.date)` into `qmPrices`, keyed by
|
||||
//! `['qmSearchCode', 'date']`.
|
||||
//! - `apps/stock/data-pipeline/src/normalization/bar-spans.ts:19-24`: `qmPrices` uses
|
||||
//! `qmSearchCode` and `date`.
|
||||
//! - `apps/stock/data-pipeline/src/security-master/sample-closes.ts:300-303`: documents `qmPrices`
|
||||
//! copying the provider's `date` string verbatim (`YYYY-MM-DD`, with BSON `Date` stored
|
||||
//! separately in `dateTime`).
|
||||
//! - `design/DATA-CONTRACTS.md` §1 (line 14): `qmPrices` (`51.5M` docs) stores genuinely raw
|
||||
//! `unadjustedopen..unadjustedclose` and `sharevolume` for `eodPrices` volume cross-checking.
|
||||
//!
|
||||
//! Accepted BSON field representations:
|
||||
//! - `qmSearchCode`: BSON UTF-8 `String` (borrowed verbatim — never trimmed; empty or
|
||||
//! whitespace-only is rejected as [`BsonQmPriceError::EmptyField`]).
|
||||
//! - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` validated via
|
||||
//! [`crate::bson_eod_prices::parse_ymd_strict_days`]; BSON `DateTime` and other types are
|
||||
//! rejected as [`BsonQmPriceError::WrongType`], and malformed/non-calendar strings as
|
||||
//! [`BsonQmPriceError::MalformedDate`].
|
||||
//! - `sharevolume`: BSON `Double`, `Int32`, or `Int64` decoded to `f64`. Numeric value validity
|
||||
//! (non-finite / negative) is intentionally left to [`crate::bars::build_bars_1d`]
|
||||
//! (`qm_invalid_volume_dropped`). Missing, `Null`, or non-numeric types are rejected with
|
||||
//! counted reasons.
|
||||
//! - Unknown extra fields (`_id`, `symbol`, `exchange`, `dateTime`,
|
||||
//! `unadjustedopen..unadjustedclose`, nested objects/arrays, etc.) are skipped without calling
|
||||
//! `elem.value()`.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use crate::bars::QmRawVolume;
|
||||
use crate::bson_eod_prices::{
|
||||
iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError,
|
||||
};
|
||||
|
||||
/// MongoDB field name for the QuoteMedia security key (`prices.action.ts:101,108`).
|
||||
pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode";
|
||||
/// MongoDB field name for the verbatim `YYYY-MM-DD` session date string (`prices.action.ts:102,108`).
|
||||
pub const FIELD_DATE: &str = "date";
|
||||
/// MongoDB field name for the genuinely raw QuoteMedia share volume (`DATA-CONTRACTS.md` §1).
|
||||
pub const FIELD_SHARE_VOLUME: &str = "sharevolume";
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `qmPrices` BSON document.
|
||||
///
|
||||
/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice.
|
||||
/// `share_volume` is passed through without domain filtering so downstream [`crate::bars::build_bars_1d`]
|
||||
/// accounts for negative or non-finite values under `qm_invalid_volume_dropped`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawQmPrice<'a> {
|
||||
pub qm_search_code: &'a str,
|
||||
/// Session date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub session_date: i32,
|
||||
/// Raw `qmPrices.sharevolume` converted from BSON `Double`, `Int32`, or `Int64`.
|
||||
pub share_volume: f64,
|
||||
}
|
||||
|
||||
impl<'a> RawQmPrice<'a> {
|
||||
/// Converts this borrowed view into a [`QmRawVolume<K>`] using a caller-supplied key mapper.
|
||||
#[inline]
|
||||
pub fn into_qm_raw_volume<K, F>(self, map_key: F) -> QmRawVolume<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> K,
|
||||
{
|
||||
QmRawVolume {
|
||||
key: map_key(self.qm_search_code, self.session_date),
|
||||
session_date: self.session_date,
|
||||
share_volume: self.share_volume,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fallible conversion into [`QmRawVolume<K>`] using a caller-supplied key resolver.
|
||||
#[inline]
|
||||
pub fn try_into_qm_raw_volume<K, F>(self, map_key: F) -> Option<QmRawVolume<K>>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = map_key(self.qm_search_code, self.session_date)?;
|
||||
Some(QmRawVolume {
|
||||
key,
|
||||
session_date: self.session_date,
|
||||
share_volume: self.share_volume,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed errors returned while decoding raw `qmPrices` 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 BsonQmPriceError {
|
||||
/// 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 required field had an unexpected BSON element type.
|
||||
WrongType {
|
||||
field: &'static str,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// `date` string was not a valid strict `YYYY-MM-DD` Gregorian calendar date.
|
||||
MalformedDate { field: &'static str },
|
||||
/// 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 BsonQmPriceError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingField { field } => {
|
||||
write!(f, "qmPrices BSON missing required field '{field}'")
|
||||
}
|
||||
Self::EmptyField { field } => {
|
||||
write!(
|
||||
f,
|
||||
"qmPrices BSON field '{field}' must not be empty or blank"
|
||||
)
|
||||
}
|
||||
Self::WrongType { field, actual } => {
|
||||
write!(
|
||||
f,
|
||||
"qmPrices BSON field '{field}' has unexpected BSON type {actual:?}"
|
||||
)
|
||||
}
|
||||
Self::MalformedDate { field } => {
|
||||
write!(
|
||||
f,
|
||||
"qmPrices BSON field '{field}' is not a valid strict YYYY-MM-DD date"
|
||||
)
|
||||
}
|
||||
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 BsonQmPriceError {}
|
||||
|
||||
#[inline]
|
||||
fn map_framing_error(err: BsonEodPriceError) -> BsonQmPriceError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonQmPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonQmPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => {
|
||||
BsonQmPriceError::CorruptBson { offset, detail }
|
||||
}
|
||||
BsonEodPriceError::MissingField { field } => BsonQmPriceError::MissingField { field },
|
||||
BsonEodPriceError::EmptyField { field } => BsonQmPriceError::EmptyField { field },
|
||||
BsonEodPriceError::WrongType { field, actual } => {
|
||||
BsonQmPriceError::WrongType { field, actual }
|
||||
}
|
||||
BsonEodPriceError::MalformedDate { field } => BsonQmPriceError::MalformedDate { field },
|
||||
BsonEodPriceError::InvalidNumber { field, .. } => BsonQmPriceError::CorruptBson {
|
||||
offset: 0,
|
||||
detail: format!("unexpected numeric framing error on field '{field}'"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-batch decode and rejection accounting for [`decode_qm_price_buffer`].
|
||||
///
|
||||
/// Conservation invariant: `decoded + rejected_total() == docs_in`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonQmPriceDecodeStats {
|
||||
pub docs_in: usize,
|
||||
pub decoded: usize,
|
||||
pub rejected_missing_field: usize,
|
||||
pub rejected_empty_field: usize,
|
||||
pub rejected_wrong_type: usize,
|
||||
pub rejected_malformed_date: usize,
|
||||
pub rejected_corrupt_document: usize,
|
||||
}
|
||||
|
||||
impl BsonQmPriceDecodeStats {
|
||||
/// 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_corrupt_document
|
||||
}
|
||||
|
||||
/// Increments the rejection counter corresponding to `err`.
|
||||
#[inline]
|
||||
pub fn record_error(&mut self, err: &BsonQmPriceError) {
|
||||
match err {
|
||||
BsonQmPriceError::MissingField { .. } => self.rejected_missing_field += 1,
|
||||
BsonQmPriceError::EmptyField { .. } => self.rejected_empty_field += 1,
|
||||
BsonQmPriceError::WrongType { .. } => self.rejected_wrong_type += 1,
|
||||
BsonQmPriceError::MalformedDate { .. } => self.rejected_malformed_date += 1,
|
||||
BsonQmPriceError::TruncatedDocument { .. }
|
||||
| BsonQmPriceError::CorruptDocumentLength { .. }
|
||||
| BsonQmPriceError::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_corrupt_document += other.rejected_corrupt_document;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonQmPriceDecodeStats {
|
||||
#[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>, BsonQmPriceError> {
|
||||
elem.value().map_err(|err| BsonQmPriceError::CorruptBson {
|
||||
offset,
|
||||
detail: format!("field '{field}': {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_numeric_passthrough(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonQmPriceError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => Ok(v),
|
||||
RawBsonRef::Int32(v) => Ok(f64::from(v)),
|
||||
RawBsonRef::Int64(v) => Ok(v as f64),
|
||||
other => Err(BsonQmPriceError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_qm_price_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawQmPrice<'a>, BsonQmPriceError> {
|
||||
let mut qm_search_code: Option<&'a str> = None;
|
||||
let mut session_date: Option<i32> = None;
|
||||
let mut share_volume: Option<f64> = None;
|
||||
let mut first_semantic_err: Option<BsonQmPriceError> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonQmPriceError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key();
|
||||
|
||||
if key == cstr!("qmSearchCode") {
|
||||
match decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)? {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonQmPriceError::EmptyField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
qm_search_code = Some(s);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonQmPriceError::WrongType {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("date") {
|
||||
match decode_element_value(FIELD_DATE, elem, offset)? {
|
||||
RawBsonRef::String(s) => match parse_ymd_strict_days(s) {
|
||||
Some(d) => session_date = Some(d),
|
||||
None => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err =
|
||||
Some(BsonQmPriceError::MalformedDate { field: FIELD_DATE });
|
||||
}
|
||||
}
|
||||
},
|
||||
other => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonQmPriceError::WrongType {
|
||||
field: FIELD_DATE,
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("sharevolume") {
|
||||
let val = decode_element_value(FIELD_SHARE_VOLUME, elem, offset)?;
|
||||
match decode_numeric_passthrough(FIELD_SHARE_VOLUME, val) {
|
||||
Ok(v) => share_volume = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Unknown extra fields (`_id`, `dateTime`, `unadjustedopen..unadjustedclose`, etc.)
|
||||
// are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
if let Some(err) = first_semantic_err {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let Some(qm_search_code) = qm_search_code else {
|
||||
return Err(BsonQmPriceError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
};
|
||||
let Some(session_date) = session_date else {
|
||||
return Err(BsonQmPriceError::MissingField { field: FIELD_DATE });
|
||||
};
|
||||
let Some(share_volume) = share_volume else {
|
||||
return Err(BsonQmPriceError::MissingField {
|
||||
field: FIELD_SHARE_VOLUME,
|
||||
});
|
||||
};
|
||||
|
||||
Ok(RawQmPrice {
|
||||
qm_search_code,
|
||||
session_date,
|
||||
share_volume,
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `qmPrices` MongoDB document in one forward pass
|
||||
/// without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_qm_price_doc<'a>(doc: &'a RawDocument) -> Result<RawQmPrice<'a>, BsonQmPriceError> {
|
||||
decode_qm_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed [`RawQmPrice`].
|
||||
pub fn decode_qm_price_bytes<'a>(bytes: &'a [u8]) -> Result<RawQmPrice<'a>, BsonQmPriceError> {
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_qm_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_price_doc`], invoking
|
||||
/// `on_price` 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_price_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_price: F,
|
||||
mut on_error: E,
|
||||
) -> BsonQmPriceDecodeStats
|
||||
where
|
||||
F: FnMut(RawQmPrice<'a>),
|
||||
E: FnMut(usize, BsonQmPriceError),
|
||||
{
|
||||
let mut stats = BsonQmPriceDecodeStats::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_price_doc_at(doc, doc_offset) {
|
||||
Ok(price) => {
|
||||
stats.decoded += 1;
|
||||
on_price(price);
|
||||
}
|
||||
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_prices_tests.rs"]
|
||||
mod tests;
|
||||
413
tools/curate-etl/src/bson_qm_prices_tests.rs
Normal file
413
tools/curate-etl/src/bson_qm_prices_tests.rs
Normal file
|
|
@ -0,0 +1,413 @@
|
|||
use bson::oid::ObjectId;
|
||||
use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf};
|
||||
use bson::spec::ElementType;
|
||||
use bson::DateTime;
|
||||
|
||||
use super::*;
|
||||
use crate::bson_eod_prices::MILLIS_PER_DAY;
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
fn make_qm_price_doc_f64(code: &str, date: &str, share_volume: f64) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("sharevolume"), share_volume);
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_realistic_qm_price_doc_and_ignores_extra_fields() {
|
||||
let mut nested = RawDocumentBuf::new();
|
||||
nested.append(cstr!("provider"), "quotemedia");
|
||||
nested.append(cstr!("version"), 2_i32);
|
||||
|
||||
let mut tags = RawArrayBuf::new();
|
||||
tags.push("eod");
|
||||
tags.push("raw");
|
||||
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(
|
||||
cstr!("_id"),
|
||||
ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
|
||||
);
|
||||
doc.append(cstr!("symbol"), "NVDA");
|
||||
doc.append(cstr!("exchange"), "NASDAQ");
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-07");
|
||||
doc.append(
|
||||
cstr!("dateTime"),
|
||||
DateTime::from_millis(i64::from(day(2024, 6, 7)) * MILLIS_PER_DAY),
|
||||
);
|
||||
doc.append(cstr!("unadjustedopen"), 1197.7_f64);
|
||||
doc.append(cstr!("unadjustedhigh"), 1216.92_f64);
|
||||
doc.append(cstr!("unadjustedlow"), 1180.22_f64);
|
||||
doc.append(cstr!("unadjustedclose"), 1208.88_f64);
|
||||
doc.append(cstr!("sharevolume"), 41_239_000.0_f64);
|
||||
doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let decoded = decode_qm_price_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.qm_search_code, "NVDA");
|
||||
assert_eq!(decoded.session_date, day(2024, 6, 7));
|
||||
assert_eq!(decoded.share_volume.to_bits(), 41_239_000.0_f64.to_bits());
|
||||
assert_eq!(decode_qm_price_bytes(doc.as_bytes()).unwrap(), decoded);
|
||||
|
||||
let mapped = decoded.into_qm_raw_volume(|code, _d| format!("{code}.US"));
|
||||
assert_eq!(mapped.key, "NVDA.US");
|
||||
assert_eq!(mapped.session_date, day(2024, 6, 7));
|
||||
assert_eq!(mapped.share_volume.to_bits(), 41_239_000.0_f64.to_bits());
|
||||
|
||||
let maybe_mapped = decoded.try_into_qm_raw_volume(|code, _d| Some(code.to_owned()));
|
||||
assert_eq!(
|
||||
maybe_mapped,
|
||||
Some(QmRawVolume {
|
||||
key: "NVDA".to_string(),
|
||||
session_date: day(2024, 6, 7),
|
||||
share_volume: 41_239_000.0,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
decoded.try_into_qm_raw_volume::<String, _>(|_, _| None),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_sharevolume_as_double_int32_and_int64() {
|
||||
let mut doc_f64 = RawDocumentBuf::new();
|
||||
doc_f64.append(cstr!("qmSearchCode"), "AAPL");
|
||||
doc_f64.append(cstr!("date"), "2024-06-07");
|
||||
doc_f64.append(cstr!("sharevolume"), 12_345_678.5_f64);
|
||||
|
||||
let mut doc_i32 = RawDocumentBuf::new();
|
||||
doc_i32.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc_i32.append(cstr!("date"), "2024-06-07");
|
||||
doc_i32.append(cstr!("sharevolume"), 500_000_i32);
|
||||
|
||||
let mut doc_i64 = RawDocumentBuf::new();
|
||||
doc_i64.append(cstr!("qmSearchCode"), "SHOP:CA");
|
||||
doc_i64.append(cstr!("date"), "2024-06-07");
|
||||
doc_i64.append(cstr!("sharevolume"), 3_000_000_000_i64);
|
||||
|
||||
let p_f64 = decode_qm_price_doc(&doc_f64).unwrap();
|
||||
assert_eq!(p_f64.share_volume.to_bits(), 12_345_678.5_f64.to_bits());
|
||||
|
||||
let p_i32 = decode_qm_price_doc(&doc_i32).unwrap();
|
||||
assert_eq!(p_i32.share_volume.to_bits(), 500_000.0_f64.to_bits());
|
||||
|
||||
let p_i64 = decode_qm_price_doc(&doc_i64).unwrap();
|
||||
assert_eq!(p_i64.share_volume.to_bits(), 3_000_000_000.0_f64.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_through_negative_nan_inf_and_neg_zero_sharevolume_to_builder() {
|
||||
let cases = [
|
||||
(-100.0_f64, true),
|
||||
(f64::NAN, false),
|
||||
(f64::INFINITY, true),
|
||||
(f64::NEG_INFINITY, true),
|
||||
(-0.0_f64, true),
|
||||
];
|
||||
|
||||
for (val, compare_bits) in cases {
|
||||
let doc = make_qm_price_doc_f64("NVDA", "2024-06-07", val);
|
||||
let decoded = decode_qm_price_doc(&doc).unwrap();
|
||||
if compare_bits {
|
||||
assert_eq!(decoded.share_volume.to_bits(), val.to_bits());
|
||||
} else {
|
||||
assert!(decoded.share_volume.is_nan());
|
||||
}
|
||||
}
|
||||
|
||||
let mut neg_i32 = RawDocumentBuf::new();
|
||||
neg_i32.append(cstr!("qmSearchCode"), "NVDA");
|
||||
neg_i32.append(cstr!("date"), "2024-06-07");
|
||||
neg_i32.append(cstr!("sharevolume"), -42_i32);
|
||||
assert_eq!(decode_qm_price_doc(&neg_i32).unwrap().share_volume, -42.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_qm_search_code_verbatim_including_leading_and_trailing_spaces() {
|
||||
let doc = make_qm_price_doc_f64(" NVDA ", "2024-06-07", 1_000.0);
|
||||
let decoded = decode_qm_price_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.qm_search_code, " NVDA ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_null_empty_and_wrong_typed_fields() {
|
||||
// Missing qmSearchCode
|
||||
let mut missing_code = RawDocumentBuf::new();
|
||||
missing_code.append(cstr!("date"), "2024-06-07");
|
||||
missing_code.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&missing_code),
|
||||
Err(BsonQmPriceError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
})
|
||||
);
|
||||
|
||||
// Missing date
|
||||
let mut missing_date = RawDocumentBuf::new();
|
||||
missing_date.append(cstr!("qmSearchCode"), "NVDA");
|
||||
missing_date.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&missing_date),
|
||||
Err(BsonQmPriceError::MissingField { field: FIELD_DATE })
|
||||
);
|
||||
|
||||
// Missing sharevolume
|
||||
let mut missing_vol = RawDocumentBuf::new();
|
||||
missing_vol.append(cstr!("qmSearchCode"), "NVDA");
|
||||
missing_vol.append(cstr!("date"), "2024-06-07");
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&missing_vol),
|
||||
Err(BsonQmPriceError::MissingField {
|
||||
field: FIELD_SHARE_VOLUME,
|
||||
})
|
||||
);
|
||||
|
||||
// Empty / whitespace-only qmSearchCode
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let doc = make_qm_price_doc_f64(blank, "2024-06-07", 100.0);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&doc),
|
||||
Err(BsonQmPriceError::EmptyField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// Null / wrong-typed qmSearchCode
|
||||
let mut null_code = RawDocumentBuf::new();
|
||||
null_code.append(cstr!("qmSearchCode"), RawBsonRef::Null);
|
||||
null_code.append(cstr!("date"), "2024-06-07");
|
||||
null_code.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&null_code),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
actual: ElementType::Null,
|
||||
})
|
||||
);
|
||||
|
||||
let mut int_code = RawDocumentBuf::new();
|
||||
int_code.append(cstr!("qmSearchCode"), 42_i32);
|
||||
int_code.append(cstr!("date"), "2024-06-07");
|
||||
int_code.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&int_code),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
actual: ElementType::Int32,
|
||||
})
|
||||
);
|
||||
|
||||
// Null / BSON DateTime / int date
|
||||
let mut null_date = RawDocumentBuf::new();
|
||||
null_date.append(cstr!("qmSearchCode"), "NVDA");
|
||||
null_date.append(cstr!("date"), RawBsonRef::Null);
|
||||
null_date.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&null_date),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_DATE,
|
||||
actual: ElementType::Null,
|
||||
})
|
||||
);
|
||||
|
||||
let mut dt_date = RawDocumentBuf::new();
|
||||
dt_date.append(cstr!("qmSearchCode"), "NVDA");
|
||||
dt_date.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(day(2024, 6, 7)) * MILLIS_PER_DAY),
|
||||
);
|
||||
dt_date.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&dt_date),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_DATE,
|
||||
actual: ElementType::DateTime,
|
||||
})
|
||||
);
|
||||
|
||||
// Null / string / bool sharevolume
|
||||
let mut null_vol = RawDocumentBuf::new();
|
||||
null_vol.append(cstr!("qmSearchCode"), "NVDA");
|
||||
null_vol.append(cstr!("date"), "2024-06-07");
|
||||
null_vol.append(cstr!("sharevolume"), RawBsonRef::Null);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&null_vol),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_SHARE_VOLUME,
|
||||
actual: ElementType::Null,
|
||||
})
|
||||
);
|
||||
|
||||
let mut str_vol = RawDocumentBuf::new();
|
||||
str_vol.append(cstr!("qmSearchCode"), "NVDA");
|
||||
str_vol.append(cstr!("date"), "2024-06-07");
|
||||
str_vol.append(cstr!("sharevolume"), "1000");
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&str_vol),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_SHARE_VOLUME,
|
||||
actual: ElementType::String,
|
||||
})
|
||||
);
|
||||
|
||||
let mut bool_vol = RawDocumentBuf::new();
|
||||
bool_vol.append(cstr!("qmSearchCode"), "NVDA");
|
||||
bool_vol.append(cstr!("date"), "2024-06-07");
|
||||
bool_vol.append(cstr!("sharevolume"), true);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&bool_vol),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_SHARE_VOLUME,
|
||||
actual: ElementType::Boolean,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_and_non_calendar_date_strings() {
|
||||
let bad_dates = [
|
||||
"",
|
||||
"2023-02-29",
|
||||
"2024-04-31",
|
||||
"2024-00-10",
|
||||
"2024-13-01",
|
||||
"2024/06/07",
|
||||
" 2024-06-07",
|
||||
"2024-06-07 ",
|
||||
"2024-06-07T00:00:00Z",
|
||||
"24-06-07",
|
||||
];
|
||||
for bad in bad_dates {
|
||||
let doc = make_qm_price_doc_f64("NVDA", bad, 100.0);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&doc),
|
||||
Err(BsonQmPriceError::MalformedDate { field: FIELD_DATE }),
|
||||
"expected MalformedDate for '{bad}'"
|
||||
);
|
||||
}
|
||||
|
||||
// Leap day 2024-02-29 is valid.
|
||||
let leap = make_qm_price_doc_f64("NVDA", "2024-02-29", 100.0);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&leap).unwrap().session_date,
|
||||
day(2024, 2, 29)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_and_truncated_buffers_never_panic_and_preserve_accounting() {
|
||||
assert!(matches!(
|
||||
decode_qm_price_bytes(&[1, 2]),
|
||||
Err(BsonQmPriceError::TruncatedDocument { offset: 0, .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_price_bytes(&4_i32.to_le_bytes()),
|
||||
Err(BsonQmPriceError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: 4
|
||||
})
|
||||
));
|
||||
|
||||
// Mixed buffer: 3 valid (Double, Int32, Int64), 1 missing field, 1 empty field,
|
||||
// 1 wrong type, 1 malformed date, 1 trailing truncated doc.
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(make_qm_price_doc_f64("NVDA", "2024-06-07", 41_239_000.0).as_bytes());
|
||||
|
||||
let mut d_i32 = RawDocumentBuf::new();
|
||||
d_i32.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_i32.append(cstr!("date"), "2024-06-07");
|
||||
d_i32.append(cstr!("sharevolume"), 2_500_000_i32);
|
||||
buf.extend_from_slice(d_i32.as_bytes());
|
||||
|
||||
let mut d_i64 = RawDocumentBuf::new();
|
||||
d_i64.append(cstr!("qmSearchCode"), "AAPL");
|
||||
d_i64.append(cstr!("date"), "2024-06-07");
|
||||
d_i64.append(cstr!("sharevolume"), 50_000_000_i64);
|
||||
buf.extend_from_slice(d_i64.as_bytes());
|
||||
|
||||
let mut missing = RawDocumentBuf::new();
|
||||
missing.append(cstr!("qmSearchCode"), "MSFT");
|
||||
missing.append(cstr!("date"), "2024-06-07");
|
||||
buf.extend_from_slice(missing.as_bytes());
|
||||
|
||||
buf.extend_from_slice(make_qm_price_doc_f64(" ", "2024-06-07", 10.0).as_bytes());
|
||||
|
||||
let mut wrong_type = RawDocumentBuf::new();
|
||||
wrong_type.append(cstr!("qmSearchCode"), "AMZN");
|
||||
wrong_type.append(cstr!("date"), "2024-06-07");
|
||||
wrong_type.append(cstr!("sharevolume"), "not-a-number");
|
||||
buf.extend_from_slice(wrong_type.as_bytes());
|
||||
|
||||
buf.extend_from_slice(make_qm_price_doc_f64("GOOG", "2023-02-29", 10.0).as_bytes());
|
||||
|
||||
let truncated_offset = buf.len();
|
||||
buf.extend_from_slice(&50_i32.to_le_bytes());
|
||||
buf.extend_from_slice(&[0x02, b'a', 0x00]);
|
||||
|
||||
let mut decoded_rows: Vec<(String, i32, f64)> = Vec::new();
|
||||
let mut errors: Vec<(usize, BsonQmPriceError)> = Vec::new();
|
||||
let stats = decode_qm_price_buffer(
|
||||
&buf,
|
||||
|p| decoded_rows.push((p.qm_search_code.to_owned(), p.session_date, p.share_volume)),
|
||||
|off, err| errors.push((off, err)),
|
||||
);
|
||||
|
||||
assert_eq!(stats.docs_in, 8);
|
||||
assert_eq!(stats.decoded, 3);
|
||||
assert_eq!(stats.rejected_missing_field, 1);
|
||||
assert_eq!(stats.rejected_empty_field, 1);
|
||||
assert_eq!(stats.rejected_wrong_type, 1);
|
||||
assert_eq!(stats.rejected_malformed_date, 1);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stats.rejected_total(), 5);
|
||||
assert_eq!(stats.docs_in, stats.decoded + stats.rejected_total());
|
||||
assert_eq!(decoded_rows.len(), 3);
|
||||
assert_eq!(errors.len(), 5);
|
||||
assert_eq!(errors.last().unwrap().0, truncated_offset);
|
||||
assert!(matches!(
|
||||
errors.last().unwrap().1,
|
||||
BsonQmPriceError::TruncatedDocument { .. }
|
||||
));
|
||||
|
||||
// Verify merge / AddAssign.
|
||||
let mut merged = BsonQmPriceDecodeStats::default();
|
||||
merged += stats;
|
||||
merged += stats;
|
||||
assert_eq!(merged.docs_in, 16);
|
||||
assert_eq!(merged.decoded, 6);
|
||||
assert_eq!(merged.rejected_total(), 10);
|
||||
assert_eq!(merged.docs_in, merged.decoded + merged.rejected_total());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_bson_later_in_doc_surfaces_before_semantic_error() {
|
||||
// Build a doc with a semantic error (wrong-typed sharevolume) followed by corrupt trailing bytes.
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-07");
|
||||
doc.append(cstr!("sharevolume"), "bad-type");
|
||||
doc.append(cstr!("extra"), "hello");
|
||||
let mut bytes = doc.into_bytes();
|
||||
// Corrupt the type byte of "extra" (change string element type 0x02 to invalid 0x7E)
|
||||
// Locate "extra\0" in bytes; the type byte is right before it.
|
||||
let pos = bytes
|
||||
.windows(6)
|
||||
.position(|w| w == b"extra\0")
|
||||
.expect("extra key");
|
||||
bytes[pos - 1] = 0x7E;
|
||||
|
||||
let err = decode_qm_price_bytes(&bytes).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonQmPriceError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson, got {err:?}"
|
||||
);
|
||||
}
|
||||
|
|
@ -36,6 +36,9 @@ use crate::bson_qm_events::{
|
|||
BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, QmFilingsFieldNames,
|
||||
RawQmEarning, RawQmFiling,
|
||||
};
|
||||
use crate::bson_qm_prices::{
|
||||
decode_qm_price_buffer, BsonQmPriceDecodeStats, BsonQmPriceError, RawQmPrice,
|
||||
};
|
||||
use crate::bson_te_market_data::{
|
||||
decode_te_market_data_buffer, BsonTeMarketDataDecodeStats, BsonTeMarketDataError,
|
||||
};
|
||||
|
|
@ -669,6 +672,75 @@ where
|
|||
decode_qm_dividend_chunks(&mut chunk_reader, on_dividend, on_error)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rebase_qm_price_error(base: u64, err: BsonQmPriceError) -> BsonQmPriceError {
|
||||
match err {
|
||||
BsonQmPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonQmPriceError::TruncatedDocument {
|
||||
offset: rebase_offset(base, offset),
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonQmPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonQmPriceError::CorruptDocumentLength {
|
||||
offset: rebase_offset(base, offset),
|
||||
declared_len,
|
||||
},
|
||||
BsonQmPriceError::CorruptBson { offset, detail } => BsonQmPriceError::CorruptBson {
|
||||
offset: rebase_offset(base, offset),
|
||||
detail,
|
||||
},
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_price_buffer`],
|
||||
/// accumulating [`BsonQmPriceDecodeStats`] and rebasing per-document error offsets to absolute
|
||||
/// stream byte offsets.
|
||||
pub fn decode_qm_price_chunks<R, F, E>(
|
||||
reader: &mut RawBsonChunkReader<R>,
|
||||
mut on_price: F,
|
||||
mut on_error: E,
|
||||
) -> Result<BsonQmPriceDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawQmPrice<'a>),
|
||||
E: FnMut(u64, BsonQmPriceError),
|
||||
{
|
||||
let mut total = BsonQmPriceDecodeStats::default();
|
||||
while let Some(chunk) = reader.next_chunk()? {
|
||||
let base = chunk.start_offset;
|
||||
let chunk_stats = decode_qm_price_buffer(chunk.bytes, &mut on_price, |local_offset, err| {
|
||||
let abs_offset = base + local_offset as u64;
|
||||
on_error(abs_offset, rebase_qm_price_error(base, err));
|
||||
});
|
||||
total += chunk_stats;
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
/// Streams a concatenated raw BSON `qmPrices` [`std::io::Read`] source through
|
||||
/// [`decode_qm_price_buffer`] with bounded memory.
|
||||
pub fn decode_qm_price_stream<R, F, E>(
|
||||
reader: R,
|
||||
options: BsonStreamOptions,
|
||||
on_price: F,
|
||||
on_error: E,
|
||||
) -> Result<BsonQmPriceDecodeStats, BsonStreamError>
|
||||
where
|
||||
R: io::Read,
|
||||
F: for<'a> FnMut(RawQmPrice<'a>),
|
||||
E: FnMut(u64, BsonQmPriceError),
|
||||
{
|
||||
let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?;
|
||||
decode_qm_price_chunks(&mut chunk_reader, on_price, on_error)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn rebase_te_error(base: u64, err: BsonTeMarketDataError) -> BsonTeMarketDataError {
|
||||
match err {
|
||||
|
|
|
|||
|
|
@ -10,10 +10,11 @@ use crate::bson_eod_prices::{
|
|||
use crate::bson_qm_actions::{
|
||||
decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats,
|
||||
};
|
||||
use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError};
|
||||
use crate::bson_stream::{
|
||||
decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_split_stream, BsonStreamError,
|
||||
BsonStreamOptions, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES,
|
||||
MIN_BSON_DOC_BYTES,
|
||||
decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_price_stream,
|
||||
decode_qm_split_stream, BsonStreamError, BsonStreamOptions, RawBsonChunkReader,
|
||||
DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
|
|
@ -2013,3 +2014,102 @@ fn qm_filings_and_earnings_stream_match_buffer_and_rebase_corrupt_offsets() {
|
|||
if offset == expected_offset
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_qm_price_stream_matches_buffer_rebases_offsets_and_fails_on_framing() {
|
||||
let make_doc = |code: &str, date: &str, vol: f64| -> Vec<u8> {
|
||||
let mut d = RawDocumentBuf::new();
|
||||
d.append(cstr!("qmSearchCode"), code);
|
||||
d.append(cstr!("date"), date);
|
||||
d.append(cstr!("sharevolume"), vol);
|
||||
d.into_bytes()
|
||||
};
|
||||
|
||||
let mut fixture = Vec::new();
|
||||
fixture.extend_from_slice(&make_doc("NVDA", "2024-06-07", 41_239_000.0));
|
||||
|
||||
let mut bad_type = RawDocumentBuf::new();
|
||||
bad_type.append(cstr!("qmSearchCode"), "AAPL");
|
||||
bad_type.append(cstr!("date"), "2024-06-07");
|
||||
bad_type.append(cstr!("sharevolume"), "bad");
|
||||
fixture.extend_from_slice(&bad_type.into_bytes());
|
||||
|
||||
let mut int_doc = RawDocumentBuf::new();
|
||||
int_doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
int_doc.append(cstr!("date"), "2024-06-07");
|
||||
int_doc.append(cstr!("sharevolume"), 2_500_000_i64);
|
||||
fixture.extend_from_slice(&int_doc.into_bytes());
|
||||
|
||||
// Corrupt element inside a cleanly framed document to verify CorruptBson offset rebasing.
|
||||
let mut corrupt = RawDocumentBuf::new();
|
||||
corrupt.append(cstr!("qmSearchCode"), "BAD");
|
||||
corrupt.append(cstr!("date"), "2024-06-07");
|
||||
corrupt.append(cstr!("sharevolume"), 100.0_f64);
|
||||
corrupt.append(cstr!("z"), 1_i32);
|
||||
let mut corrupt_bytes = corrupt.into_bytes();
|
||||
let z_pos = corrupt_bytes
|
||||
.windows(3)
|
||||
.position(|w| w == [0x10, b'z', 0x00])
|
||||
.expect("locate z");
|
||||
corrupt_bytes[z_pos] = 0x7e;
|
||||
let corrupt_offset = fixture.len() as u64;
|
||||
fixture.extend_from_slice(&corrupt_bytes);
|
||||
|
||||
fixture.extend_from_slice(&make_doc("SHOP:CA", "2024-06-10", 1_234_567.0));
|
||||
|
||||
let mut expected_rows = Vec::new();
|
||||
let mut expected_errs = Vec::new();
|
||||
let expected_stats = decode_qm_price_buffer(
|
||||
&fixture,
|
||||
|p| expected_rows.push((p.qm_search_code.to_owned(), p.session_date, p.share_volume.to_bits())),
|
||||
|off, err| expected_errs.push((off as u64, err)),
|
||||
);
|
||||
assert_eq!(expected_stats.docs_in, 5);
|
||||
assert_eq!(expected_stats.decoded, 3);
|
||||
assert_eq!(expected_stats.rejected_total(), 2);
|
||||
|
||||
for cap in [1, 17, 64, 512] {
|
||||
let opts = BsonStreamOptions {
|
||||
chunk_capacity_bytes: cap,
|
||||
max_doc_bytes: 4096,
|
||||
};
|
||||
let mut got_rows = Vec::new();
|
||||
let mut got_errs = Vec::new();
|
||||
let got_stats = decode_qm_price_stream(
|
||||
FixedStepReader::new(&fixture, 7),
|
||||
opts,
|
||||
|p| got_rows.push((p.qm_search_code.to_owned(), p.session_date, p.share_volume.to_bits())),
|
||||
|off, err| got_errs.push((off, err)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(got_stats, expected_stats);
|
||||
assert_eq!(got_rows, expected_rows);
|
||||
assert_eq!(got_errs.len(), expected_errs.len());
|
||||
for ((g_off, g_err), (e_off, e_err)) in got_errs.iter().zip(&expected_errs) {
|
||||
assert_eq!(g_off, e_off);
|
||||
assert_eq!(g_err, e_err);
|
||||
}
|
||||
assert!(matches!(
|
||||
got_errs[1],
|
||||
(off, BsonQmPriceError::CorruptBson { offset, .. })
|
||||
if off == corrupt_offset && offset as u64 == corrupt_offset
|
||||
));
|
||||
}
|
||||
|
||||
// Truncated trailing document must fail closed with BsonStreamError::TruncatedDocument.
|
||||
let mut truncated = fixture.clone();
|
||||
truncated.extend_from_slice(&100_i32.to_le_bytes());
|
||||
truncated.extend_from_slice(&[0x02, b'a', 0x00]);
|
||||
let err = decode_qm_price_stream(
|
||||
Cursor::new(&truncated),
|
||||
BsonStreamOptions {
|
||||
chunk_capacity_bytes: 64,
|
||||
max_doc_bytes: 4096,
|
||||
},
|
||||
|_| {},
|
||||
|_, _| {},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, BsonStreamError::TruncatedDocument { .. }));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
Usage:\n\
|
||||
{name} [--help | -h]\n\
|
||||
{name} [--version | -V]\n\
|
||||
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> (--curate-inputs <dir> | --provider-mapping <path> --listing-currencies <path>) --out <dir> [--rel-tolerance <f64>]\n\
|
||||
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> [--qm-prices <path>] (--curate-inputs <dir> | --provider-mapping <path> --listing-currencies <path>) --out <dir> [--rel-tolerance <f64>]\n\
|
||||
Curate daily bars from BSON + TSV files into bars_1d/year=YYYY/part.parquet (default --rel-tolerance: {DEFAULT_CURATE_BARS_REL_TOLERANCE})\n\
|
||||
{name} curate-adj-factors --qm-splits <path> --qm-dividends <path> --provider-mapping <path> --bars-1d <dir> --out <dir>\n\
|
||||
Curate retrospective adj_factors from BSON + TSV + bars_1d Parquet into adj_factors/part.parquet\n\
|
||||
|
|
@ -135,7 +135,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
"Usage:\n\
|
||||
{name} [--help | -h]\n\
|
||||
{name} [--version | -V]\n\
|
||||
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> (--curate-inputs <dir> | --provider-mapping <path> --listing-currencies <path>) --out <dir> [--rel-tolerance <f64>]\n\
|
||||
{name} curate-bars-1d --eod-prices <path> --qm-splits <path> [--qm-prices <path>] (--curate-inputs <dir> | --provider-mapping <path> --listing-currencies <path>) --out <dir> [--rel-tolerance <f64>]\n\
|
||||
{name} curate-adj-factors --qm-splits <path> --qm-dividends <path> --provider-mapping <path> --bars-1d <dir> --out <dir>\n\
|
||||
{name} curate-corporate-actions --qm-splits <path> --qm-dividends <path> (--curate-inputs <dir> | --provider-mapping <path> [--delistings <path>]) --out <dir>\n\
|
||||
{name} curate-fx-1d --eod-prices <path> --te-market-data <path> [--te-symbol <sym>] --out <dir>\n\
|
||||
|
|
@ -216,6 +216,7 @@ pub fn pin_curate_inputs_dir(dir: &Path) -> Result<PathBuf, String> {
|
|||
fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String> {
|
||||
let mut eod_prices: Option<PathBuf> = None;
|
||||
let mut qm_splits: Option<PathBuf> = None;
|
||||
let mut qm_prices: Option<PathBuf> = None;
|
||||
let mut curate_inputs: Option<PathBuf> = None;
|
||||
let mut provider_mapping: Option<PathBuf> = None;
|
||||
let mut listing_currencies: Option<PathBuf> = None;
|
||||
|
|
@ -259,6 +260,7 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String>
|
|||
match flag {
|
||||
"--eod-prices" => set_path(&mut eod_prices, "--eod-prices", value)?,
|
||||
"--qm-splits" => set_path(&mut qm_splits, "--qm-splits", value)?,
|
||||
"--qm-prices" => set_path(&mut qm_prices, "--qm-prices", value)?,
|
||||
"--curate-inputs" => set_path(&mut curate_inputs, "--curate-inputs", value)?,
|
||||
"--provider-mapping" => set_path(&mut provider_mapping, "--provider-mapping", value)?,
|
||||
"--listing-currencies" => {
|
||||
|
|
@ -315,6 +317,7 @@ fn parse_curate_bars_1d_args(args: &[&str]) -> Result<CurateBars1dArgs, String>
|
|||
Ok(CurateBars1dArgs {
|
||||
eod_prices,
|
||||
qm_splits,
|
||||
qm_prices,
|
||||
provider_mapping,
|
||||
listing_currencies,
|
||||
out_dir,
|
||||
|
|
@ -1692,6 +1695,36 @@ mod tests {
|
|||
CliAction::CurateBars1d(CurateBars1dArgs {
|
||||
eod_prices: PathBuf::from("/tmp/eodPrices.bson"),
|
||||
qm_splits: PathBuf::from("/tmp/qmSplits.bson"),
|
||||
qm_prices: None,
|
||||
provider_mapping: PathBuf::from("/tmp/provider_mapping.tsv"),
|
||||
listing_currencies: PathBuf::from("/tmp/listing_currencies.tsv"),
|
||||
out_dir: PathBuf::from("/tmp/out"),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
);
|
||||
|
||||
let with_qm_prices = parse_args(&to_args(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
"/tmp/eodPrices.bson",
|
||||
"--qm-splits",
|
||||
"/tmp/qmSplits.bson",
|
||||
"--qm-prices",
|
||||
"/tmp/qmPrices.bson",
|
||||
"--provider-mapping",
|
||||
"/tmp/provider_mapping.tsv",
|
||||
"--listing-currencies",
|
||||
"/tmp/listing_currencies.tsv",
|
||||
"--out",
|
||||
"/tmp/out",
|
||||
]))
|
||||
.expect("valid curate-bars-1d args with --qm-prices");
|
||||
assert_eq!(
|
||||
with_qm_prices,
|
||||
CliAction::CurateBars1d(CurateBars1dArgs {
|
||||
eod_prices: PathBuf::from("/tmp/eodPrices.bson"),
|
||||
qm_splits: PathBuf::from("/tmp/qmSplits.bson"),
|
||||
qm_prices: Some(PathBuf::from("/tmp/qmPrices.bson")),
|
||||
provider_mapping: PathBuf::from("/tmp/provider_mapping.tsv"),
|
||||
listing_currencies: PathBuf::from("/tmp/listing_currencies.tsv"),
|
||||
out_dir: PathBuf::from("/tmp/out"),
|
||||
|
|
@ -1703,6 +1736,7 @@ mod tests {
|
|||
"curate-bars-1d",
|
||||
"--eod-prices=/tmp/e.bson",
|
||||
"--qm-splits=/tmp/s.bson",
|
||||
"--qm-prices=/tmp/q.bson",
|
||||
"--provider-mapping=/tmp/m.tsv",
|
||||
"--listing-currencies=/tmp/c.tsv",
|
||||
"--out=--literal-out-dir",
|
||||
|
|
@ -1711,6 +1745,7 @@ mod tests {
|
|||
.expect("equals-style curate-bars-1d args");
|
||||
match equals_style {
|
||||
CliAction::CurateBars1d(a) => {
|
||||
assert_eq!(a.qm_prices, Some(PathBuf::from("/tmp/q.bson")));
|
||||
assert_eq!(a.out_dir, PathBuf::from("--literal-out-dir"));
|
||||
assert_eq!(a.rel_tolerance.to_bits(), 0.0_f64.to_bits());
|
||||
}
|
||||
|
|
@ -1761,6 +1796,22 @@ mod tests {
|
|||
let err = parse_args(&to_args(&dup)).unwrap_err();
|
||||
assert!(err.contains("duplicate flag '--out'"), "{err}");
|
||||
|
||||
// Invalid --qm-prices: duplicate, empty, missing value.
|
||||
let mut dup_qm = full.to_vec();
|
||||
dup_qm.extend(["--qm-prices", "q1.bson", "--qm-prices=q2.bson"]);
|
||||
let err = parse_args(&to_args(&dup_qm)).unwrap_err();
|
||||
assert!(err.contains("duplicate flag '--qm-prices'"), "{err}");
|
||||
|
||||
let mut empty_qm = full.to_vec();
|
||||
empty_qm.push("--qm-prices=");
|
||||
let err = parse_args(&to_args(&empty_qm)).unwrap_err();
|
||||
assert!(err.contains("empty value for flag '--qm-prices'"), "{err}");
|
||||
|
||||
let mut missing_qm = full.to_vec();
|
||||
missing_qm.push("--qm-prices");
|
||||
let err = parse_args(&to_args(&missing_qm)).unwrap_err();
|
||||
assert!(err.contains("missing value for flag '--qm-prices'"), "{err}");
|
||||
|
||||
// Unknown flag.
|
||||
let mut unk = full.to_vec();
|
||||
unk.extend(["--bogus", "1"]);
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ pub mod bson_ceo_shorts;
|
|||
pub mod bson_eod_prices;
|
||||
pub mod bson_qm_actions;
|
||||
pub mod bson_qm_events;
|
||||
pub mod bson_qm_prices;
|
||||
pub mod bson_stream;
|
||||
pub mod bson_te_market_data;
|
||||
pub mod cli;
|
||||
|
|
@ -56,13 +57,18 @@ pub use bson_qm_events::{
|
|||
DEFAULT_EARNINGS_KEY_FIELD, DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD,
|
||||
DEFAULT_FILINGS_TIMEFILED_FIELD,
|
||||
};
|
||||
pub use bson_qm_prices::{
|
||||
decode_qm_price_buffer, decode_qm_price_bytes, decode_qm_price_doc, BsonQmPriceDecodeStats,
|
||||
BsonQmPriceError, RawQmPrice, FIELD_SHARE_VOLUME,
|
||||
};
|
||||
pub use bson_stream::{
|
||||
decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_price_chunks,
|
||||
decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream,
|
||||
decode_qm_earnings_chunks, decode_qm_earnings_stream, decode_qm_filings_chunks,
|
||||
decode_qm_filings_stream, decode_qm_split_chunks, decode_qm_split_stream,
|
||||
decode_te_market_data_chunks, decode_te_market_data_stream, BsonCeoShortsStreamError,
|
||||
BsonQmEventsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader,
|
||||
decode_qm_filings_stream, decode_qm_price_chunks, decode_qm_price_stream,
|
||||
decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks,
|
||||
decode_te_market_data_stream, BsonCeoShortsStreamError, BsonQmEventsStreamError,
|
||||
BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader,
|
||||
DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||
};
|
||||
pub use bson_te_market_data::{
|
||||
|
|
@ -181,8 +187,8 @@ pub use curate_corporate_actions::{
|
|||
pub mod run_curate_bars;
|
||||
pub use run_curate_bars::{
|
||||
format_curate_bars_report, load_listing_currencies_tsv, load_provider_mapping_tsv,
|
||||
run_curate_bars_1d, CurateBars1dArgs, CurateBars1dRunReport, RunCurateBarsError,
|
||||
SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
run_curate_bars_1d, CurateBars1dArgs, CurateBars1dRunReport, QmVolumeRekeyStats,
|
||||
RunCurateBarsError, SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
|
||||
pub mod run_curate_adj;
|
||||
|
|
|
|||
|
|
@ -740,11 +740,13 @@ fn main() -> ExitCode {
|
|||
};
|
||||
println!("curate-etl bench-curate-bars-cmd");
|
||||
println!(
|
||||
" input: rows={} eod_bytes={} splits_docs={} splits_bytes={} keys={}",
|
||||
" input: rows={} eod_bytes={} splits_docs={} splits_bytes={} qm_docs={} qm_bytes={} keys={}",
|
||||
report.rows,
|
||||
report.eod_bytes_read,
|
||||
report.splits_docs_framed,
|
||||
report.splits_bytes_read,
|
||||
report.qm_docs_framed,
|
||||
report.qm_bytes_read,
|
||||
report.key_count
|
||||
);
|
||||
println!(
|
||||
|
|
@ -757,6 +759,22 @@ fn main() -> ExitCode {
|
|||
report.buffered_bar_bytes,
|
||||
report.bytes_per_buffered_bar
|
||||
);
|
||||
println!(
|
||||
" qm: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s attached={} unmapped={} no_eod_partner={} rejected={} checked={} within_tol={} mismatched={} (injected={}) unchecked={} samples={}",
|
||||
report.qm_decode_rekey_elapsed_ms,
|
||||
report.qm_decode_rekey_docs_per_sec,
|
||||
report.qm_input_mb_per_sec,
|
||||
report.qm_rekey.qm_attached,
|
||||
report.qm_rekey.qm_unmapped_qm,
|
||||
report.qm_rekey.qm_no_eod_partner,
|
||||
report.qm_prices_decode.rejected_total(),
|
||||
report.curate_stats.builder.volume_checked,
|
||||
report.curate_stats.builder.volume_within_tolerance,
|
||||
report.curate_stats.builder.volume_mismatched,
|
||||
report.injected_mismatches,
|
||||
report.curate_stats.builder.volume_unchecked,
|
||||
report.mismatch_samples_out
|
||||
);
|
||||
println!(
|
||||
" curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) listings_out={} unmapped={} missing_curr={} ts_oor={} coll_collapsed={} coll_dropped={}",
|
||||
report.curate_elapsed_ms,
|
||||
|
|
|
|||
|
|
@ -29,17 +29,20 @@ use std::path::{Path, PathBuf};
|
|||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::bars::EodDailyBar;
|
||||
use crate::bars::{EodDailyBar, QmRawVolume, VolumeMismatchSample};
|
||||
use crate::bson_eod_prices::{parse_ymd_strict_days, BsonEodDecodeStats};
|
||||
use crate::bson_qm_actions::BsonQmActionDecodeStats;
|
||||
use crate::bson_qm_prices::BsonQmPriceDecodeStats;
|
||||
use crate::bson_stream::{
|
||||
decode_eod_price_chunks, decode_qm_split_chunks, BsonStreamError, RawBsonChunkReader,
|
||||
decode_eod_price_chunks, decode_qm_price_chunks, decode_qm_split_chunks, BsonStreamError,
|
||||
RawBsonChunkReader,
|
||||
};
|
||||
use crate::curate_bars::{
|
||||
curate_and_write_bars_1d, curate_bars_1d, CurateBars1dStats, CurateBarsWriteError,
|
||||
};
|
||||
use crate::parquet_bars::{write_bars_1d_dataset, Bars1dWriteOptions, Bars1dWriteStats};
|
||||
use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable};
|
||||
use crate::shorts::epoch_days_to_ymd;
|
||||
use crate::split::{SplitError, SplitEvent, SplitTable};
|
||||
|
||||
/// Default relative volume tolerance passed to `curate_bars_1d` (matches `bench-curate-bars`).
|
||||
|
|
@ -50,6 +53,7 @@ pub const DEFAULT_CURATE_BARS_REL_TOLERANCE: f64 = 0.01;
|
|||
pub struct CurateBars1dArgs {
|
||||
pub eod_prices: PathBuf,
|
||||
pub qm_splits: PathBuf,
|
||||
pub qm_prices: Option<PathBuf>,
|
||||
pub provider_mapping: PathBuf,
|
||||
pub listing_currencies: PathBuf,
|
||||
pub out_dir: PathBuf,
|
||||
|
|
@ -80,6 +84,27 @@ pub struct SplitRekeyStats {
|
|||
pub split_events_attached: usize,
|
||||
}
|
||||
|
||||
/// Accounting counters for date-aware re-keying of `qmPrices`
|
||||
/// (`qmSearchCode` -> `listing_id` -> `eodSearchCode`).
|
||||
///
|
||||
/// Conservation invariants (paired with `qm_prices_decode: BsonQmPriceDecodeStats` and
|
||||
/// `curate_stats.builder: Bars1dStats`):
|
||||
/// - `qm_in == qm_attached + qm_unmapped_qm + qm_no_eod_partner + qm_prices_decode.rejected_total()`
|
||||
/// - `qm_volumes_attached == curate_stats.builder.qm_rows_in`
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct QmVolumeRekeyStats {
|
||||
/// Total `qmPrices` documents framed and fed into the decoder (`== qm_prices_decode.docs_in`).
|
||||
pub qm_in: usize,
|
||||
/// Decoded `qmPrices` rows whose `("qm", qm_search_code, session_date)` had no mapping.
|
||||
pub qm_unmapped_qm: usize,
|
||||
/// Mapped `qmPrices` rows whose `listing_id` had no `"eod"` mapping covering `session_date`.
|
||||
pub qm_no_eod_partner: usize,
|
||||
/// Decoded `qmPrices` rows attached to at least one date-covering `"eod"` `source_id`.
|
||||
pub qm_attached: usize,
|
||||
/// Total `QmRawVolume<Arc<str>>` observations pushed into `build_bars_1d` (`== builder.qm_rows_in`).
|
||||
pub qm_volumes_attached: usize,
|
||||
}
|
||||
|
||||
/// Full run report produced by [`run_curate_bars_1d`].
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateBars1dRunReport {
|
||||
|
|
@ -90,6 +115,12 @@ pub struct CurateBars1dRunReport {
|
|||
pub splits_bytes_read: u64,
|
||||
pub splits_decode: BsonQmActionDecodeStats,
|
||||
pub split_rekey: SplitRekeyStats,
|
||||
pub qm_prices_present: bool,
|
||||
pub qm_prices_docs_framed: u64,
|
||||
pub qm_prices_bytes_read: u64,
|
||||
pub qm_prices_decode: BsonQmPriceDecodeStats,
|
||||
pub qm_rekey: QmVolumeRekeyStats,
|
||||
pub buffered_qm_bytes: usize,
|
||||
pub bars_unmapped_source_dropped: usize,
|
||||
pub buffered_bars: usize,
|
||||
/// Approximate heap bytes occupied by the buffered `Vec<EodDailyBar<Arc<str>>>` capacity plus
|
||||
|
|
@ -97,6 +128,7 @@ pub struct CurateBars1dRunReport {
|
|||
pub buffered_bar_bytes: usize,
|
||||
pub curate_stats: CurateBars1dStats,
|
||||
pub write_stats: Bars1dWriteStats,
|
||||
pub mismatch_samples: Vec<VolumeMismatchSample<Arc<str>>>,
|
||||
pub elapsed_secs: f64,
|
||||
}
|
||||
|
||||
|
|
@ -105,6 +137,7 @@ pub struct CurateBars1dRunReport {
|
|||
pub(crate) struct CurateBars1dTimedRun {
|
||||
pub report: CurateBars1dRunReport,
|
||||
pub decode_elapsed_secs: f64,
|
||||
pub qm_decode_rekey_elapsed_secs: f64,
|
||||
pub curate_elapsed_secs: f64,
|
||||
pub write_elapsed_secs: f64,
|
||||
}
|
||||
|
|
@ -438,6 +471,7 @@ struct LoadedCurateBarsInputs {
|
|||
currencies: HashMap<i32, Cow<'static, str>>,
|
||||
splits: SplitTable<Arc<str>>,
|
||||
bars: Vec<EodDailyBar<Arc<str>>>,
|
||||
qm_volumes: Vec<QmRawVolume<Arc<str>>>,
|
||||
eod_docs_framed: u64,
|
||||
eod_bytes_read: u64,
|
||||
eod_decode: BsonEodDecodeStats,
|
||||
|
|
@ -445,11 +479,32 @@ struct LoadedCurateBarsInputs {
|
|||
splits_bytes_read: u64,
|
||||
splits_decode: BsonQmActionDecodeStats,
|
||||
split_rekey: SplitRekeyStats,
|
||||
qm_prices_present: bool,
|
||||
qm_prices_docs_framed: u64,
|
||||
qm_prices_bytes_read: u64,
|
||||
qm_prices_decode: BsonQmPriceDecodeStats,
|
||||
qm_rekey: QmVolumeRekeyStats,
|
||||
buffered_qm_bytes: usize,
|
||||
qm_decode_rekey_elapsed_secs: f64,
|
||||
bars_unmapped_source_dropped: usize,
|
||||
buffered_bars: usize,
|
||||
buffered_bar_bytes: usize,
|
||||
}
|
||||
|
||||
struct EodListingRange {
|
||||
valid_from: i32,
|
||||
valid_to: Option<i32>,
|
||||
key: Arc<str>,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn valid_to_sort_key(valid_to: Option<i32>) -> (u8, i32) {
|
||||
match valid_to {
|
||||
Some(to) => (0, to),
|
||||
None => (1, i32::MAX),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_out_dir(out_dir: &Path) -> Result<(), RunCurateBarsError> {
|
||||
if out_dir.exists() && !out_dir.is_dir() {
|
||||
return Err(RunCurateBarsError::InvalidOutDir {
|
||||
|
|
@ -586,8 +641,13 @@ fn load_and_decode_inputs(
|
|||
let currencies = load_listing_currencies_tsv(&args.listing_currencies)?;
|
||||
|
||||
// Build interned `"eod"` key set and reverse `listing_id -> [eod source_id]` index once.
|
||||
// When `--qm-prices` is provided, also build a date-aware reverse index
|
||||
// `listing_id -> [(valid_from, valid_to, Arc<str>)]` so reused EOD tickers never receive
|
||||
// cross-check observations outside their mapping range.
|
||||
let mut eod_keys: HashSet<Arc<str>> = HashSet::new();
|
||||
let mut eod_by_listing: HashMap<i32, Vec<Arc<str>>> = HashMap::new();
|
||||
let mut eod_ranges_by_listing: HashMap<i32, Vec<EodListingRange>> = HashMap::new();
|
||||
let track_eod_ranges = args.qm_prices.is_some();
|
||||
for row in &mapping_rows {
|
||||
if row.source == "eod" {
|
||||
let key = match eod_keys.get(row.source_id.as_str()) {
|
||||
|
|
@ -598,6 +658,16 @@ fn load_and_decode_inputs(
|
|||
arc
|
||||
}
|
||||
};
|
||||
if track_eod_ranges {
|
||||
eod_ranges_by_listing
|
||||
.entry(row.listing_id)
|
||||
.or_default()
|
||||
.push(EodListingRange {
|
||||
valid_from: row.valid_from,
|
||||
valid_to: row.valid_to,
|
||||
key: Arc::clone(&key),
|
||||
});
|
||||
}
|
||||
eod_by_listing.entry(row.listing_id).or_default().push(key);
|
||||
}
|
||||
}
|
||||
|
|
@ -605,6 +675,14 @@ fn load_and_decode_inputs(
|
|||
partners.sort_unstable();
|
||||
partners.dedup();
|
||||
}
|
||||
for ranges in eod_ranges_by_listing.values_mut() {
|
||||
ranges.sort_unstable_by(|a, b| {
|
||||
a.valid_from
|
||||
.cmp(&b.valid_from)
|
||||
.then_with(|| valid_to_sort_key(a.valid_to).cmp(&valid_to_sort_key(b.valid_to)))
|
||||
.then_with(|| a.key.cmp(&b.key))
|
||||
});
|
||||
}
|
||||
|
||||
let mapping = ProviderMappingTable::from_rows(mapping_rows).map_err(|source| {
|
||||
RunCurateBarsError::ProviderMapping {
|
||||
|
|
@ -718,11 +796,78 @@ fn load_and_decode_inputs(
|
|||
let buffered_bar_bytes =
|
||||
bars.capacity() * size_of::<EodDailyBar<Arc<str>>>() + interned_key_bytes;
|
||||
|
||||
// Optionally stream `qmPrices` and date-aware re-key into interned `"eod"` keys.
|
||||
let mut qm_volumes: Vec<QmRawVolume<Arc<str>>> = Vec::new();
|
||||
let mut qm_prices_present = false;
|
||||
let mut qm_prices_docs_framed = 0u64;
|
||||
let mut qm_prices_bytes_read = 0u64;
|
||||
let mut qm_prices_decode = BsonQmPriceDecodeStats::default();
|
||||
let mut qm_rekey = QmVolumeRekeyStats::default();
|
||||
let mut qm_decode_rekey_elapsed_secs = 0.0f64;
|
||||
|
||||
if let Some(qm_prices_path) = &args.qm_prices {
|
||||
qm_prices_present = true;
|
||||
let qm_start = Instant::now();
|
||||
let qm_file =
|
||||
File::open(qm_prices_path).map_err(|source| RunCurateBarsError::OpenInput {
|
||||
label: "qm-prices",
|
||||
path: qm_prices_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
let mut qm_reader = RawBsonChunkReader::new(qm_file);
|
||||
qm_prices_decode = decode_qm_price_chunks(
|
||||
&mut qm_reader,
|
||||
|raw_price| {
|
||||
let Some(listing_id) =
|
||||
mapping.resolve("qm", raw_price.qm_search_code, raw_price.session_date)
|
||||
else {
|
||||
qm_rekey.qm_unmapped_qm += 1;
|
||||
return;
|
||||
};
|
||||
let mut matched_eod = 0usize;
|
||||
if let Some(ranges) = eod_ranges_by_listing.get(&listing_id) {
|
||||
for range in ranges {
|
||||
if raw_price.session_date >= range.valid_from
|
||||
&& range
|
||||
.valid_to
|
||||
.is_none_or(|to| raw_price.session_date <= to)
|
||||
{
|
||||
qm_volumes.push(QmRawVolume {
|
||||
key: Arc::clone(&range.key),
|
||||
session_date: raw_price.session_date,
|
||||
share_volume: raw_price.share_volume,
|
||||
});
|
||||
matched_eod += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if matched_eod == 0 {
|
||||
qm_rekey.qm_no_eod_partner += 1;
|
||||
} else {
|
||||
qm_rekey.qm_attached += 1;
|
||||
qm_rekey.qm_volumes_attached += matched_eod;
|
||||
}
|
||||
},
|
||||
|_offset, _err| {},
|
||||
)
|
||||
.map_err(|source| RunCurateBarsError::BsonStream {
|
||||
label: "qm-prices",
|
||||
path: qm_prices_path.clone(),
|
||||
source,
|
||||
})?;
|
||||
qm_prices_docs_framed = qm_reader.docs_framed();
|
||||
qm_prices_bytes_read = qm_reader.bytes_read();
|
||||
qm_rekey.qm_in = qm_prices_decode.docs_in;
|
||||
qm_decode_rekey_elapsed_secs = qm_start.elapsed().as_secs_f64();
|
||||
}
|
||||
let buffered_qm_bytes = qm_volumes.capacity() * size_of::<QmRawVolume<Arc<str>>>();
|
||||
|
||||
Ok(LoadedCurateBarsInputs {
|
||||
mapping,
|
||||
currencies,
|
||||
splits,
|
||||
bars,
|
||||
qm_volumes,
|
||||
eod_docs_framed,
|
||||
eod_bytes_read,
|
||||
eod_decode,
|
||||
|
|
@ -730,6 +875,13 @@ fn load_and_decode_inputs(
|
|||
splits_bytes_read,
|
||||
splits_decode,
|
||||
split_rekey,
|
||||
qm_prices_present,
|
||||
qm_prices_docs_framed,
|
||||
qm_prices_bytes_read,
|
||||
qm_prices_decode,
|
||||
qm_rekey,
|
||||
buffered_qm_bytes,
|
||||
qm_decode_rekey_elapsed_secs,
|
||||
bars_unmapped_source_dropped,
|
||||
buffered_bars,
|
||||
buffered_bar_bytes,
|
||||
|
|
@ -747,7 +899,7 @@ pub fn run_curate_bars_1d(
|
|||
&args.out_dir,
|
||||
loaded.bars,
|
||||
&loaded.splits,
|
||||
std::iter::empty(),
|
||||
loaded.qm_volumes,
|
||||
args.rel_tolerance,
|
||||
&loaded.mapping,
|
||||
"eod",
|
||||
|
|
@ -767,11 +919,18 @@ pub fn run_curate_bars_1d(
|
|||
splits_bytes_read: loaded.splits_bytes_read,
|
||||
splits_decode: loaded.splits_decode,
|
||||
split_rekey: loaded.split_rekey,
|
||||
qm_prices_present: loaded.qm_prices_present,
|
||||
qm_prices_docs_framed: loaded.qm_prices_docs_framed,
|
||||
qm_prices_bytes_read: loaded.qm_prices_bytes_read,
|
||||
qm_prices_decode: loaded.qm_prices_decode,
|
||||
qm_rekey: loaded.qm_rekey,
|
||||
buffered_qm_bytes: loaded.buffered_qm_bytes,
|
||||
bars_unmapped_source_dropped: loaded.bars_unmapped_source_dropped,
|
||||
buffered_bars: loaded.buffered_bars,
|
||||
buffered_bar_bytes: loaded.buffered_bar_bytes,
|
||||
curate_stats: write_report.curate_stats,
|
||||
write_stats: write_report.write_stats,
|
||||
mismatch_samples: write_report.mismatch_samples,
|
||||
elapsed_secs: start.elapsed().as_secs_f64(),
|
||||
})
|
||||
}
|
||||
|
|
@ -791,7 +950,7 @@ pub(crate) fn run_curate_bars_1d_timed(
|
|||
let curated = curate_bars_1d(
|
||||
loaded.bars,
|
||||
&loaded.splits,
|
||||
std::iter::empty(),
|
||||
loaded.qm_volumes,
|
||||
args.rel_tolerance,
|
||||
&loaded.mapping,
|
||||
"eod",
|
||||
|
|
@ -820,17 +979,25 @@ pub(crate) fn run_curate_bars_1d_timed(
|
|||
splits_bytes_read: loaded.splits_bytes_read,
|
||||
splits_decode: loaded.splits_decode,
|
||||
split_rekey: loaded.split_rekey,
|
||||
qm_prices_present: loaded.qm_prices_present,
|
||||
qm_prices_docs_framed: loaded.qm_prices_docs_framed,
|
||||
qm_prices_bytes_read: loaded.qm_prices_bytes_read,
|
||||
qm_prices_decode: loaded.qm_prices_decode,
|
||||
qm_rekey: loaded.qm_rekey,
|
||||
buffered_qm_bytes: loaded.buffered_qm_bytes,
|
||||
bars_unmapped_source_dropped: loaded.bars_unmapped_source_dropped,
|
||||
buffered_bars: loaded.buffered_bars,
|
||||
buffered_bar_bytes: loaded.buffered_bar_bytes,
|
||||
curate_stats: curated.stats,
|
||||
write_stats,
|
||||
mismatch_samples: curated.mismatch_samples,
|
||||
elapsed_secs: total_start.elapsed().as_secs_f64(),
|
||||
};
|
||||
|
||||
Ok(CurateBars1dTimedRun {
|
||||
report,
|
||||
decode_elapsed_secs,
|
||||
qm_decode_rekey_elapsed_secs: loaded.qm_decode_rekey_elapsed_secs,
|
||||
curate_elapsed_secs,
|
||||
write_elapsed_secs,
|
||||
})
|
||||
|
|
@ -840,6 +1007,8 @@ pub(crate) fn run_curate_bars_1d_timed(
|
|||
///
|
||||
/// Only the final `timing:` line contains wall-clock time (`elapsed_secs`).
|
||||
pub fn format_curate_bars_report(report: &CurateBars1dRunReport) -> String {
|
||||
use std::fmt::Write as _;
|
||||
|
||||
let years = if report.write_stats.rows_by_year.is_empty() {
|
||||
"none".to_string()
|
||||
} else {
|
||||
|
|
@ -852,7 +1021,7 @@ pub fn format_curate_bars_report(report: &CurateBars1dRunReport) -> String {
|
|||
.join(" ")
|
||||
};
|
||||
|
||||
format!(
|
||||
let mut out = format!(
|
||||
"curate-etl curate-bars-1d\n\
|
||||
\x20 eod_bson: docs_framed={} bytes_read={} docs_in={} decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\
|
||||
\x20 splits_bson: docs_framed={} bytes_read={} docs_in={} decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})\n\
|
||||
|
|
@ -861,8 +1030,7 @@ pub fn format_curate_bars_report(report: &CurateBars1dRunReport) -> String {
|
|||
\x20 builder: bars_in={} rows_out={} keys_out={} invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} dup_collapsed={} dup_conflict_dropped={}\n\
|
||||
\x20 curate: rows_in={} rows_out={} listings_out={} dropped_unmapped={} dropped_missing_currency={} dropped_ts_out_of_range={} listing_collision_collapsed={} listing_collision_dropped={}\n\
|
||||
\x20 write: rows_written={} files_written={} row_groups_written={} bytes_written={}\n\
|
||||
\x20 years: {years}\n\
|
||||
\x20 timing: elapsed_secs={:.6}",
|
||||
\x20 years: {years}\n",
|
||||
report.eod_docs_framed,
|
||||
report.eod_bytes_read,
|
||||
report.eod_decode.docs_in,
|
||||
|
|
@ -916,8 +1084,63 @@ pub fn format_curate_bars_report(report: &CurateBars1dRunReport) -> String {
|
|||
report.write_stats.files_written,
|
||||
report.write_stats.row_groups_written,
|
||||
report.write_stats.bytes_written,
|
||||
report.elapsed_secs,
|
||||
)
|
||||
);
|
||||
|
||||
if report.qm_prices_present {
|
||||
let b = &report.curate_stats.builder;
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" qm_bson: docs_framed={} bytes_read={} docs_in={} decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} corrupt={})",
|
||||
report.qm_prices_docs_framed,
|
||||
report.qm_prices_bytes_read,
|
||||
report.qm_prices_decode.docs_in,
|
||||
report.qm_prices_decode.decoded,
|
||||
report.qm_prices_decode.rejected_total(),
|
||||
report.qm_prices_decode.rejected_missing_field,
|
||||
report.qm_prices_decode.rejected_empty_field,
|
||||
report.qm_prices_decode.rejected_wrong_type,
|
||||
report.qm_prices_decode.rejected_malformed_date,
|
||||
report.qm_prices_decode.rejected_corrupt_document,
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" qm_rekey: qm_in={} qm_attached={} qm_unmapped_qm={} qm_no_eod_partner={} qm_volumes_attached={} buffered_qm_bytes={}",
|
||||
report.qm_rekey.qm_in,
|
||||
report.qm_rekey.qm_attached,
|
||||
report.qm_rekey.qm_unmapped_qm,
|
||||
report.qm_rekey.qm_no_eod_partner,
|
||||
report.qm_rekey.qm_volumes_attached,
|
||||
report.buffered_qm_bytes,
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" qm_check: qm_rows_in={} qm_unique_partners={} qm_invalid_vol={} qm_dup_collapsed={} qm_dup_conflict={} volume_checked={} volume_within_tolerance={} volume_mismatched={} volume_unchecked={} max_rel_diff={:.6} mismatch_samples={}",
|
||||
b.qm_rows_in,
|
||||
b.qm_unique_partners,
|
||||
b.qm_invalid_volume_dropped,
|
||||
b.qm_duplicate_collapsed,
|
||||
b.qm_duplicate_conflict_dropped,
|
||||
b.volume_checked,
|
||||
b.volume_within_tolerance,
|
||||
b.volume_mismatched,
|
||||
b.volume_unchecked,
|
||||
b.max_rel_diff,
|
||||
report.mismatch_samples.len(),
|
||||
);
|
||||
for sample in &report.mismatch_samples {
|
||||
let (y, m, d) = epoch_days_to_ymd(sample.session_date);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" qm_mismatch: key={} session_date={y:04}-{m:02}-{d:02} volume={:.6} share_volume={:.6} rel={:.6}",
|
||||
sample.key, sample.volume, sample.share_volume, sample.rel,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
out.push_str(" qm_check: qm_prices=absent\n");
|
||||
}
|
||||
|
||||
let _ = write!(out, " timing: elapsed_secs={:.6}", report.elapsed_secs);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
|||
|
|
@ -194,6 +194,7 @@ fn end_to_end_happy_path_nvda_cross_provider_split() {
|
|||
let args = CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_path,
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_dir.clone(),
|
||||
|
|
@ -307,6 +308,7 @@ fn split_rekey_edge_cases_and_conservation_invariants() {
|
|||
let args = CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_path,
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_dir.clone(),
|
||||
|
|
@ -409,6 +411,7 @@ fn qm_alias_splits_collapse_identical_and_reject_conflicting_with_parquet_readba
|
|||
let report = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_path.clone(),
|
||||
qm_splits: splits_ok,
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out_ok.clone(),
|
||||
|
|
@ -456,6 +459,7 @@ fn qm_alias_splits_collapse_identical_and_reject_conflicting_with_parquet_readba
|
|||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_conflict,
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_conflict.clone(),
|
||||
|
|
@ -526,6 +530,7 @@ fn early_filter_missing_currency_and_full_bar_accounting() {
|
|||
let args = CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_path,
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_dir.clone(),
|
||||
|
|
@ -656,6 +661,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() {
|
|||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: dir.path().join("does_not_exist.bson"),
|
||||
qm_splits: valid_splits.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: valid_map.clone(),
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out1.clone(),
|
||||
|
|
@ -674,6 +680,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() {
|
|||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: trunc_eod,
|
||||
qm_splits: valid_splits.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: valid_map.clone(),
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out2.clone(),
|
||||
|
|
@ -699,6 +706,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() {
|
|||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: huge_eod,
|
||||
qm_splits: valid_splits.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: valid_map.clone(),
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out3.clone(),
|
||||
|
|
@ -724,6 +732,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() {
|
|||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
qm_splits: valid_splits.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: bad_map,
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out4.clone(),
|
||||
|
|
@ -745,6 +754,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() {
|
|||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
qm_splits: valid_splits.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: overlap_map,
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out5.clone(),
|
||||
|
|
@ -766,6 +776,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() {
|
|||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
qm_splits: valid_splits.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: valid_map.clone(),
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out_file.clone(),
|
||||
|
|
@ -784,6 +795,7 @@ fn failure_modes_return_typed_errors_and_leave_no_partial_dataset() {
|
|||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: valid_eod,
|
||||
qm_splits: valid_splits,
|
||||
qm_prices: None,
|
||||
provider_mapping: valid_map,
|
||||
listing_currencies: valid_curr,
|
||||
out_dir: out_obstructed.clone(),
|
||||
|
|
@ -856,6 +868,7 @@ fn deterministic_parquet_and_report_across_runs_and_shuffled_inputs_and_timed_pa
|
|||
let r1 = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_a.clone(),
|
||||
qm_splits: splits_a.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out1.clone(),
|
||||
|
|
@ -865,6 +878,7 @@ fn deterministic_parquet_and_report_across_runs_and_shuffled_inputs_and_timed_pa
|
|||
let r2 = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_a.clone(),
|
||||
qm_splits: splits_a.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out2.clone(),
|
||||
|
|
@ -874,6 +888,7 @@ fn deterministic_parquet_and_report_across_runs_and_shuffled_inputs_and_timed_pa
|
|||
let r3 = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_shuf,
|
||||
qm_splits: splits_shuf,
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out3.clone(),
|
||||
|
|
@ -883,6 +898,7 @@ fn deterministic_parquet_and_report_across_runs_and_shuffled_inputs_and_timed_pa
|
|||
let rt = run_curate_bars_1d_timed(&CurateBars1dArgs {
|
||||
eod_prices: eod_a,
|
||||
qm_splits: splits_a,
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_timed.clone(),
|
||||
|
|
@ -932,6 +948,7 @@ fn rerun_with_narrower_year_range_replaces_emitted_year_and_leaves_older_year_un
|
|||
let r1 = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_full,
|
||||
qm_splits: splits_path.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out_dir.clone(),
|
||||
|
|
@ -953,6 +970,7 @@ fn rerun_with_narrower_year_range_replaces_emitted_year_and_leaves_older_year_un
|
|||
let r2 = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_2024,
|
||||
qm_splits: splits_path,
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_dir.clone(),
|
||||
|
|
@ -995,6 +1013,7 @@ fn failed_rerun_over_existing_dataset_leaves_published_partitions_byte_identical
|
|||
run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
qm_splits: valid_splits.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: valid_map.clone(),
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out_dir.clone(),
|
||||
|
|
@ -1024,6 +1043,7 @@ fn failed_rerun_over_existing_dataset_leaves_published_partitions_byte_identical
|
|||
assert!(run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: trunc_eod,
|
||||
qm_splits: valid_splits.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: valid_map.clone(),
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out_dir.clone(),
|
||||
|
|
@ -1041,6 +1061,7 @@ fn failed_rerun_over_existing_dataset_leaves_published_partitions_byte_identical
|
|||
assert!(run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: valid_eod.clone(),
|
||||
qm_splits: conflict_splits,
|
||||
qm_prices: None,
|
||||
provider_mapping: valid_map.clone(),
|
||||
listing_currencies: valid_curr.clone(),
|
||||
out_dir: out_dir.clone(),
|
||||
|
|
@ -1055,6 +1076,7 @@ fn failed_rerun_over_existing_dataset_leaves_published_partitions_byte_identical
|
|||
assert!(run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: valid_eod,
|
||||
qm_splits: valid_splits,
|
||||
qm_prices: None,
|
||||
provider_mapping: valid_map,
|
||||
listing_currencies: bad_curr,
|
||||
out_dir: out_dir.clone(),
|
||||
|
|
@ -1080,6 +1102,7 @@ fn empty_and_all_unmapped_inputs_publish_nothing_and_account_cleanly() {
|
|||
let report_empty = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: empty_eod,
|
||||
qm_splits: empty_splits.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: empty_map,
|
||||
listing_currencies: empty_curr,
|
||||
out_dir: out_empty.clone(),
|
||||
|
|
@ -1108,6 +1131,7 @@ fn empty_and_all_unmapped_inputs_publish_nothing_and_account_cleanly() {
|
|||
let report_unmapped = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: unmapped_eod,
|
||||
qm_splits: empty_splits,
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_unmapped.clone(),
|
||||
|
|
@ -1159,6 +1183,7 @@ fn multi_forward_and_reverse_split_math_preserves_ohlc() {
|
|||
let report = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_path,
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_dir.clone(),
|
||||
|
|
@ -1253,6 +1278,7 @@ fn tsv_loaders_reject_strict_edge_cases_and_accept_no_trailing_newline() {
|
|||
let err = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: empty_eod,
|
||||
qm_splits: empty_splits,
|
||||
qm_prices: None,
|
||||
provider_mapping: inv_range_map,
|
||||
listing_currencies: no_nl_curr,
|
||||
out_dir: dir.path().join("out_inv_range"),
|
||||
|
|
@ -1267,3 +1293,336 @@ fn tsv_loaders_reject_strict_edge_cases_and_accept_no_trailing_newline() {
|
|||
}
|
||||
));
|
||||
}
|
||||
|
||||
fn qm_price_doc_f64(code: &str, date: &str, share_volume: f64) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("sharevolume"), share_volume);
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
fn qm_price_doc_i32(code: &str, date: &str, share_volume: i32) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("sharevolume"), share_volume);
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
fn qm_price_doc_i64(code: &str, date: &str, share_volume: i64) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("sharevolume"), share_volume);
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
fn assert_qm_accounting_invariants(report: &CurateBars1dRunReport) {
|
||||
assert_eq!(
|
||||
report.qm_prices_decode.docs_in,
|
||||
report.qm_prices_decode.decoded + report.qm_prices_decode.rejected_total(),
|
||||
"qm_prices_decode conservation violated: {:?}",
|
||||
report.qm_prices_decode
|
||||
);
|
||||
assert_eq!(
|
||||
report.qm_rekey.qm_in, report.qm_prices_decode.docs_in,
|
||||
"qm_in must match qm_prices_decode.docs_in"
|
||||
);
|
||||
assert_eq!(
|
||||
report.qm_rekey.qm_in,
|
||||
report.qm_rekey.qm_attached
|
||||
+ report.qm_rekey.qm_unmapped_qm
|
||||
+ report.qm_rekey.qm_no_eod_partner
|
||||
+ report.qm_prices_decode.rejected_total(),
|
||||
"qm_rekey conservation violated: {:?}",
|
||||
report.qm_rekey
|
||||
);
|
||||
let b = &report.curate_stats.builder;
|
||||
assert_eq!(
|
||||
report.qm_rekey.qm_volumes_attached, b.qm_rows_in,
|
||||
"qm_volumes_attached must equal builder.qm_rows_in"
|
||||
);
|
||||
assert_eq!(
|
||||
b.volume_checked + b.volume_unchecked,
|
||||
b.rows_out,
|
||||
"volume_checked + volume_unchecked != rows_out"
|
||||
);
|
||||
assert_eq!(
|
||||
b.volume_within_tolerance + b.volume_mismatched,
|
||||
b.volume_checked,
|
||||
"volume_within_tolerance + volume_mismatched != volume_checked"
|
||||
);
|
||||
assert_eq!(
|
||||
b.qm_rows_in,
|
||||
b.qm_unique_partners
|
||||
+ b.qm_invalid_volume_dropped
|
||||
+ b.qm_duplicate_collapsed
|
||||
+ b.qm_duplicate_conflict_dropped,
|
||||
"builder qm conservation violated"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qm_prices_nvda_split_cross_check_mismatch_samples_and_readonly_parquet_invariance() {
|
||||
let dir = TestTempDir::new("qm-nvda-split");
|
||||
let eod_path = dir.path().join("eodPrices.bson");
|
||||
let splits_path = dir.path().join("qmSplits.bson");
|
||||
let qm_path = dir.path().join("qmPrices.bson");
|
||||
let qm_shuf_path = dir.path().join("qmPrices_shuf.bson");
|
||||
let map_path = dir.path().join("provider_mapping.tsv");
|
||||
let curr_path = dir.path().join("listing_currencies.tsv");
|
||||
|
||||
write_bytes(
|
||||
&map_path,
|
||||
b"eod\tNVDA.US\t2020-01-01\t\t101\n\
|
||||
qm\tNVDA\t2020-01-01\t\t101\n",
|
||||
);
|
||||
write_bytes(&curr_path, b"101\tUSD\n");
|
||||
|
||||
// 10:1 forward split on 2024-06-10.
|
||||
write_bytes(&splits_path, &split_doc("NVDA", "2024-06-10", 10.0));
|
||||
|
||||
// 5 EOD bars across 2023 and 2024.
|
||||
let eod_docs = [
|
||||
// 2023-12-29 (pre-split, factor=10 -> raw vol 30_000_000): conflicting QM dups -> unchecked
|
||||
eod_doc("NVDA.US", "2023-12-29", 495.0, 500.0, 490.0, 495.22, 300_000_000.0),
|
||||
// 2024-06-06 (pre-split, factor=10 -> raw vol 40_000_000): injected >1% mismatch (38_000_000 -> ~5.26%)
|
||||
eod_doc("NVDA.US", "2024-06-06", 1200.0, 1220.0, 1190.0, 1210.0, 400_000_000.0),
|
||||
// 2024-06-07 (pre-split, factor=10 -> raw vol 41_239_000): matches QM within 1%
|
||||
eod_doc("NVDA.US", "2024-06-07", 1197.7, 1216.92, 1180.22, 1208.88, 412_390_000.0),
|
||||
// 2024-06-10 (exact ex-date, factor=1 -> raw vol 314_162_700): matches QM exact (Int64)
|
||||
eod_doc("NVDA.US", "2024-06-10", 120.37, 123.10, 117.01, 121.79, 314_162_700.0),
|
||||
// 2024-06-11 (post-split, factor=1 -> raw vol 222_551_200): matches QM exact (Int32)
|
||||
eod_doc("NVDA.US", "2024-06-11", 121.77, 122.87, 118.74, 120.91, 222_551_200.0),
|
||||
];
|
||||
write_bytes(&eod_path, &eod_docs.concat());
|
||||
|
||||
let mut wrong_type_doc = RawDocumentBuf::new();
|
||||
wrong_type_doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
wrong_type_doc.append(cstr!("date"), "2024-06-07");
|
||||
wrong_type_doc.append(cstr!("sharevolume"), "not-numeric");
|
||||
|
||||
let qm_docs: Vec<Vec<u8>> = vec![
|
||||
qm_price_doc_f64("NVDA", "2023-12-29", 30_000_000.0),
|
||||
qm_price_doc_f64("NVDA", "2023-12-29", 30_500_000.0), // conflict -> both dropped -> unchecked
|
||||
qm_price_doc_f64("NVDA", "2024-06-06", 38_000_000.0), // >1% divergence
|
||||
qm_price_doc_f64("NVDA", "2024-06-07", 41_300_000.0), // ~0.148% diff -> within 1%
|
||||
qm_price_doc_i64("NVDA", "2024-06-10", 314_162_700), // exact Int64
|
||||
qm_price_doc_i32("NVDA", "2024-06-11", 222_551_200), // exact Int32
|
||||
qm_price_doc_f64("NVDA", "2024-06-07", -5.0), // invalid volume dropped by builder
|
||||
qm_price_doc_f64("NVDA", "2024-06-07", f64::NAN), // invalid volume dropped by builder
|
||||
wrong_type_doc.into_bytes(), // rejected by decoder
|
||||
];
|
||||
write_bytes(&qm_path, &qm_docs.concat());
|
||||
let mut shuf = qm_docs.clone();
|
||||
shuf.reverse();
|
||||
write_bytes(&qm_shuf_path, &shuf.concat());
|
||||
|
||||
let out_without = dir.path().join("out_without");
|
||||
let out_with = dir.path().join("out_with");
|
||||
let out_shuf = dir.path().join("out_shuf");
|
||||
let out_timed = dir.path().join("out_timed");
|
||||
|
||||
let r_without = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_path.clone(),
|
||||
qm_splits: splits_path.clone(),
|
||||
qm_prices: None,
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out_without.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let r_with = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_path.clone(),
|
||||
qm_splits: splits_path.clone(),
|
||||
qm_prices: Some(qm_path.clone()),
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out_with.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let r_shuf = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_path.clone(),
|
||||
qm_splits: splits_path.clone(),
|
||||
qm_prices: Some(qm_shuf_path),
|
||||
provider_mapping: map_path.clone(),
|
||||
listing_currencies: curr_path.clone(),
|
||||
out_dir: out_shuf.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let r_timed = run_curate_bars_1d_timed(&CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_path,
|
||||
qm_prices: Some(qm_path),
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: out_timed.clone(),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert!(!r_without.qm_prices_present);
|
||||
assert!(r_with.qm_prices_present);
|
||||
assert_qm_accounting_invariants(&r_with);
|
||||
assert_qm_accounting_invariants(&r_shuf);
|
||||
assert_qm_accounting_invariants(&r_timed.report);
|
||||
|
||||
assert_eq!(r_with.qm_prices_decode.docs_in, 9);
|
||||
assert_eq!(r_with.qm_prices_decode.decoded, 8);
|
||||
assert_eq!(r_with.qm_prices_decode.rejected_wrong_type, 1);
|
||||
assert_eq!(r_with.qm_rekey.qm_attached, 8);
|
||||
assert_eq!(r_with.qm_rekey.qm_volumes_attached, 8);
|
||||
|
||||
let b = &r_with.curate_stats.builder;
|
||||
assert_eq!(b.rows_out, 5);
|
||||
assert_eq!(b.qm_rows_in, 8);
|
||||
assert_eq!(b.qm_invalid_volume_dropped, 2);
|
||||
assert_eq!(b.qm_duplicate_conflict_dropped, 2);
|
||||
assert_eq!(b.qm_unique_partners, 4);
|
||||
assert_eq!(b.volume_checked, 4);
|
||||
assert_eq!(b.volume_within_tolerance, 3);
|
||||
assert_eq!(b.volume_mismatched, 1);
|
||||
assert_eq!(b.volume_unchecked, 1);
|
||||
|
||||
assert_eq!(r_with.mismatch_samples.len(), 1);
|
||||
let sample = &r_with.mismatch_samples[0];
|
||||
assert_eq!(sample.key.as_ref(), "NVDA.US");
|
||||
assert_eq!(sample.session_date, ymd_to_epoch_days(2024, 6, 6).unwrap());
|
||||
assert!((sample.volume - 40_000_000.0).abs() < 1e-6);
|
||||
assert!((sample.share_volume - 38_000_000.0).abs() < 1e-6);
|
||||
assert!(sample.rel > 0.05 && sample.rel < 0.06);
|
||||
|
||||
// Cross-check is strictly read-only: emitted Parquet files are byte-identical across all runs.
|
||||
for year in [2023, 2024] {
|
||||
let rel_path = format!("bars_1d/year={year}/part.parquet");
|
||||
let bytes_without = fs::read(out_without.join(&rel_path)).unwrap();
|
||||
let bytes_with = fs::read(out_with.join(&rel_path)).unwrap();
|
||||
let bytes_shuf = fs::read(out_shuf.join(&rel_path)).unwrap();
|
||||
let bytes_timed = fs::read(out_timed.join(&rel_path)).unwrap();
|
||||
assert_eq!(bytes_without, bytes_with, "Parquet bytes differed for {year}");
|
||||
assert_eq!(bytes_with, bytes_shuf, "Shuffled QM altered Parquet for {year}");
|
||||
assert_eq!(bytes_with, bytes_timed, "Timed run altered Parquet for {year}");
|
||||
}
|
||||
|
||||
// Report formatting assertions + determinism across shuffled qmPrices and timed run.
|
||||
let strip_timing = |s: &str| {
|
||||
s.lines()
|
||||
.filter(|l| !l.trim_start().starts_with("timing:"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
};
|
||||
let text_without = format_curate_bars_report(&r_without);
|
||||
let text_with = format_curate_bars_report(&r_with);
|
||||
let text_shuf = format_curate_bars_report(&r_shuf);
|
||||
let text_timed = format_curate_bars_report(&r_timed.report);
|
||||
|
||||
assert!(text_without.contains("qm_check: qm_prices=absent"), "{text_without}");
|
||||
assert!(text_with.contains("qm_bson:"), "{text_with}");
|
||||
assert!(text_with.contains("qm_rekey:"), "{text_with}");
|
||||
assert!(
|
||||
text_with.contains("volume_checked=4 volume_within_tolerance=3 volume_mismatched=1 volume_unchecked=1"),
|
||||
"{text_with}"
|
||||
);
|
||||
assert!(
|
||||
text_with.contains("qm_mismatch: key=NVDA.US session_date=2024-06-06"),
|
||||
"{text_with}"
|
||||
);
|
||||
assert_eq!(strip_timing(&text_with), strip_timing(&text_shuf));
|
||||
assert_eq!(strip_timing(&text_with), strip_timing(&text_timed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qm_prices_date_aware_rekey_reused_ticker_rename_alias_fanout_and_unmapped_counts() {
|
||||
let dir = TestTempDir::new("qm-date-aware-rekey");
|
||||
let eod_path = dir.path().join("eodPrices.bson");
|
||||
let splits_path = dir.path().join("qmSplits.bson");
|
||||
let qm_path = dir.path().join("qmPrices.bson");
|
||||
let map_path = dir.path().join("provider_mapping.tsv");
|
||||
let curr_path = dir.path().join("listing_currencies.tsv");
|
||||
|
||||
// Reused EOD ticker FB.US: listing 10 (2012-01-01..=2022-06-08), listing 20 (2025-01-01..).
|
||||
// Rename on listing 10: META.US (2022-06-09..).
|
||||
// Multi-EOD alias on listing 30: ALIAS_A.US & ALIAS_B.US both cover 2024-01-01..
|
||||
// QM-only listing 40: QMONLY:US has no EOD partner at all.
|
||||
// Date-gap partner test on listing 20: QM FBETF:US starts 2024-01-01 while EOD FB.US starts 2025-01-01.
|
||||
write_bytes(
|
||||
&map_path,
|
||||
b"eod\tFB.US\t2012-01-01\t2022-06-08\t10\n\
|
||||
eod\tMETA.US\t2022-06-09\t\t10\n\
|
||||
qm\tFB:US\t2012-01-01\t2022-06-08\t10\n\
|
||||
qm\tMETA:US\t2022-06-09\t\t10\n\
|
||||
eod\tFB.US\t2025-01-01\t\t20\n\
|
||||
qm\tFBETF:US\t2024-01-01\t\t20\n\
|
||||
eod\tALIAS_A.US\t2024-01-01\t\t30\n\
|
||||
eod\tALIAS_B.US\t2024-01-01\t\t30\n\
|
||||
qm\tALIAS:US\t2024-01-01\t\t30\n\
|
||||
qm\tQMONLY:US\t2024-01-01\t\t40\n",
|
||||
);
|
||||
write_bytes(&curr_path, b"10\tUSD\n20\tUSD\n30\tUSD\n40\tUSD\n");
|
||||
write_bytes(&splits_path, b"");
|
||||
|
||||
let eod_docs = [
|
||||
// Listing 10 pre-rename on FB.US (vol 1_000)
|
||||
eod_doc("FB.US", "2022-06-08", 190.0, 195.0, 188.0, 192.0, 1_000.0),
|
||||
// Listing 10 post-rename on META.US (vol 2_000)
|
||||
eod_doc("META.US", "2022-06-09", 191.0, 194.0, 189.0, 193.0, 2_000.0),
|
||||
// Listing 20 on reused ticker FB.US (vol 5_000)
|
||||
eod_doc("FB.US", "2025-01-02", 25.0, 26.0, 24.5, 25.5, 5_000.0),
|
||||
// Listing 30 on both EOD aliases (identical OHLCV -> collapses in curate_bars_1d, both checked in builder)
|
||||
eod_doc("ALIAS_A.US", "2024-05-01", 50.0, 52.0, 49.0, 51.0, 7_000.0),
|
||||
eod_doc("ALIAS_B.US", "2024-05-01", 50.0, 52.0, 49.0, 51.0, 7_000.0),
|
||||
];
|
||||
write_bytes(&eod_path, &eod_docs.concat());
|
||||
|
||||
let qm_docs = [
|
||||
// 1. Listing 10 on 2022-06-08 -> attaches ONLY to FB.US (matches 1_000)
|
||||
qm_price_doc_f64("FB:US", "2022-06-08", 1_000.0),
|
||||
// 2. Listing 10 on 2022-06-09 -> attaches ONLY to META.US (matches 2_000)
|
||||
qm_price_doc_f64("META:US", "2022-06-09", 2_000.0),
|
||||
// 3. Listing 20 on 2025-01-02 -> attaches ONLY to FB.US (matches 5_000)
|
||||
qm_price_doc_f64("FBETF:US", "2025-01-02", 5_000.0),
|
||||
// 4. Listing 30 on 2024-05-01 -> fans out to BOTH ALIAS_A.US and ALIAS_B.US (2 volumes attached)
|
||||
qm_price_doc_f64("ALIAS:US", "2024-05-01", 7_000.0),
|
||||
// 5. Unmapped QM key -> qm_unmapped_qm
|
||||
qm_price_doc_f64("UNKNOWN:US", "2024-05-01", 999.0),
|
||||
// 6. Expired QM key outside its range -> qm_unmapped_qm
|
||||
qm_price_doc_f64("FB:US", "2025-01-02", 999.0),
|
||||
// 7. QM-only listing (no EOD mapping at all) -> qm_no_eod_partner
|
||||
qm_price_doc_f64("QMONLY:US", "2024-05-01", 333.0),
|
||||
// 8. Listing 20 date before EOD mapping starts -> date-aware lookup finds no EOD partner -> qm_no_eod_partner
|
||||
qm_price_doc_f64("FBETF:US", "2024-06-01", 444.0),
|
||||
];
|
||||
write_bytes(&qm_path, &qm_docs.concat());
|
||||
|
||||
let report = run_curate_bars_1d(&CurateBars1dArgs {
|
||||
eod_prices: eod_path,
|
||||
qm_splits: splits_path,
|
||||
qm_prices: Some(qm_path),
|
||||
provider_mapping: map_path,
|
||||
listing_currencies: curr_path,
|
||||
out_dir: dir.path().join("out"),
|
||||
rel_tolerance: DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_qm_accounting_invariants(&report);
|
||||
assert_eq!(report.qm_rekey.qm_in, 8);
|
||||
assert_eq!(report.qm_rekey.qm_attached, 4);
|
||||
assert_eq!(report.qm_rekey.qm_volumes_attached, 5); // 1 + 1 + 1 + 2 (alias fan-out)
|
||||
assert_eq!(report.qm_rekey.qm_unmapped_qm, 2);
|
||||
assert_eq!(report.qm_rekey.qm_no_eod_partner, 2);
|
||||
|
||||
let b = &report.curate_stats.builder;
|
||||
assert_eq!(b.rows_out, 5);
|
||||
assert_eq!(b.volume_checked, 5);
|
||||
assert_eq!(b.volume_within_tolerance, 5);
|
||||
assert_eq!(b.volume_mismatched, 0);
|
||||
assert_eq!(b.volume_unchecked, 0);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -453,6 +453,190 @@ fn curate_bars_1d_cli_happy_path_and_determinism_with_shuffled_bson() {
|
|||
let pq_a = fs::read(out_a.join("bars_1d/year=2024/part.parquet")).unwrap();
|
||||
let pq_b = fs::read(out_b.join("bars_1d/year=2024/part.parquet")).unwrap();
|
||||
assert_eq!(pq_a, pq_b);
|
||||
assert!(text_a.contains("qm_check: qm_prices=absent"), "{text_a}");
|
||||
}
|
||||
|
||||
fn make_qm_price_doc(code: &str, date: &str, share_volume: f64) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("sharevolume"), share_volume);
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_bars_1d_cli_qm_prices_cross_check_and_framing_failures() {
|
||||
let dir = CliTempDir::new("qm-prices-cli");
|
||||
let eod_path = dir.path.join("eod.bson");
|
||||
let splits_path = dir.path.join("splits.bson");
|
||||
let qm_path = dir.path.join("qm.bson");
|
||||
let map_path = dir.path.join("map.tsv");
|
||||
let curr_path = dir.path.join("curr.tsv");
|
||||
|
||||
write_file(
|
||||
&map_path,
|
||||
b"eod\tNVDA.US\t2020-01-01\t\t1\nqm\tNVDA:US\t2020-01-01\t\t1\n",
|
||||
);
|
||||
write_file(&curr_path, b"1\tUSD\n");
|
||||
write_file(&splits_path, &make_split_doc("NVDA:US", "2024-06-10", 10.0));
|
||||
let d1 = make_eod_doc("NVDA.US", "2024-06-07", 1208.88, 412_390_000.0);
|
||||
let d2 = make_eod_doc("NVDA.US", "2024-06-10", 121.79, 310_000_000.0);
|
||||
write_file(&eod_path, &[d1.as_slice(), d2.as_slice()].concat());
|
||||
|
||||
// 2024-06-07 matches (41_239_000), 2024-06-10 has an injected >1% mismatch (300_000_000 vs 310_000_000).
|
||||
let q1 = make_qm_price_doc("NVDA:US", "2024-06-07", 41_239_000.0);
|
||||
let q2 = make_qm_price_doc("NVDA:US", "2024-06-10", 300_000_000.0);
|
||||
write_file(&qm_path, &[q1.as_slice(), q2.as_slice()].concat());
|
||||
|
||||
let out_no_qm = dir.path.join("out_no_qm");
|
||||
let out_with_qm = dir.path.join("out_with_qm");
|
||||
let out_eq_qm = dir.path.join("out_eq_qm");
|
||||
|
||||
let run_no_qm = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_path.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_path.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
map_path.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_path.to_str().unwrap(),
|
||||
"--out",
|
||||
out_no_qm.to_str().unwrap(),
|
||||
]);
|
||||
assert!(run_no_qm.status.success(), "{}", stderr(&run_no_qm));
|
||||
assert!(stdout(&run_no_qm).contains("qm_check: qm_prices=absent"));
|
||||
|
||||
// Mismatch still exits 0 and emits byte-identical Parquet.
|
||||
let run_with_qm = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_path.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_path.to_str().unwrap(),
|
||||
"--qm-prices",
|
||||
qm_path.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
map_path.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_path.to_str().unwrap(),
|
||||
"--out",
|
||||
out_with_qm.to_str().unwrap(),
|
||||
]);
|
||||
assert!(run_with_qm.status.success(), "{}", stderr(&run_with_qm));
|
||||
assert!(stderr(&run_with_qm).is_empty(), "{}", stderr(&run_with_qm));
|
||||
let out_text = stdout(&run_with_qm);
|
||||
assert!(out_text.contains("qm_bson:"), "{out_text}");
|
||||
assert!(out_text.contains("qm_rekey:"), "{out_text}");
|
||||
assert!(
|
||||
out_text.contains("volume_checked=2 volume_within_tolerance=1 volume_mismatched=1 volume_unchecked=0"),
|
||||
"{out_text}"
|
||||
);
|
||||
assert!(
|
||||
out_text.contains("qm_mismatch: key=NVDA.US session_date=2024-06-10"),
|
||||
"{out_text}"
|
||||
);
|
||||
|
||||
let pq_no_qm = fs::read(out_no_qm.join("bars_1d/year=2024/part.parquet")).unwrap();
|
||||
let pq_with_qm = fs::read(out_with_qm.join("bars_1d/year=2024/part.parquet")).unwrap();
|
||||
assert_eq!(pq_no_qm, pq_with_qm);
|
||||
|
||||
// Equals syntax (`--qm-prices=<path>`) also succeeds.
|
||||
let eq_flag = format!("--qm-prices={}", qm_path.to_str().unwrap());
|
||||
let run_eq = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_path.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_path.to_str().unwrap(),
|
||||
&eq_flag,
|
||||
"--provider-mapping",
|
||||
map_path.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_path.to_str().unwrap(),
|
||||
"--out",
|
||||
out_eq_qm.to_str().unwrap(),
|
||||
]);
|
||||
assert!(run_eq.status.success(), "{}", stderr(&run_eq));
|
||||
assert_eq!(
|
||||
fs::read(out_eq_qm.join("bars_1d/year=2024/part.parquet")).unwrap(),
|
||||
pq_no_qm
|
||||
);
|
||||
|
||||
// Truncated --qm-prices fails closed with single-line stderr naming path, publishes nothing,
|
||||
// and preserves a pre-existing dataset.
|
||||
let trunc_qm = dir.path.join("trunc_qm.bson");
|
||||
let mut trunc_bytes = q1.clone();
|
||||
trunc_bytes.truncate(trunc_bytes.len() - 4);
|
||||
write_file(&trunc_qm, &trunc_bytes);
|
||||
|
||||
let out_trunc_fresh = dir.path.join("out_trunc_fresh");
|
||||
let res_trunc = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_path.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_path.to_str().unwrap(),
|
||||
"--qm-prices",
|
||||
trunc_qm.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
map_path.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_path.to_str().unwrap(),
|
||||
"--out",
|
||||
out_trunc_fresh.to_str().unwrap(),
|
||||
]);
|
||||
assert!(!res_trunc.status.success());
|
||||
assert!(stdout(&res_trunc).is_empty());
|
||||
let err_trunc = stderr(&res_trunc);
|
||||
assert_eq!(err_trunc.lines().count(), 1, "{err_trunc}");
|
||||
assert!(err_trunc.contains("trunc_qm.bson"), "{err_trunc}");
|
||||
assert!(!out_trunc_fresh.join("bars_1d").exists());
|
||||
|
||||
// Pre-existing published output is untouched on failure.
|
||||
let res_preserve = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_path.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_path.to_str().unwrap(),
|
||||
"--qm-prices",
|
||||
trunc_qm.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
map_path.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_path.to_str().unwrap(),
|
||||
"--out",
|
||||
out_with_qm.to_str().unwrap(),
|
||||
]);
|
||||
assert!(!res_preserve.status.success());
|
||||
assert_eq!(
|
||||
fs::read(out_with_qm.join("bars_1d/year=2024/part.parquet")).unwrap(),
|
||||
pq_with_qm
|
||||
);
|
||||
|
||||
// Missing --qm-prices file fails closed.
|
||||
let missing_qm = dir.path.join("missing_qm.bson");
|
||||
let res_missing = run(&[
|
||||
"curate-bars-1d",
|
||||
"--eod-prices",
|
||||
eod_path.to_str().unwrap(),
|
||||
"--qm-splits",
|
||||
splits_path.to_str().unwrap(),
|
||||
"--qm-prices",
|
||||
missing_qm.to_str().unwrap(),
|
||||
"--provider-mapping",
|
||||
map_path.to_str().unwrap(),
|
||||
"--listing-currencies",
|
||||
curr_path.to_str().unwrap(),
|
||||
"--out",
|
||||
dir.path.join("out_missing").to_str().unwrap(),
|
||||
]);
|
||||
assert!(!res_missing.status.success());
|
||||
let err_missing = stderr(&res_missing);
|
||||
assert_eq!(err_missing.lines().count(), 1, "{err_missing}");
|
||||
assert!(err_missing.contains("missing_qm.bson"), "{err_missing}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -704,7 +888,10 @@ fn bench_curate_bars_cmd_small_run_succeeds_and_reports_splits() {
|
|||
let text = stdout(&out);
|
||||
assert!(text.contains("curate-etl bench-curate-bars-cmd"), "{text}");
|
||||
assert!(text.contains("rows=2000 "), "{text}");
|
||||
assert!(text.contains("qm_docs="), "{text}");
|
||||
assert!(text.contains("decode:"), "{text}");
|
||||
assert!(text.contains("qm:"), "{text}");
|
||||
assert!(text.contains("injected="), "{text}");
|
||||
assert!(text.contains("curate:"), "{text}");
|
||||
assert!(text.contains("write:"), "{text}");
|
||||
assert!(text.contains("total:"), "{text}");
|
||||
|
|
|
|||
|
|
@ -80,6 +80,7 @@ fn args_for(dir: &TempDir, out: &str, rel_tolerance: f64) -> CurateBars1dArgs {
|
|||
CurateBars1dArgs {
|
||||
eod_prices: dir.join("eodPrices.bson"),
|
||||
qm_splits: dir.join("qmSplits.bson"),
|
||||
qm_prices: None,
|
||||
provider_mapping: dir.join("provider_mapping.tsv"),
|
||||
listing_currencies: dir.join("listing_currencies.tsv"),
|
||||
out_dir: dir.join(out),
|
||||
|
|
|
|||
|
|
@ -131,6 +131,7 @@ fn args_for(dir: &TempDir, out: &str) -> CurateBars1dArgs {
|
|||
CurateBars1dArgs {
|
||||
eod_prices: dir.join("eodPrices.bson"),
|
||||
qm_splits: dir.join("qmSplits.bson"),
|
||||
qm_prices: None,
|
||||
provider_mapping: dir.join("provider_mapping.tsv"),
|
||||
listing_currencies: dir.join("listing_currencies.tsv"),
|
||||
out_dir: dir.join(out),
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue