T-214: M2.1w — Add notebook snapshot CLI, MCP end-to-end study+snapshot+finding test, and fix docs/->design/ path drift

This commit is contained in:
Studio 2026-12-05 13:45:27 -05:00
parent 8e2bf1c7f2
commit 2e71dda7f2
10 changed files with 2192 additions and 43 deletions

View file

@ -1,6 +1,6 @@
# `curate-etl`
Dedicated Rust crate (three exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) 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, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`, the `M1.2ak` read-only MongoDB URI safety guard (`mongo_safety`), and the `M1.2al` driver-independent read-only MongoDB raw-BSON cursor seam (`mongo_stream`).
Dedicated Rust crate (four exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `mongodb` `=3.10.2` with `default-features = false, features = ["compat-3-3-0", "bson-3", "sync", "rustls-tls", "dns-resolver"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) 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, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`, the `M1.2ak` read-only MongoDB URI safety guard (`mongo_safety`), the `M1.2al` read-only MongoDB raw-BSON cursor seam (`mongo_stream`) + M1 `--from-mongo` runners (`run_mongo`), and the M2 `curate-posts`, `curate-fundamentals`, `curate-macro`, `curate-bars-1m`, `curate-qm-bars-1m`, `curate-fx-1m`, and `send-ilp` commands.
## Scope & Sign Conventions
@ -92,7 +92,7 @@ Rules:
- Merge: `rows_out == eod.rows_kept + te.rows_kept - te_superseded_by_eod == eod_rows_out + te_rows_out`
- Overlap: `overlap_within_tolerance + overlap_mismatched == overlap_checked == te_superseded_by_eod`
Deferred out of `src/fx.rs`: `ts`/`known_at` timestamp derivation policy (the `M1.2l` Parquet writer accepts caller-supplied timestamps; derivation belongs to the Mongo-streaming wiring task), `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring FX into `src/adj.rs` cross-currency dividends.
Deferred out of `src/fx.rs`: `CADUSD.FOREX` inversion and wiring FX into `src/adj.rs` cross-currency dividends (`ts`/`known_at` `23:59:59.999999 UTC` stamping is implemented in `src/curate_fx.rs`, and `fx_1m` intraday FX lives in `src/curate_fx_1m.rs` / `curate-fx-1m`).
## `shorts` Builder (`M1.2f`)
@ -478,8 +478,8 @@ Rules:
- Never panics on untrusted input. `BsonEodPriceError` names the offending field on every field-level error: `MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, `TruncatedDocument`, `CorruptDocumentLength`, and `CorruptBson`.
- `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 (`eodIntraday1M`). (`qmSplits`/`qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, and `qmFilings`/`qmEarnings` decoders are now implemented alongside all six M1 `curate-*` file-to-Parquet commands.)
5. **Status of follow-ups from `M1.2o`:**
- All six M1 `curate-*` commands (file mode and `--from-mongo` via `mongodb = "=3.10.2"` in `src/mongo_stream.rs` + `src/run_mongo.rs`), `rayon` year-sharded parallel `bars_1d` Parquet writes, and the `eodIntraday1M` decoder (`src/bson_eod_intraday.rs`) are now implemented. Direct PostgreSQL `provider_mapping` preload (replacing TSV export) remains out of scope.
## `qmSplits` / `qmDividends` Raw BSON Decoders (`M1.2w`)
@ -1152,7 +1152,7 @@ Single-threaded baseline measured locally (`2026-11-29`, prior to `rayon` parall
### Known Limits
- **Full in-RAM buffering of mapped bars (and optional QM volumes) + parallel year-bucketing RAM:** `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). When `--threads > 1`, Pass 1 of `write_bars_1d_dataset` buckets validated `Bars1dParquetRow`s by year (`~136 B/row` struct size plus `Vec` growth slack, `~180–200 B/row` transient overhead before the caller's `curated.rows` vector drops) and holds up to `min(threads, years)` concurrent `RowGroupBuffer`s during parallel Zstd encoding (each year's bucket drops as soon as its worker finishes). Pass `--threads 1` to use the bounded-RAM single-pass streaming writer. 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.
- **Parallelism scope & direct MongoDB cursors:** `rayon` year-sharded parallelism currently covers the `curate-bars-1d` Parquet write stage (`--threads`); parallel BSON decode, parallel curate/sort, other `curate-*` commands, and direct MongoDB cursors remain deferred to follow-up tasks.
- **Parallelism scope & direct MongoDB cursors:** `rayon` year-sharded parallelism covers the `curate-bars-1d` Parquet write stage (`--threads`), and `--from-mongo` read-only streaming is wired for all six M1 `curate-*` commands (`src/run_mongo.rs`); parallel BSON decode, parallel curate/sort, and `--from-mongo` on M2 commands remain deferred to follow-up tasks.
- **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.
@ -1657,7 +1657,7 @@ Library-only, driver-independent read-only MongoDB raw-BSON cursor seam (`src/mo
### Dependencies
- **No new dependency added:** `tools/curate-etl/Cargo.toml` and `Cargo.lock` are unchanged (still three exact-pinned direct dependencies: `bson = "=3.1.0"`, `parquet = "=60.2.0"`, and `rayon = "=1.12.0"`). `src/mongo_stream.rs` contains no `mongodb::` driver paths yet.
- **Exact-pinned direct dependencies (`tools/curate-etl/Cargo.toml`):** `bson = "=3.1.0"`, `mongodb = "=3.10.2"` (`compat-3-3-0`, `bson-3`, `sync`, `rustls-tls`, `dns-resolver`), `parquet = "=60.2.0"`, and `rayon = "=1.12.0"`. `src/mongo_stream.rs` implements both the offline driver-independent `RawDocumentSource` seam and the read-only `mongodb`-backed `ReadOnlyMongoClient` / `MongoRawDocumentSource`, wired into all six M1 `curate-*` commands via `src/run_mongo.rs`.
### Public API & Sealing Guarantees
@ -1679,10 +1679,9 @@ Measured locally (`2026-11-30`, two back-to-back offline runs on the final code
- **Run 1:** plain `264.49 ms` (`3,780,816 docs/s`, `1,029.92 MiB/s`) vs. `RawBsonCursorReader` `263.32 ms` (`3,797,634 docs/s`, `1,034.50 MiB/s`, ratio `1.004x`, `peak_pending_capacity=271 bytes`)
- **Run 2:** plain `281.99 ms` (`3,546,241 docs/s`, `966.02 MiB/s`) vs. `RawBsonCursorReader` `270.90 ms` (`3,691,390 docs/s`, `1,005.56 MiB/s`, ratio `1.041x`, `peak_pending_capacity=271 bytes`)
### Not Done / Not Verified
### Live-Host Verification Pending
- **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress.
- **Live QA MongoDB cursor throughput on `quant`:** not run (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the driver/CLI wiring and live-host verification tasks).
- **Live QA MongoDB cursor throughput on `quant`:** all tests and benchmarks run 100% offline with zero network connections; `ReadOnlyMongoClient` / `MongoRawDocumentSource` (`src/mongo_stream.rs`) and M1 `--from-mongo` runners (`src/run_mongo.rs`) are implemented and unit-tested offline, while live cursor throughput against read-only QA MongoDB on `quant` awaits host-side execution.
## Zero-Copy `eodIntraday1M` BSON Decoder (`M2.3d`)
@ -1694,7 +1693,7 @@ Measured locally (`2026-11-30`, two back-to-back offline runs on the final code
## Point-in-Time Fundamentals Core (`M2.2a`)
Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals.rs`, tested in `src/fundamentals_tests.rs`) generic over listing key `K`. BSON decoding, Zstd Parquet writing, CLI `curate-*` wiring, and `MarketDataStore.fundamentalsAsOf` are deferred to follow-up tasks.
Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals.rs`, tested in `src/fundamentals_tests.rs`) generic over listing key `K`. Downstream wiring now lives in `src/bson_qm_financials.rs` (BSON decoding), `src/parquet_fundamentals.rs` (Zstd Parquet writing), `src/run_curate_fundamentals.rs` / `curate-fundamentals` (CLI), and `libs/research/src/market-data-store-duckdb.ts` (`MarketDataStore.fundamentalsAsOf`).
### Public API & Field Set
@ -1749,7 +1748,7 @@ See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.m
- **Explicit field paths & fiscal policy (no unverified defaults):** `CurateFundamentalsArgs::with_verified_defaults(...)` populates only the four verified `qmFinancials` defaults (`qmSearchCode`, `periodEndDate`, `reportDate`, `reportPeriod`), the two verified `qmFilings` defaults (`symbol`, `timefiled`), and `mapping_source = "qm"`. Callers must explicitly supply the `currency` path, all six numeric metric `Option<String>` paths, `CurateFundamentalsFiscalPeriod` (`Fixed(FiscalPeriod)` or `ByTokens { quarterly, annual }`), `filings_form_type_field`, and snapshot period limit `k >= 1`.
- **`listing_venues.tsv` format (`load_listing_venues_tsv`):** strict headerless 2-column tab-separated file `listing_id<TAB>venue`, where `listing_id` is a strictly positive ASCII base-10 integer and `venue` is exact `us_tsx` (`StatutoryLagVenue::UsTsx`) or `tsxv_cse` (`StatutoryLagVenue::TsxvCse`). Wrong column counts, non-integer/non-positive IDs, unknown venues, duplicate IDs, and interior blank lines fail closed with a single-line error naming the path and 1-based line number.
- **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `<out_dir>/fundamentals_pit` or modifying pre-existing partitions. CLI wiring (`curate-fundamentals`) is a separate follow-up.
- **Fail-closed & zero-row behavior:** Config validation, output/input path alias checks (including existing `year=YYYY` partition targets), TSV loading, and both BSON stream decodes complete before `curate_and_write_fundamentals` runs. Empty or all-unmapped inputs return `Ok` with `rows_written == 0` without creating `<out_dir>/fundamentals_pit` or modifying pre-existing partitions. File-mode CLI wiring is available via `curate-fundamentals` above.
## `run_curate_bars_1m` Bounded-Memory File-to-File Runner (`M2.3k`)
@ -1824,7 +1823,7 @@ curate-etl send-ilp \
- **Bounded-memory chunking & raw OHLCV passthrough:** Drives `RawBsonChunkReader::with_options`, `next_chunk()`, and `decode_qm_intraday_buffer` directly, borrowing `qmSearchCode` per chunk and curating without split un-adjustment (no splits input; raw `qmIntraday` OHLCV passes through bit-identical aside from `-0.0 -> +0.0` volume normalization) into one shared `IlpShardedWriter` with `finish()` called once after clean EOF. `mapping_source` rejects blank values and forwards any nonblank namespace verbatim (`DEFAULT_QM_BARS_1M_MAPPING_SOURCE = "qm"`).
- **Cross-chunk semantics, table/file separation & reporting:** Sorting and collision collapse/drop apply per chunk; cross-chunk duplicates rely on QuestDB `DEDUP UPSERT KEYS(ts, listing_id)`, and `curate_stats.listings_out` / `curate_stats.builder.keys_out` sum per-chunk counts. Emitted ILP v2 rows target table `bars_1m` with `source=qm_raw` and caller-supplied `known_at_micros`, while output files use the `bars_1m_qm.shard-<NN>.ilp` prefix so QM and EOD (`bars_1m.shard-<NN>.ilp`) exports can share `out_dir` safely.
- **Fail-closed publication:** Preflight rejects any pre-existing `bars_1m_qm.shard-<digits>.ilp` in `out_dir` regardless of `shard_count`, writes to exclusively created staging files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only this run's final and staging files on any error. CLI wiring, `--from-mongo`, and live QuestDB ingestion remain follow-ups.
- **Fail-closed publication:** Preflight rejects any pre-existing `bars_1m_qm.shard-<digits>.ilp` in `out_dir` regardless of `shard_count`, writes to exclusively created staging files, flushes and `sync_all`s on `finish`, publishes via same-directory `hard_link` + temp removal, and rolls back only this run's final and staging files on any error. File-mode CLI wiring is available via `curate-qm-bars-1m`; `--from-mongo` and live QuestDB ingestion remain follow-ups.
## Lagged Macro Regime Series Builder (`M2.2n`)