Compare commits
13 commits
a6163d9577
...
88308e1f12
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88308e1f12 | ||
|
|
91f10312e9 | ||
|
|
76fc415db4 | ||
|
|
be144d874a | ||
|
|
97fad30fd0 | ||
|
|
d998115dcf | ||
|
|
88b7a5d141 | ||
|
|
a1690717c8 | ||
|
|
1db433bf01 | ||
|
|
cc39ee379a | ||
|
|
9adc8f18c6 | ||
|
|
4f09c6596d | ||
|
|
8560b22c71 |
13 changed files with 7446 additions and 5 deletions
|
|
@ -13,6 +13,7 @@ Start here. Every document below has a single responsibility; historical sprint
|
|||
| **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)** | Raw MongoDB provider quirks, PostgreSQL security-master DDL, split/volume un-adjustment rules, `known_at` derivation, DuckDB/Parquet & QuestDB `10.2.0` schemas, and `MarketDataStore` API | Before touching `data-pipeline`, `data-ingestion`, SQL migrations, or `MarketDataStore` |
|
||||
| **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)** | Canonical metric definitions, `trial_ledger` schema, effective-trials DSR ($\hat{N}$), CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, lifecycle gates, and Dual Live Drift + IB/TSX execution rules | Before touching `libs/calculations`, `libs/research`, validation workflows, or paper/live execution |
|
||||
| **[servers.md](servers.md)** | Host roles (`quant` `12900K` research/data server, `9900K` isolated IB live/paper host, `TrueNAS` cold storage, dev workstation) and port/storage layout | Infrastructure, deployment, and worker sizing |
|
||||
| **[data-pipeline/rust-migration-evaluation.md](data-pipeline/rust-migration-evaluation.md)** | Evidence-based evaluation of keeping `apps/stock/data-pipeline` in TypeScript vs. moving bulk MongoDB streaming or the full pipeline into Rust (`tools/curate-etl`) | Before `M2` adds PIT fundamentals, `ceoPosts`, or `bars_1m` QuestDB ingestion |
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
249
design/data-pipeline/rust-migration-evaluation.md
Normal file
249
design/data-pipeline/rust-migration-evaluation.md
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
# Evaluation: Moving `apps/stock/data-pipeline` into Rust
|
||||
|
||||
**Date:** 2026-11-29
|
||||
**Status:** Decision brief for the director (docs-only spike; no code, crate, config, or milestone changes enacted)
|
||||
**Scope:** Evaluate the second half of the settled Rust ETL decision — whether to keep `apps/stock/data-pipeline` in TypeScript, move bulk MongoDB streaming into `tools/curate-etl` (Rust), or port all of `apps/stock/data-pipeline` to Rust before Milestone `M2` adds PIT fundamentals, `ceoPosts`, and `bars_1m` intraday QuestDB ingestion.
|
||||
|
||||
## Bottom Line (Recommendation)
|
||||
|
||||
**Adopt Option B: keep `apps/stock/data-pipeline` in TypeScript for security-master resolution, TSV export, probes, and BullMQ/HTTP orchestration, and add direct read-only MongoDB `RawDocumentBuf` streaming (with Rust-side read-only safety guards) to `tools/curate-etl` for bulk curation.**
|
||||
|
||||
- **Why not full port (Option C):** 88.1% of `apps/stock/data-pipeline/src/` (`17,924` of `20,349` LOC, backed by `40` test files / `32,435` test LOC) is logic- and review-bound security-master code operating on `319` exchanges and `396k` symbol catalog rows that already runs in sub-second synthetic benchmarks (`479.6 ms` for `100k` records in `run.ts`, `402.8 ms` for `500k` TSV mappings in `export-curate-inputs.ts`). Porting it adds weeks of parity risk, requires re-implementing BullMQ/PostgreSQL/env-safety adapters, and reopens settled decision `D5` / §4 layer boundaries for negligible wall-time gain.
|
||||
- **Why not keep the JS raw-BSON file bridge forever (Option A):** While `export-raw-bson.ts` avoids JS object decoding (`3.57M–3.83M docs/s` synthetic), staging `845.7M` `eodPrices` and `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` rows through intermediate `.bson` files forces an unnecessary full NVMe write + read of hundreds of GiB (synthetic estimate: ~127–225 GiB peak file capacity / ~255–450 GiB total write+read I/O for `eodPrices`; ~499–832 GiB peak capacity / ~998–1,664 GiB total write+read I/O for the two intraday collections) before Rust even begins curating. Streaming directly from read-only MongoDB cursors in `tools/curate-etl` eliminates that scratch hop without touching the TypeScript security master.
|
||||
- **Decision ownership:** The final choice among Options A, B, and C belongs to the director. None of the follow-up tasks in Section 6 are queued or enacted by this document.
|
||||
|
||||
---
|
||||
|
||||
## 1. Current `apps/stock/data-pipeline` Inventory
|
||||
|
||||
Measured directly from the repository working tree (no database connections). Every production file under `apps/stock/data-pipeline/src/` is `.ts` (zero non-`.ts` files).
|
||||
|
||||
| Area under `apps/stock/data-pipeline/src/` | Prod Files | Non-Test LOC | Dedicated Test Files | Test LOC | Primary I/O & Role |
|
||||
| --- | ---: | ---: | ---: | ---: | --- |
|
||||
| `security-master/` | 21 | 17,924 | 40 | 32,435 | Pure in-memory Passes 1–6 + read-only MongoDB readers (`eodSymbols`, `ibSymbols`, `qmSymbols`, `ceoSymbols`, `eodSymbolChange`, `eodPrices`, `qmPrices`, exchanges, raw BSON, field-shape probe) + PostgreSQL master read/write (`persist.ts`, `export-curate-inputs.ts`) + local file output |
|
||||
| `normalization/` | 4 | 1,318 | 6 | 2,468 | Pure in-memory (`identifiers.ts`, `provider-symbol.ts`, `ticker.ts`) + read-only MongoDB aggregation reader (`bar-spans.ts`: `$match`/`$group`/`$project`/`$sort` only, `$out`/`$merge` forbidden) |
|
||||
| `handlers/` | 12 | 809 | 1* | 290* | BullMQ job handlers (`{data-pipeline_exchanges}`, `{data-pipeline_symbols}` queues via `getFullQueueName`), read-only MongoDB reads, PostgreSQL master reads/writes via `PipelineSyncRepository` |
|
||||
| `repositories/` | 1 | 166 | (shared)* | (shared)* | PostgreSQL transactional sync/reset (`PipelineSyncRepository`, `pg_advisory_xact_lock(1937007472, 1)`) using `@stock-bot/types` `parseReferenceDataResetRequest` |
|
||||
| `routes/` | 2 | 23 | 0 | 0 | HTTP `GET /health` via Hono (`create-routes.ts`, `health.routes.ts`) |
|
||||
| `types/` | 1 | 21 | 0 | 0 | Pure in-memory TypeScript interfaces (`job-payloads.ts`: `JobPayload`, `SyncResult`, `SyncStatus`) |
|
||||
| `index.ts` | 1 | 88 | 0 | 0 | Service bootstrap (`ServiceApplication`, `initializeStockConfig('dataPipeline', { mongoReadOnly: true })`, port `2002`, BullMQ + HTTP + Postgres + read-only Mongo) |
|
||||
| **Total (`src/`)** | **42** | **20,349** | **47** | **35,193** | — |
|
||||
|
||||
*\*`test/postgres/pipeline-safety.test.ts` (1 file, 290 lines) exercises both `handlers/` operations and `PipelineSyncRepository`; it is counted once in the total. `routes/`, `types/`, and `index.ts` have no dedicated unit test files and are covered indirectly by `test/unit/environment-safety*.test.ts` and `test/unit/mongodb-read-only.test.ts`.*
|
||||
|
||||
Separately from production LOC, `apps/stock/data-pipeline/benchmarks/` holds **5 files / 1,144 LOC** of local synthetic benchmark scripts (`export-curate-inputs-benchmark.ts`, `export-raw-bson-benchmark.ts`, `run-security-master-pass4-benchmark.ts`, `sample-closes-benchmark.ts`, `source-field-shapes-benchmark.ts`).
|
||||
|
||||
### Key CLI & Exporter Subsystems Inside `security-master/`
|
||||
|
||||
- **`run-security-master.ts` (T-89 / T-105, `1,042` LOC) + `run.ts` (`1,345` LOC):** Runs the full read-only MongoDB security-master pipeline (`read-exchanges` → `read-sources` → `compute-bar-spans` → Pass 4 `readSampleCloses` + `crossCheckPrices` → `composeSecurityMasterRun`) and writes deterministic `match-report.md`, `conflicts.csv`, `override-template.sql`, and `run-stats.json`, with opt-in `--persist` to isolated dev PostgreSQL guarded by `assertSecurityMasterPersistSafety()`. **Source note:** Pass 4 is **wired and enabled by default** in `run-security-master.ts` (`--skip-price-cross-check`, `--sample-dates <n>`), even though `apps/stock/data-pipeline/README.md` line 201 still states it is not yet wired.
|
||||
- **TSV Exporter (T-116, `export-curate-inputs.ts` `2,040` LOC + `run-export-curate-inputs.ts` `345` LOC = `2,385` LOC):** Reads PostgreSQL security-master tables inside a `REPEATABLE READ READ ONLY` transaction (server-side `NO SCROLL` cursor, chunk size `<= 5,000`) and atomically publishes `provider_mapping.tsv`, `listing_currencies.tsv`, and Pass 6 `delistings.tsv` into `<out-dir>/generations/<generationId>` behind `<out-dir>/.publish.lock` and a single `<out-dir>/current` symlink.
|
||||
- **Raw-BSON Exporter (T-117, `export-raw-bson.ts` `670` LOC + `run-export-raw-bson.ts` `477` LOC = `1,147` LOC):** Streams 8 allowlisted M1 MongoDB collections (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`) via `find(filter, { raw: true, batchSize })` with zero per-document JS decoding, validating BSON frame lengths, coalescing through an `8 MiB` write buffer, computing SHA-256, and publishing `<collection>.bson` atomically.
|
||||
- **Field-Shape Probe (`source-field-shapes.ts` `915` LOC + `probe-source-field-shapes.ts` `291` LOC = `1,206` LOC):** Bounded read-only `find({}, { limit <= 10_000, promoteValues: false, promoteLongs: false })` probe over the 8 M1 collections to confirm live BSON field names and types before curation runs.
|
||||
|
||||
### Cross-App Coupling & Safety Guards
|
||||
|
||||
- **Zero direct package imports:** No other app or library imports `@stock-bot/data-pipeline`.
|
||||
- **`web-api` runtime contract:** `apps/stock/web-api/src/services/pipeline.service.ts` enqueues BullMQ jobs onto `{data-pipeline_exchanges}` and `{data-pipeline_symbols}` via `getFullQueueName` (`libs/core/queue/src/service-utils.ts`, re-exported by `@stock-bot/queue`; using shared `@stock-bot/types` `parseReferenceDataResetRequest` / `ReferenceDataResetScope` for reset confirmation), and `apps/stock/web-api/src/services/monitoring.service.ts` monitors those two queues and polls `GET /health` on port `2002`.
|
||||
- **Safety guard stack:** Every service and CLI entrypoint calls `initializeStockConfig('dataPipeline', { mongoReadOnly: true })` and `assertEnvironmentSafety()` (`apps/stock/config/src/env-safety.ts`, `706` LOC), which resolves loopback/LAN/numeric IPv4 aliases and throws if `development` targets QA PostgreSQL (`localhost:5432/trading_bot`) or opens QA MongoDB (`localhost:27017`) without `mongoReadOnly: true` or with `trading_admin`. At the driver layer, `MongoDBClient` (`libs/data/mongodb/src/client.ts`) wraps databases, collections, and cursors in read-only proxies that reject all write, index, and collection-mutation operations.
|
||||
|
||||
### Reproducible Inventory Commands
|
||||
|
||||
Re-running these POSIX commands from the repository root at the same commit reproduces every count in the table above:
|
||||
|
||||
```bash
|
||||
# 1. Production source file counts & non-test LOC per area
|
||||
for area in security-master normalization handlers repositories routes types; do
|
||||
files=$(find "apps/stock/data-pipeline/src/$area" -type f -name '*.ts' | sort)
|
||||
count=$(printf '%s\n' "$files" | grep -c .)
|
||||
lines=$(printf '%s\n' "$files" | xargs wc -l | tail -n 1 | awk '{print $1}')
|
||||
printf '%-18s files=%2d loc=%5d\n' "$area/" "$count" "$lines"
|
||||
done
|
||||
printf '%-18s files=%2d loc=%5d\n' "index.ts" 1 "$(wc -l < apps/stock/data-pipeline/src/index.ts)"
|
||||
total_files=$(find apps/stock/data-pipeline/src -type f -name '*.ts' | wc -l)
|
||||
total_lines=$(find apps/stock/data-pipeline/src -type f -name '*.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')
|
||||
printf '%-18s files=%2d loc=%5d\n' "TOTAL" "$total_files" "$total_lines"
|
||||
|
||||
# 2. Dedicated test files & benchmark scripts
|
||||
printf 'data-pipeline/test: %2d files %5d lines\n' \
|
||||
"$(find apps/stock/data-pipeline/test -type f -name '*.test.ts' | wc -l)" \
|
||||
"$(find apps/stock/data-pipeline/test -type f -name '*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
|
||||
printf 'unit security-master: %2d files %5d lines\n' \
|
||||
"$(find test/unit -type f -name 'security-master-*.test.ts' | wc -l)" \
|
||||
"$(find test/unit -type f -name 'security-master-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
|
||||
printf 'postgres security-master: %2d files %5d lines\n' \
|
||||
"$(find test/postgres -type f -name 'security-master-*.test.ts' | wc -l)" \
|
||||
"$(find test/postgres -type f -name 'security-master-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
|
||||
printf 'unit normalization: %2d files %5d lines\n' \
|
||||
"$(find test/unit -type f -name 'normalization-*.test.ts' | wc -l)" \
|
||||
"$(find test/unit -type f -name 'normalization-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
|
||||
printf 'integration provider-symbol: %2d files %5d lines\n' \
|
||||
1 "$(wc -l < test/integration/provider-symbol.test.ts)"
|
||||
printf 'postgres pipeline-safety: %2d files %5d lines\n' \
|
||||
1 "$(wc -l < test/postgres/pipeline-safety.test.ts)"
|
||||
printf 'benchmarks (separate): %2d files %5d lines\n' \
|
||||
"$(find apps/stock/data-pipeline/benchmarks -type f -name '*.ts' | wc -l)" \
|
||||
"$(find apps/stock/data-pipeline/benchmarks -type f -name '*.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. What Already Lives in Rust (`tools/curate-etl`)
|
||||
|
||||
`tools/curate-etl` is a standalone Cargo workspace member with **three exact-pinned dependencies** (`bson = "=3.1.0"` with `compat-3-0-0`, `parquet = "=60.2.0"` Zstd-only, `rayon = "=1.12.0"`), **zero async runtime**, and **zero database clients**.
|
||||
|
||||
| Module Group under `tools/curate-etl/src/` | Files | LOC | Contents |
|
||||
| --- | ---: | ---: | --- |
|
||||
| Domain builders | 9 | 8,170 | `adj.rs`, `bars.rs`, `corporate_actions.rs`, `events.rs`, `fx.rs`, `provider_mapping.rs`, `session_close.rs`, `shorts.rs`, `split.rs` |
|
||||
| Zero-copy BSON decoders & framing | 7 | 5,594 | `bson_ceo_shorts.rs`, `bson_eod_prices.rs`, `bson_qm_actions.rs`, `bson_qm_events.rs`, `bson_qm_prices.rs`, `bson_stream.rs`, `bson_te_market_data.rs` |
|
||||
| Zstd Parquet writers & atomic publish | 7 | 9,841 | `parquet_adj.rs`, `parquet_bars.rs`, `parquet_corporate_actions.rs`, `parquet_events.rs`, `parquet_fx.rs`, `parquet_publish.rs`, `parquet_shorts.rs` |
|
||||
| Curation stages | 6 | 3,726 | `curate_adj.rs`, `curate_bars.rs`, `curate_corporate_actions.rs`, `curate_events.rs`, `curate_fx.rs`, `curate_shorts.rs` |
|
||||
| Runnable `curate-*` CLI runners | 6 | 5,202 | `run_curate_adj.rs`, `run_curate_bars.rs`, `run_curate_corporate_actions.rs`, `run_curate_events.rs`, `run_curate_fx.rs`, `run_curate_shorts.rs` |
|
||||
| CLI, benchmarks, entrypoints | 4 | 16,884 | `bench.rs`, `cli.rs`, `lib.rs`, `main.rs` |
|
||||
| Dedicated test modules (`*_tests.rs`) | 26 | 27,215 | Unit, property, parity, and TSV/BSON fixture tests |
|
||||
| **Total (`tools/curate-etl/src/`)** | **65** | **76,632** | **39 non-test files (49,417 LOC) + 26 test files (27,215 LOC)** |
|
||||
|
||||
Reproducible command:
|
||||
|
||||
```bash
|
||||
find tools/curate-etl/src -type f -name '*.rs' ! -name '*_tests.rs' | wc -l
|
||||
find tools/curate-etl/src -type f -name '*.rs' ! -name '*_tests.rs' | sort | xargs wc -l | tail -n 1
|
||||
find tools/curate-etl/src -type f -name '*_tests.rs' | wc -l
|
||||
find tools/curate-etl/src -type f -name '*_tests.rs' | sort | xargs wc -l | tail -n 1
|
||||
```
|
||||
|
||||
The binary already implements all **six M1 curation commands** (`curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, `curate-fx-1d`, `curate-shorts`, `curate-events`) reading local TSVs + concatenated raw-BSON files and atomically publishing Hive-partitioned Zstd Parquet.
|
||||
|
||||
### Measured Local Baselines (Synthetic / Offline — Zero Live QA MongoDB or `quant` Runs)
|
||||
|
||||
| Benchmark | Source & Date | Command | Workload & Measured Result |
|
||||
| --- | --- | --- | --- |
|
||||
| `curate-bars-1d` (1-thread baseline) | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 1000000` | `1,000,000` EOD + `227,439` QM + `2,040` splits: `decode 234.63 ms` (`4.26M rows/s`), `curate 208.07 ms`, `write 456.39 ms` (`2.06M rows/s`), **total `899.09 ms` (`1.11M rows/s`, `193.78 MB/s`)** |
|
||||
| `curate-bars-1d` (`rayon` parallel write, **local re-run**) | Local sandbox re-run (`2026-11-29`, 32-thread host, synthetic) | `CARGO_BUILD_JOBS=2 cargo run --release -p curate-etl --offline -- bench-curate-bars-cmd 1000000` | Same `1,000,000`-row synthetic input: `decode 233.19 ms` (`4.29M rows/s`), `curate 207.45 ms`, `write_1 (threads=1) 445.79 ms` (`2.10M rows/s`) vs **`write (threads=32) 94.42 ms` (`9.93M rows/s`, `259.56 MB/s`, `4.72x` speedup)**, **total `535.06 ms` (`1.87M rows/s`, `325.63 MB/s`)** |
|
||||
| `curate-bars-1d` (5M rows, 1-thread) | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 5000000` | `5,000,000` EOD + `1.14M` QM + `4,080` splits: **total `3,525.02 ms` (`1.42M rows/s`, `247.01 MB/s`)** |
|
||||
| `curate-adj-factors` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd` | `500,000` events + `62,720` `bars_1d`: **total `436.90–500.88 ms` (`998k–1.14M events/s`)** across 2 runs |
|
||||
| `curate-corporate-actions` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd 1000000` | `1,000,000` events (`39,186` splits, `950,896` divs, `9,918` delistings): **total `752.71–775.67 ms` (`1.29M–1.33M events/s`)** |
|
||||
| `curate-fx-1d` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-fx-cmd` | `20,000` FX rows (`CAD.FOREX` + `USDCAD`): **total `20.19–29.97 ms` (`667k–990k rows/s`)** |
|
||||
| `curate-shorts` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-shorts-command` | `700,000` `ceoShorts` docs (`64.78 MiB`): **total `365.73–369.48 ms` (`1.89M–1.91M rows/s`)**, `peak_chunk_bytes = 8 MiB` |
|
||||
| `curate-events` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-events-cmd` | `500,000` rows (`492.5k` filings, `7.5k` earnings): **total `838.71–861.10 ms` (`581k–596k rows/s`)**; linear synthetic extrapolation to `30.96M` rows: `51.9–53.3 s` single-core |
|
||||
| `bson_eod_prices` decode-only | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-bson-eod-prices` | `1,000,000` docs (`272.4 MiB`): **`217.38–221.82 ms` (`4.51M–4.60M rows/s`, `1.23–1.25 GB/s`)** |
|
||||
| `bson_stream` short-read | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-bson-stream` | `2,000,000` docs (`544.8 MiB`): **`544.59 ms` (`3.67M rows/s`, `1.00 GiB/s`, `0.963x` vs in-memory buffer, `8 MiB` peak buffer)** |
|
||||
| `parquet_bars` write-only | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-parquet-bars` | `5,000,000` rows, 20 year files: **`1,422.27 ms` (`3.52M rows/s`, `155.11 MB/s`, `1.82x` Zstd)** |
|
||||
| `split` builder | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-split` | `10,000,000` synthetic rows: **`367.40 ms` (`27.22M rows/s`)** |
|
||||
| `bars` builder | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-bars` | `10,000,000` synthetic rows: **`842.38 ms` (`11.87M rows/s`)** |
|
||||
| `provider_mapping` lookup | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-provider-mapping` | `10,000,000` synthetic lookups: **`447.14 ms` (`22.36M lookups/s`)** |
|
||||
| TS `export-raw-bson` | `apps/stock/data-pipeline/README.md` (`2026-11-29`) | `bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts` | `1,000,000` synthetic `eodPrices` frames (`123.9 B` avg): **`270.8–279.8 ms` (`3.57M–3.69M docs/s`, `422–436 MiB/s`, `peak_rss 150–151 MiB`)**; `2M` docs: `3.83M docs/s`, `peak_rss 146.88 MiB` |
|
||||
| TS `export-curate-inputs` | `apps/stock/data-pipeline/README.md` (`2026-11-29`) | `bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts` | `500k` mappings + `100k` listings + `2k` OTC (`606,680` TSV rows, `17.2 MB`): **`402.8 ms` (`1.51M rows/s`, `277.01 MiB` peak RSS)** |
|
||||
| TS `sample-closes` (Pass 4a) | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts` | `500,025` synthetic docs (25 dates × 20k IDs + FX): **`190.3 ms` (`2.63M docs/s`)** |
|
||||
| TS `source-symbol-readers` | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-source-symbol-readers.test.ts` | `368,000` synthetic symbol docs: **`488.0 ms` (`754k docs/s`)** |
|
||||
| TS `security-type` classifier | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-security-type.test.ts` | `300,000` synthetic EOD records (`100k` distinct ISIN buckets, `20` conflicting ISINs): **`70.1 ms` (`4.28M records/s`, floor `>= 100k records/s`)** |
|
||||
| TS `run.ts` composer (Passes 3–6) | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-run.test.ts` | `100,000` synthetic source records end-to-end: **`479.6 ms` (`208.5k records/s`)** |
|
||||
| TS `persistSecurityMaster` | `apps/stock/data-pipeline/README.md` (`2026-11-28`, host Postgres safety schema) | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts` | `20k` instruments + `20k` listings + `60k` mappings (`140k` total rows): **`2.36 s` full test wall time (`>= 59.3k total rows/s`)** |
|
||||
| TS `source-field-shapes` probe | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts` | `80,000` synthetic docs (8 collections × 10k): **`218.7 ms` (`365.8k docs/s`)** |
|
||||
|
||||
---
|
||||
|
||||
## 3. Workload Classification by Area
|
||||
|
||||
Row volumes come from the measured 2026-11-26 QA MongoDB inventory in `design/data-pipeline/phase1-investigation.md` and `design/DATA-CONTRACTS.md` §1.
|
||||
|
||||
| Area / Pipeline Stage | Raw / Target Volume | Bottleneck Class | Run Cadence | Rust Value-Add |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Pass 1 Exchanges (`exchange-pass1.ts`, `generate-exchange-seed.ts`) | `319` rows (`eodExchanges` 76, `ibExchanges` 214, `qmExchanges` 25, `ceoExchanges` 4) | **Logic / human-review-bound** | Rare (initial seed + schema override migrations) | **None** |
|
||||
| Pass 2–3–5–6 Security Master (`source-symbol-readers.ts`, `instrument-stage-a.ts`, `listing-stage-b.ts`, `delisting-chains.ts`, `match-report.ts`, `run.ts`, `persist.ts`) | `396,041` symbol docs (`eodSymbols` 317.8k, `qmSymbols` 47.2k, `ibSymbols` 18.4k, `ceoSymbols` 12.6k) + `230` `eodSymbolChange` | **Logic / edge-case / review-bound** (ISIN Luhn + CUSIP rescue, IB ATS venues, ticker-reuse spans, OTC delisting chains, override precedence) | Infrequent (initial US+CA build, then periodic delta refreshes) | **Negligible** (TS already does `100k` records in `0.48 s` and `140k` PG rows in `2.36 s`) |
|
||||
| Pass 2 `bar-spans.ts` & Pass 4 `sample-closes.ts` | Server-side Mongo `$group` on `eodPrices`/`qmPrices` + 25-date `$in` slice (~500k docs) | **MongoDB index/server I/O-bound** | Same as security master | **Negligible** (MongoDB server does the scan; TS client processes 500k closes in `0.19 s`) |
|
||||
| TSV Export (`export-curate-inputs.ts`) | ~100k–500k PostgreSQL rows (~17 MB) | **Small Postgres read** | Before each curation batch | **Negligible** (`0.40 s` synthetic; ~17 MB on disk) |
|
||||
| Field-Shape Probe (`source-field-shapes.ts`) | `<= 80,000` sampled docs (`8 × 10k`) | **Diagnostic / interactive** | Occasional schema check | **None** |
|
||||
| Service Control Plane (`handlers/`, `repositories/`, `routes/`, `index.ts`) | Legacy BullMQ sync jobs + `GET /health` | **Control-plane / queue glue** | Always-on daemon (low QPS) | **Negative** (BullMQ/DI/Hono already in TS) |
|
||||
| **M1 Bulk Raw-BSON Export → Parquet (`eodPrices`, `qmPrices`, `qmFilings`, `qmDividends`, `qmSplits`, `ceoShorts`, `qmEarnings`, `teMarketData`)** | **`845.7M` `eodPrices` + `51.5M` `qmPrices` + `30.5M` `qmFilings` + `1.65M` others** | **CPU + NVMe-scratch / throughput-bound** | Full backfill + nightly/weekly incremental | **High — already in Rust for curation; JS file hop adds huge NVMe scratch write+read** |
|
||||
| **M2 Bulk Raw-BSON → Parquet / QuestDB ILP v2 (`eodIntraday1M`, `qmIntraday`, `ceoPosts`, `qmFinancials`)** | **`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts` + `2.77M` `qmFinancials`/`-old`** | **CPU + NVMe-scratch + network/ILP throughput-bound** | Multi-billion-row backfill + incremental | **Critical — staging `3.57B` intraday docs through local `.bson` files is an estimated ~499–832 GiB peak capacity (~998–1,664 GiB total write+read I/O) NVMe bottleneck** |
|
||||
|
||||
### Why the Intermediate `.bson` File Hop Hurts at M1/M2 Scale
|
||||
|
||||
Even though `export-raw-bson.ts` avoids JS object deserialization (`3.57M–3.83M docs/s` synthetic), it writes every raw document to `<collection>.bson` on NVMe before `curate-etl` reads the file back (so total NVMe bytes moved is **2×** the peak file size, using binary `1 GiB = 2^30` bytes throughout):
|
||||
|
||||
- **M1 `eodPrices` (`845.7M` docs):** Under the synthetic average frame-size assumption of `161.7–285.6 B/doc` (`bench-curate-bars-cmd` / `bench-bson-eod-prices`), staging `eodPrices.bson` requires roughly **~127–225 GiB peak scratch file capacity** and **~255–450 GiB total NVMe I/O (write + read-back)** before `qmPrices` (`51.5M`) and `qmFilings` (`30.5M`).
|
||||
- **M2 intraday (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` = `3.57B` docs):** Under an assumed synthetic `150–250 B/doc` average frame size, staging both intraday collections to `.bson` files requires roughly **~499–832 GiB peak scratch file capacity** and **~998–1,664 GiB total NVMe I/O (write + read-back)** on `quant`'s 4 TB SN850X NVMe (which also holds the `~638 GB` MongoDB corpus, PostgreSQL, QuestDB, and curated Parquet). Eliminating that intermediate file via direct Rust `RawDocumentBuf` cursors saves that entire scratch file footprint and extra NVMe write+read pass. *(All byte-size figures are extrapolated from synthetic documents; actual live BSON document sizes are unverified — see Section 7.)*
|
||||
|
||||
---
|
||||
|
||||
## 4. Options Comparison
|
||||
|
||||
| Dimension | Option A: Keep Current TS + File-Bridge Rust Split | Option B: Direct Read-Only MongoDB Streaming in `tools/curate-etl` (Recommended) | Option C: Full Port of `apps/stock/data-pipeline` to Rust |
|
||||
| --- | --- | --- | --- |
|
||||
| **Architecture** | Status quo (`PLATFORM-PLAN.md` §4): TS owns security master, TSV export, raw-BSON export, probes, BullMQ/HTTP; Rust `curate-etl` reads local TSV + `.bson` files | TS keeps security master (Passes 1–6), TSV export (`export-curate-inputs.ts`), probes, BullMQ/HTTP. Rust `curate-etl` gains a read-only MongoDB cursor adapter (`--mongo-uri` / `MONGODB_READ_URI`) feeding the existing `RawDocumentBuf` decoders directly, while **retaining** file-based CLI mode for offline/reproducible tests | Rewrite all 42 TS files (`20,349` LOC) + 47 test files (`35,193` LOC) in Rust (security master, Postgres persistence, TSV/direct PG read, probes, BullMQ worker, HTTP `/health`, plus direct Mongo cursors) |
|
||||
| **Estimated Effort** | **0 new files/LOC** for M1 bridge; in M2 must extend `RAW_BSON_EXPORT_COLLECTIONS` and add scratch-space management / chunked export for `3.40B` `eodIntraday1M` | **Two-stage effort:**<br>1. **Cursor-only swap (~4–6 new `.rs` files, ~1,200–1,800 LOC + ~1,000–1,500 test LOC):** Rust `env-safety` URI/host/user read-only guard, sealed `mongodb` read-only `RawDocumentBuf` cursor adapter, and `--mongo-uri` / `--collection` CLI wiring alongside existing file mode.<br>2. **Bounded-memory partitioning & overlapped I/O (additional ~3–5 `.rs` files / runner refactors, ~1,500–2,500 LOC + ~1,500–2,000 test LOC):** Date/year or key-range partitioned streaming in `run_curate_bars.rs` and `run_curate_events.rs` (which currently accumulate all decoded rows in RAM before sorting/curation) plus bounded channel pipelining between MongoDB cursor reads and `rayon` Parquet / ILP writes.<br>**Combined:** ~7–11 files, ~2,700–4,300 LOC + ~2,500–3,500 test LOC | **Very large (~40+ `.rs` files, ~15,000–22,000 LOC + ~25,000–35,000 test LOC):** Re-implement Passes 1–6, `persist.ts`, `bar-spans.ts`, `sample-closes.ts`, `source-field-shapes.ts`, `PipelineSyncRepository`, BullMQ Redis protocol, Hono `/health`, and re-verify all 47 test suites (plus Option B's Stage 1+2 work) |
|
||||
| **New Rust Crates Required** | None (`bson =3.1.0`, `parquet =60.2.0`, `rayon =1.12.0` stay unchanged) | `mongodb` (with `bson-3` feature matching `bson =3.1.0`), `tokio` (minimal `rt-multi-thread`/`net`/`time` for async driver), `url` (or strict custom URI parser for safety guard). *Note: keeps zero Postgres/HTTP/Redis crates in `curate-etl`.* | Everything in Option B **plus** `tokio-postgres` / `sqlx`, `axum` / `hyper` (HTTP `/health`), `redis` + custom BullMQ Lua/stream worker compatibility (no official Rust BullMQ crate), `serde` / `serde_json`, `chrono` / `time` |
|
||||
| **Expected Runtime & NVMe Gain (Evidence-Backed)** | Baseline: TS `export-raw-bson` (`3.57M–3.83M docs/s` synthetic) + Rust `curate-bars-1d` (`1.87M rows/s` with `rayon` write). Pays full NVMe scratch footprint (~127–225 GiB peak / ~255–450 GiB write+read for M1 `eodPrices`; ~499–832 GiB peak / ~998–1,664 GiB write+read for M2 intraday, synthetic estimates) | **Stage 1 (cursor-only):** Eliminates intermediate `.bson` scratch files (~100% of bulk scratch NVMe capacity and the extra write+read pass) and removes the TS process hop, **without** reducing decoded-row RAM or overlapping curation/Parquet writes (since `run_curate_bars.rs` and `run_curate_events.rs` still buffer decoded rows before sorting).<br>**Stage 2 (partitioned streaming + pipelining):** Adds bounded-memory execution (needed for global `845.7M` `eodPrices` on `quant`'s `125 GiB` RAM) and overlaps MongoDB wire reads with Rust decode/Parquet/ILP writes.<br>**End-to-end wall-time speedup is unmeasured** (see Section 7). Zero change to sub-second security-master runs | Same bulk gain as Option B; **< 1–3 seconds saved** on security master (`run.ts` is already `479.6 ms` / `100k` records; `persist.ts` is `2.36 s` / `140k` rows, bound by Postgres `UNNEST` I/O; `export-curate-inputs.ts` is `402.8 ms` / `500k` rows) |
|
||||
| **Key Risks** | 1. NVMe capacity/wear spike on `quant` when exporting `3.57B` intraday docs to `.bson` files.<br>2. Two-step manual/scripted orchestration per bulk collection | 1. **Safety-guard parity:** Bypassing TS `assertEnvironmentSafety()` and `MongoDBClient` `mongoReadOnly: true` requires a battle-tested Rust read-only guard (blocking `trading_admin`, loopback/LAN IPv4 variants, and any write command).<br>2. **Memory scope:** A cursor swap alone does not bound RAM on global `845.7M` `eodPrices` until Stage 2 partitioning lands.<br>3. **Crate/async footprint:** Adds `mongodb` + `tokio` to Cargo workspace (requires crates.io fetch and offline cache refresh). | 1. **Pass 1–6 parity risk:** Re-verifying 17,924 LOC of subtle ISIN/CUSIP/ATS/ticker-reuse/delisting-chain rules against 40 test suites.<br>2. **Shared TS contract loss:** Loses `@stock-bot/types` (`ReferenceDataResetRequest`), `@stock-bot/stock-config`, `@stock-bot/postgres` migrations, and BullMQ `{data-pipeline_exchanges}`/`{data-pipeline_symbols}` queue parity with `web-api`.<br>3. **Safety-guard duplication** for both MongoDB and PostgreSQL.<br>4. **Multi-week M2 delay** with no user-visible research value |
|
||||
| **Impact on M2 Work Items** | Slows M2 `bars_1m` (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` → QuestDB ILP v2) because raw `.bson` staging doesn't scale cleanly to multi-billion-row streams; `ceoPosts` (`14.8M`) and `qmFinancials` (`2.77M`) remain workable | **Directly accelerates M2:** `tools/curate-etl` streams `eodIntraday1M` (`3.40B`, **split-unadjusting** retroactively adjusted OHLCV via `qmSplits`) and `qmIntraday` (`173.3M`, taking **already-raw** `open..close` and `sharevolume` directly — **no** split un-adjustment) into multi-socket QuestDB ILP v2 (`bars_1m`, `DEDUP UPSERT KEYS(ts, listing_id)`) with zero `.bson` scratch files, verified by the M2 split-boundary comparison (`NEXM.V` `1:20` and `NVDA.US` `10:1` `bars_1m` session closes within `0.5%` of raw `bars_1d` closes); same cursor adapter serves `ceoPosts` (`14.8M`) and `qmFinancials` | **Blocks M2** for weeks while porting already-working M1 security-master code instead of building MCP, PIT fundamentals, QuestDB `10.2.0` `bars_1m`, and Feature Library |
|
||||
|
||||
*Why Option B keeps `export-curate-inputs.ts` in TypeScript:* Exporting `500k` security-master mappings + `100k` listings takes `402.8 ms` (`17.2 MB`) synthetically and already ships with atomic `<out-dir>/current` generation pinning consumed by `curate-etl --curate-inputs`. Keeping it in TypeScript avoids pulling a PostgreSQL driver and `assertSecurityMasterPersistSafety()` duplication into `tools/curate-etl`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Compliance Check (`D1`–`D12` & QA Database Safety Rules)
|
||||
|
||||
### Locked Decisions `D1`–`D12` (`design/PLATFORM-PLAN.md` §3)
|
||||
|
||||
| Decision | Option A | Option B (Recommended) | Option C |
|
||||
| --- | --- | --- | --- |
|
||||
| **D1** (Parquet+DuckDB daily/PIT; QuestDB `10.2.0` intraday) | Compliant | Compliant (directly enables M2 `3.40B` ILP v2 streaming to QuestDB) | Compliant |
|
||||
| **D2** (Desktop copilot MCP; isolated campaign containers) | Compliant | Compliant | Compliant |
|
||||
| **D3** (US+CA priority + FX; `ttFutures` out of scope) | Compliant | Compliant | Compliant |
|
||||
| **D4** (Incremental `web-app` evolution; no rewrite) | Compliant | Compliant | Risk of `web-api` / `PipelinePage` BullMQ contract drift |
|
||||
| **D5** (Cross-source entity resolution in `data-pipeline`) | Compliant | Compliant — matches `PLATFORM-PLAN.md` §4 (`data-pipeline` TS + `curate-etl` Rust) and `DATA-CONTRACTS.md` §3A (`mongodb::bson::RawDocumentBuf` cursors) | **Reopens §4 layer table** (moves TS entity resolution & orchestration out of TS `data-pipeline` into Rust; requires director sign-off to amend `PLATFORM-PLAN.md`) |
|
||||
| **D6** (IB Margin `USD`/`CAD` on isolated `9900K`) | Compliant (no paper/live touch) | Compliant (no paper/live touch) | Compliant (no paper/live touch) |
|
||||
| **D7** (Multi-strategy scope; no macro surprises / Form 4 $) | Compliant | Compliant | Compliant |
|
||||
| **D8** (Incremental Research Playground) | Compliant | Compliant | Compliant (delays M2 timeline) |
|
||||
| **D9** (`marimo` Python labs) | Compliant | Compliant | Compliant |
|
||||
| **D10** (Rolling 6-month Air-Gapped Vault + Post-2023 Recency) | Compliant | Compliant | Compliant |
|
||||
| **D11** (Materialized batch feature jobs; no Python→TS rewrites) | Compliant | Compliant | Compliant |
|
||||
| **D12** (Read-only Studio `library.yml` + Postgres findings) | Compliant | Compliant | Compliant |
|
||||
|
||||
### QA Database Safety Rules (`AGENTS.md`)
|
||||
|
||||
| Safety Rule | Option A | Option B (Recommended) | Option C |
|
||||
| --- | --- | --- | --- |
|
||||
| **Never drop/reset/write QA MongoDB (`localhost:27017/stock`) from `dev` or tests** | Enforced by `assertEnvironmentSafety()` + `MongoDBClient` `mongoReadOnly: true` + `studio_stock_bot_read` | **Must implement Rust read-only guard parity** before enabling `--mongo-uri`: (1) connect strictly via `MONGODB_READ_URI` with server-side `read@stock` user (`studio_stock_bot_read`); (2) reject `trading_admin` and any non-read-only URI targeting loopback/local-LAN port `27017` (matching `env-safety.ts` IPv4/octal/hex/loopback rules); (3) expose **only** `find` / `RawDocumentBuf` cursor reads in a sealed Rust module with no `insert`/`update`/`delete`/`drop`/`create_index`/`run_command` surface; (4) unit-test all rejected URIs offline | Requires Option B's Rust Mongo guard **plus** full Rust parity for PostgreSQL dev-isolation guards (`assertSecurityMasterPersistSafety`, `NODE_ENV=development` blocking `localhost:5432/trading_bot`, `pg_advisory_xact_lock`, and `rejectDestructiveSync`) |
|
||||
| **Tests never mutate QA Postgres (`trading_bot`) or QA Mongo (`stock`)** | Compliant (`stock_bot_safety*` + in-memory fakes) | Compliant — retain file-based CLI mode so all `cargo test --workspace --lib --offline` tests run with zero DB connections | Compliant only if every ported Postgres test preserves isolated `stock_bot_safety*` schema creation/teardown |
|
||||
| **No `data-ingestion` or `9900K` live/paper side effects** | Compliant | Compliant | Compliant |
|
||||
|
||||
---
|
||||
|
||||
## 6. Recommendation, Implied Follow-Up Tasks & What Not to Port
|
||||
|
||||
### Recommendation
|
||||
|
||||
**Select Option B.** It captures virtually 100% of the real throughput and NVMe-storage benefit of Rust where the data is actually large (`845.7M` `eodPrices`, `51.5M` `qmPrices`, `30.5M` `qmFilings`, and M2's `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts`), aligns word-for-word with `design/PLATFORM-PLAN.md` §4 and `design/DATA-CONTRACTS.md` §3A, requires no reopened locked decisions, and avoids risking or delaying M2 to rewrite 20k LOC of already-fast, heavily-tested TypeScript security-master logic.
|
||||
|
||||
### Implied Follow-Up Tasks (Director-Gated — Not Yet Queued or Enacted)
|
||||
|
||||
If the director approves Option B, the concrete follow-up sequence is:
|
||||
|
||||
1. **Add Rust read-only MongoDB safety guard (`tools/curate-etl/src/mongo_safety.rs`):** Port the URI/host/loopback/IPv4-normalization and `trading_admin`-blocking rules from `apps/stock/config/src/env-safety.ts` with offline unit tests mirroring `test/unit/environment-safety*.test.ts`.
|
||||
2. **Add sealed read-only MongoDB `RawDocumentBuf` cursor adapter (`tools/curate-etl/src/mongo_stream.rs`):** Add exact-pinned `mongodb` (`bson-3`) + minimal `tokio` to `tools/curate-etl/Cargo.toml`, exposing only allowlisted read-only `find` streams feeding the existing `bson_*` decoders (zero write/admin methods exposed).
|
||||
3. **Wire `--mongo-uri` / `MONGODB_READ_URI` cursor mode into `curate-bars-1d` and `curate-events` (Stage 1 — cursor swap + adoption parity & provenance checks):** Allow bulk M1 commands to stream directly from read-only QA MongoDB without intermediate `.bson` files while preserving `--eod-prices <path>` file mode for offline fixture replay. **Adoption gate:** assert byte-identical file-versus-cursor output parity on pinned fixtures, and emit a per-run provenance manifest recording the source snapshot or retained input identifier, exact query bounds (`filter`/date bounds and run timestamp), and the pinned `curate-inputs` security-master `generationId` (so production datasets remain traceable even if a provider later corrects a bar or filing).
|
||||
4. **Add partitioned bounded-memory streaming & overlapped read/write pipelining to `curate-bars-1d` and `curate-events` (Stage 2 — global-backfill RAM & I/O):** Partition MongoDB queries by calendar year or listing-key range and pipeline async cursor reads with `rayon` Parquet writes so global `845.7M` `eodPrices` and `30.5M` `qmFilings` runs fit comfortably inside `quant`'s `125 GiB` RAM instead of buffering all decoded rows in memory.
|
||||
5. **Reuse the Rust cursor adapter for M2 `curate-bars-1m` (QuestDB `10.2.0` ILP v2) and `curate-ceo-posts`:** Stream `eodIntraday1M` (`3.40B`, **un-adjusting** retroactively split-adjusted OHLCV via `qmSplits`), `qmIntraday` (`173.3M`, ingesting **already-raw** `open..close` and `sharevolume` directly without split un-adjustment), `CAD.FOREX` `1m` (`5.2M`), and `ceoPosts` (`14.8M`) directly from read-only MongoDB with zero `.bson` scratch files; enforce the M2 exit-criterion split-boundary comparison on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirming `bars_1m` session closes match raw `bars_1d` closes within `0.5%`.
|
||||
6. **Keep `run-export-raw-bson.ts` as a diagnostic/fixture tool (optional deprecation later):** Retain T-117 for bounded `--limit` fixture captures and offline debugging; remove it from the bulk production path once Step 3 (and Step 4 for global backfills) is verified on `quant`.
|
||||
|
||||
### What Should NOT Be Ported to Rust
|
||||
|
||||
- **Pass 1–6 Security Master (`apps/stock/data-pipeline/src/security-master/` — 17,924 LOC, 40 test files):** Logic- and review-bound, runs in sub-second synthetic time, and has complex domain heuristics (ISIN/CUSIP rescue, IB ATS routing, ticker-reuse spans, OTC delisting chains, override precedence) that are faster to inspect and iterate in TypeScript.
|
||||
- **PostgreSQL Security-Master Persistence (`persist.ts`) & TSV Exporter (`export-curate-inputs.ts`):** Already batched via `UNNEST` / server-side `NO SCROLL` cursor (`2.36 s` / `140k` rows; `0.40 s` / `500k` mappings) and tightly integrated with `@stock-bot/postgres` migrations and `assertSecurityMasterPersistSafety()`.
|
||||
- **Field-Shape Probe (`source-field-shapes.ts` / `probe-source-field-shapes.ts`):** Bounded `<= 10k`-doc diagnostic utility.
|
||||
- **Service Control Plane (`handlers/`, `repositories/`, `routes/`, `index.ts`):** BullMQ `{data-pipeline_exchanges}`/`{data-pipeline_symbols}` queue consumers (`getFullQueueName` in `libs/core/queue/src/service-utils.ts`), `PipelineSyncRepository`, and Hono `GET /health` tightly integrated with `@stock-bot/di`, `@stock-bot/queue`, `@stock-bot/types`, and `web-api`.
|
||||
|
||||
---
|
||||
|
||||
## 7. Not Verified
|
||||
|
||||
The following items were **not measured** in this docs-only spike and can only be verified on the `quant` host (`10.0.0.51`) or against live read-only QA MongoDB / dev PostgreSQL:
|
||||
|
||||
1. **Live MongoDB cursor throughput, WiredTiger contention, and end-to-end Option B wall-time speedup:** All `export-raw-bson.ts` (`3.57M–3.83M docs/s`) and `curate-etl` (`1.87M rows/s` with `rayon` write) numbers are local synthetic benchmarks. Actual `quant` wall time and the net end-to-end speedup of Option B (both Stage 1 cursor-only and Stage 2 overlapped I/O) are **unmeasured** and depend on WiredTiger disk reads (`--wiredTigerCacheSizeGB 16`), localhost TCP framing, BSON wire overhead on `stock` (`~638 GB`), and NVMe contention.
|
||||
2. **Real BSON document sizes & NVMe scratch footprint:** The intermediate `.bson` size estimates — **~127–225 GiB peak file capacity (~255–450 GiB total write+read I/O)** for `845.7M` `eodPrices` at synthetic `161.7–285.6 B/doc`, and **~499–832 GiB peak file capacity (~998–1,664 GiB total write+read I/O)** for `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` at assumed `150–250 B/doc` (binary `1 GiB = 2^30` bytes) — extrapolate from synthetic document byte sizes; actual uncompressed BSON sizes in QA MongoDB are unmeasured.
|
||||
3. **`quant` 24-thread `rayon` scaling and peak RAM:** The `4.72x` parallel Parquet write speedup (`94.42 ms` vs `445.79 ms`) was measured locally on a 32-thread host on `1,000,000` synthetic rows. Peak RAM and scaling on `quant` (`12900K`, 24 threads, `125 GiB` RAM) for the US+CA subset (~100–150M `eodPrices` rows, estimated `20–30 GiB` peak RAM) vs. full `845.7M` global rows (`> 160 GiB` unsharded, requiring date/key sharding or `--threads 1`) remain unverified.
|
||||
4. **Live `bar-spans.ts` and Pass 4 `sample-closes.ts` wall time:** MongoDB `$group` aggregation time on `845.7M` `eodPrices` and `51.5M` `qmPrices`, plus live 25-date `{ date: { $in: sampleDates } }` index selectivity, have not been timed against live QA MongoDB.
|
||||
5. **Unverified live provider field shapes:** Exact field names and BSON types on live QA MongoDB for `ceoShorts` (`--shares-short-field`, `timestamp` unit), `qmFilings` (`--filings-form-type-field`, `symbol` vs `qmSearchCode`), `qmEarnings` optional fields, `qmDividends` (`amount`/`currency`), `teMarketData` (`t` epoch unit), and `qmPrices.date` string vs `DateTime` format remain pending the first host run of `probe-source-field-shapes.ts`.
|
||||
6. **QuestDB `10.2.0` ILP v2 throughput (M2):** Multi-socket Rust ILP v2 ingestion rate into `bars_1m` (`PARTITION BY MONTH`, `DEDUP UPSERT KEYS(ts, listing_id)`) on `quant` has not been benchmarked.
|
||||
7. **Rust `mongodb` crate compile time and transitive crate count:** Exact transitive dependency footprint and offline build time for `mongodb` (`bson-3`) + `tokio` inside this workspace have not been measured because this spike adds no crates.
|
||||
192
test/unit/data-pipeline-rust-evaluation-doc.test.ts
Normal file
192
test/unit/data-pipeline-rust-evaluation-doc.test.ts
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
|
||||
// Guards the T-124 decision brief (design/data-pipeline/rust-migration-evaluation.md) against
|
||||
// silent drift: it must stay linked, keep its seven required sections, keep internally consistent
|
||||
// totals and derived figures, and every quoted benchmark figure must still appear verbatim in the
|
||||
// README it cites. Live file counts are deliberately not pinned here (they change with every
|
||||
// data-pipeline task); the document's own reproducible commands cover that at its commit.
|
||||
const repoRoot = join(import.meta.dir, '..', '..');
|
||||
const evalRel = 'design/data-pipeline/rust-migration-evaluation.md';
|
||||
const evalPath = join(repoRoot, evalRel);
|
||||
const designReadmePath = join(repoRoot, 'design/README.md');
|
||||
const curateReadme = readFileSync(join(repoRoot, 'tools/curate-etl/README.md'), 'utf8');
|
||||
const pipelineReadme = readFileSync(join(repoRoot, 'apps/stock/data-pipeline/README.md'), 'utf8');
|
||||
const doc = readFileSync(evalPath, 'utf8');
|
||||
|
||||
function num(text: string): number {
|
||||
return Number(text.replace(/[`,*]/g, '').trim());
|
||||
}
|
||||
|
||||
function section(title: RegExp): string {
|
||||
const lines = doc.split('\n');
|
||||
const start = lines.findIndex(line => /^## /.test(line) && title.test(line));
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
const rest = lines.slice(start + 1);
|
||||
const end = rest.findIndex(line => /^## /.test(line));
|
||||
return rest.slice(0, end === -1 ? undefined : end).join('\n');
|
||||
}
|
||||
|
||||
function tableRows(body: string, firstCell: RegExp): string[][] {
|
||||
return body
|
||||
.split('\n')
|
||||
.filter(line => line.startsWith('|'))
|
||||
.map(line => line.split('|').slice(1, -1).map(cell => cell.trim()))
|
||||
.filter(cells => firstCell.test(cells[0] ?? ''));
|
||||
}
|
||||
|
||||
describe('data-pipeline Rust migration evaluation document', () => {
|
||||
test('design/README.md links to the evaluation and the link resolves', () => {
|
||||
const readme = readFileSync(designReadmePath, 'utf8');
|
||||
expect(readme).toContain('](data-pipeline/rust-migration-evaluation.md)');
|
||||
expect(existsSync(evalPath)).toBe(true);
|
||||
});
|
||||
|
||||
test('contains all seven required sections in order', () => {
|
||||
const headings = doc.split('\n').filter(line => /^## \d\./.test(line));
|
||||
expect(headings.map(h => h.match(/^## (\d)\./)![1])).toEqual(['1', '2', '3', '4', '5', '6', '7']);
|
||||
expect(headings[0]).toMatch(/Inventory/);
|
||||
expect(headings[1]).toMatch(/Rust/);
|
||||
expect(headings[2]).toMatch(/Workload Classification/);
|
||||
expect(headings[3]).toMatch(/Options Comparison/);
|
||||
expect(headings[4]).toMatch(/Compliance/);
|
||||
expect(headings[5]).toMatch(/Recommendation/);
|
||||
expect(headings[6]).toMatch(/Not Verified/);
|
||||
});
|
||||
|
||||
test('inventory covers the T-89/T-105 CLI, T-116 TSV exporter, T-117 raw-BSON exporter and web-api coupling', () => {
|
||||
const inventory = section(/^## 1\./);
|
||||
for (const needle of ['T-89', 'T-105', 'T-116', 'T-117', 'run-security-master.ts', 'export-curate-inputs.ts', 'export-raw-bson.ts', '{data-pipeline_exchanges}', '{data-pipeline_symbols}', 'getFullQueueName', '@stock-bot/types', 'mongoReadOnly: true', 'assertEnvironmentSafety()']) {
|
||||
expect(inventory).toContain(needle);
|
||||
}
|
||||
// The commands that make the counts reproducible are printed verbatim.
|
||||
expect(inventory).toContain("find \"apps/stock/data-pipeline/src/$area\" -type f -name '*.ts'");
|
||||
});
|
||||
|
||||
test('every path referenced by the inventory commands exists', () => {
|
||||
const inventory = section(/^## 1\./);
|
||||
const block = inventory.match(/```bash\n([\s\S]*?)```/)![1]!;
|
||||
for (const area of ['security-master', 'normalization', 'handlers', 'repositories', 'routes', 'types']) {
|
||||
expect(existsSync(join(repoRoot, 'apps/stock/data-pipeline/src', area))).toBe(true);
|
||||
}
|
||||
const paths = new Set(block.match(/(?:apps|test|tools)\/[\w./-]+/g) ?? []);
|
||||
expect(paths.size).toBeGreaterThan(0);
|
||||
for (const path of paths) {
|
||||
expect({ path, exists: existsSync(join(repoRoot, path)) }).toEqual({ path, exists: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('per-area inventory rows sum to the stated src/ total', () => {
|
||||
const rows = tableRows(section(/^## 1\./), /^`(security-master|normalization|handlers|repositories|routes|types)\/`$|^`index\.ts`$|Total/);
|
||||
const areas = rows.filter(r => !/Total/.test(r[0]!));
|
||||
const total = rows.find(r => /Total/.test(r[0]!))!;
|
||||
expect(areas).toHaveLength(7);
|
||||
const sum = (col: number) => areas.reduce((acc, r) => acc + (Number.isNaN(num(r[col]!)) ? 0 : num(r[col]!)), 0);
|
||||
expect(sum(1)).toBe(num(total[1]!));
|
||||
expect(sum(2)).toBe(num(total[2]!));
|
||||
// pipeline-safety.test.ts is attributed to handlers/ and shared with repositories/ (counted once).
|
||||
expect(sum(3)).toBe(num(total[3]!));
|
||||
expect(sum(4)).toBe(num(total[4]!));
|
||||
});
|
||||
|
||||
test('curate-etl module groups sum to the stated Rust total and the non-test/test split', () => {
|
||||
const rows = tableRows(section(/^## 2\./), /./).filter(r => /^\d/.test(r[1]?.replace(/\*/g, '') ?? ''));
|
||||
const total = rows.find(r => /Total/.test(r[0]!))!;
|
||||
const groups = rows.filter(r => r !== total);
|
||||
const tests = groups.find(r => /test modules/.test(r[0]!))!;
|
||||
const files = groups.reduce((acc, r) => acc + num(r[1]!), 0);
|
||||
const loc = groups.reduce((acc, r) => acc + num(r[2]!), 0);
|
||||
expect(files).toBe(num(total[1]!));
|
||||
expect(loc).toBe(num(total[2]!));
|
||||
expect(total[3]).toContain(`${files - num(tests[1]!)} non-test files (${(loc - num(tests[2]!)).toLocaleString('en-US')} LOC)`);
|
||||
expect(total[3]).toContain(`${num(tests[1]!)} test files (${num(tests[2]!).toLocaleString('en-US')} LOC)`);
|
||||
});
|
||||
|
||||
test('derived figures in the brief are arithmetically consistent', () => {
|
||||
// 88.1% of src/ LOC is security-master/.
|
||||
expect(doc).toContain('88.1%');
|
||||
expect(((17_924 / 20_349) * 100).toFixed(1)).toBe('88.1');
|
||||
// rayon write speedup from the dated local re-run.
|
||||
expect(doc).toContain('4.72x');
|
||||
expect((445.79 / 94.42).toFixed(2)).toBe('4.72');
|
||||
// Scratch estimates are binary GiB: docs x bytes/doc / 2^30, total I/O = 2x peak.
|
||||
const gib = (docs: number, bytes: number) => Math.round((docs * bytes) / 2 ** 30);
|
||||
expect([gib(845.7e6, 161.7), gib(845.7e6, 285.6)]).toEqual([127, 225]);
|
||||
expect([gib(3.40e9 + 173.3e6, 150), gib(3.40e9 + 173.3e6, 250)]).toEqual([499, 832]);
|
||||
expect(doc).toContain('~127–225 GiB');
|
||||
expect(doc).toContain('~255–450 GiB');
|
||||
expect(doc).toContain('~499–832 GiB');
|
||||
expect(doc).toContain('~998–1,664 GiB');
|
||||
expect(doc).not.toMatch(/\d\s?GB peak/);
|
||||
});
|
||||
|
||||
test('every README-sourced benchmark row quotes figures present in the cited README', () => {
|
||||
const rows = tableRows(section(/^## 2\./), /./).filter(r => /README\.md/.test(r[1] ?? ''));
|
||||
expect(rows.length).toBeGreaterThanOrEqual(15);
|
||||
for (const [name, source, command, result] of rows) {
|
||||
const readme = source!.includes('tools/curate-etl/README.md') ? curateReadme : pipelineReadme;
|
||||
// Each row states a date or explicitly says the README omits one.
|
||||
expect({ name, dated: /\d{4}-\d{2}-\d{2}|date omitted/.test(source!) }).toEqual({ name, dated: true });
|
||||
// The command is copied in full (no ellipsis abbreviations) and appears in the README.
|
||||
const cmd = command!.replace(/`/g, '');
|
||||
expect({ name, abbreviated: cmd.includes('...') || cmd.includes('…') }).toEqual({ name, abbreviated: false });
|
||||
const bin = cmd.match(/-- (\S+)/)?.[1] ?? cmd.match(/(\S+\.(?:test\.)?ts)/)?.[1];
|
||||
expect({ name, bin, inReadme: readme.includes(bin!) }).toEqual({ name, bin, inReadme: true });
|
||||
// Every millisecond figure in the bolded result appears verbatim in the README.
|
||||
const bold = (result!.match(/\*\*([^*]+)\*\*/g) ?? []).join(' ');
|
||||
for (const ms of bold.match(/[\d,]+\.\d+(?= ms)/g) ?? []) {
|
||||
expect({ name, ms, inReadme: readme.includes(ms) || readme.includes(ms.replace(/,/g, '')) }).toEqual({ name, ms, inReadme: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('the only non-README benchmark is a labelled local synthetic re-run, never quant or live Mongo', () => {
|
||||
const rows = tableRows(section(/^## 2\./), /^`/).filter(r => r.length === 4 && !/README\.md/.test(r[1]!));
|
||||
expect(rows).toHaveLength(1);
|
||||
const [, source, command] = rows[0]!;
|
||||
expect(source).toMatch(/Local sandbox re-run/);
|
||||
expect(source).toMatch(/2026-11-29/);
|
||||
expect(source).toMatch(/synthetic/);
|
||||
expect(command).toContain('--offline');
|
||||
expect(section(/^## 2\./)).toContain('Zero Live QA MongoDB or `quant` Runs');
|
||||
});
|
||||
|
||||
test('options table compares at least three options across the required dimensions', () => {
|
||||
const body = section(/^## 4\./);
|
||||
const header = body.split('\n').find(line => line.startsWith('| Dimension'))!;
|
||||
expect(header.match(/Option [A-Z]/g)!.length).toBeGreaterThanOrEqual(3);
|
||||
for (const dim of ['Estimated Effort', 'New Rust Crates Required', 'Expected Runtime', 'Key Risks', 'Impact on M2']) {
|
||||
expect(body).toContain(dim);
|
||||
}
|
||||
expect(body).toMatch(/End-to-end wall-time speedup is unmeasured/);
|
||||
});
|
||||
|
||||
test('compliance matrix covers D1–D12 and QA safety rules for every option', () => {
|
||||
const body = section(/^## 5\./);
|
||||
for (let d = 1; d <= 12; d++) {
|
||||
const row = tableRows(body, new RegExp(`^\\*\\*D${d}\\*\\*`));
|
||||
expect({ d, rows: row.length, cells: row[0]?.length }).toEqual({ d, rows: 1, cells: 4 });
|
||||
}
|
||||
expect(body).toMatch(/Reopens §4 layer table/);
|
||||
for (const needle of ['studio_stock_bot_read', 'trading_admin', 'stock_bot_safety*']) {
|
||||
expect(body).toContain(needle);
|
||||
}
|
||||
});
|
||||
|
||||
test('gives exactly one recommendation, director-gated follow-ups and a non-port list', () => {
|
||||
const body = section(/^## 6\./);
|
||||
expect(body.match(/\*\*Select Option [A-C]\.\*\*/g)).toEqual(['**Select Option B.**']);
|
||||
expect(body).toMatch(/Director-Gated — Not Yet Queued or Enacted/);
|
||||
expect(body.match(/^\d+\. \*\*/gm)!.length).toBeGreaterThanOrEqual(3);
|
||||
expect(body).toContain('### What Should NOT Be Ported to Rust');
|
||||
});
|
||||
|
||||
test('every relative Markdown link in the brief resolves', () => {
|
||||
const links = [...doc.matchAll(/\]\(([^)#\s]+)(?:#[^)]*)?\)/g)].map(m => m[1]!).filter(l => !/^[a-z]+:/i.test(l));
|
||||
for (const link of links) {
|
||||
const target = resolve(dirname(evalPath), link);
|
||||
expect({ link, exists: existsSync(target) }).toEqual({ link, exists: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -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`, and the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`.
|
||||
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`).
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -1493,6 +1493,66 @@ Measured locally (`2026-11-29`, default `500,000` rows; two back-to-back runs wi
|
|||
- **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the `provider_mapping` namespace (for example, the QuoteMedia security ID, not a bare ticker — the security master records distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` for the same symbol and exchange, so switching earnings to bare `symbol` can merge distinct identities or drop rows). If a live `qmFilings` export lacks that unambiguous key, prepare the export with verified QuoteMedia IDs and exclude unresolved rows rather than downgrading `qmEarnings` to bare tickers.
|
||||
- **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc<str>` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope.
|
||||
|
||||
## Read-Only MongoDB URI Safety Guard (`M1.2ak`)
|
||||
|
||||
Pure, offline, `std`-only MongoDB URI safety guard (`src/mongo_safety.rs`, zero new crates, no sockets, no DNS resolution, no subprocesses) that ports the QA MongoDB target-classification rules from `apps/stock/config/src/env-safety.ts` before any Rust code may open a MongoDB connection.
|
||||
|
||||
### Public API
|
||||
|
||||
- `parse_mongo_target(uri: &str) -> Result<MongoTarget, MongoSafetyError>` — parses `mongodb://` and `mongodb+srv://` URIs, splits authority at `/` or `?` (never `#`), percent-decodes usernames (strict UTF-8, without converting `+` to space), iteratively percent-decodes seed hosts up to `8` passes (handling bracketed IPv6 with zone IDs and `mongodb://` `.sock` Unix domain sockets), and rejects control characters, Unicode whitespace, unencoded `#` or multiple `@` in authority, `@` in path/query when authority has no credentials, invalid percent-encoding, and forbidden decoded host characters.
|
||||
- `is_qa_mongo_target(target: &MongoTarget, local_hosts: &LocalHosts) -> bool` — returns `true` when any seed host is loopback (`localhost`, trailing-dot/case variants, `0.0.0.0`, `127.0.0.0/8` in dotted, shorthand `127.1`, decimal `2130706433`, hex `0x7f000001`, octal `0177.0.0.1`, leading-zero decimal `0127.0.0.1`, IPv6 `::` / `::1` with optional zone ID, and IPv4-mapped `::ffff:127.0.0.0/8` / `::ffff:0.0.0.0`) or matches an injected `LocalHosts` entry on port `27017` (or omitted/default port), regardless of database path.
|
||||
- `LocalHosts` — deterministic injected set (`LocalHosts::empty()`, `new(...)`, `from_hostname_and_ips(...)`, `with_host(...)`, `contains(...)`) plus `LocalHosts::detect()`, which is **best-effort** and `std`-only (reads `HOSTNAME` and `/etc/hostname` without NIC enumeration or DNS lookups; multi-homed callers should inject LAN IPs via `LocalHosts::from_hostname_and_ips`).
|
||||
- `assert_read_only_mongo_uri(uri, policy: &ReadOnlyPolicy, local_hosts) -> Result<ValidatedReadOnlyMongoUri, MongoSafetyError>` — fail-closed guard returning a `ValidatedReadOnlyMongoUri` proof token whose fields are private and whose only public constructor is `assert_read_only_mongo_uri`.
|
||||
- **Password redaction:** `ValidatedReadOnlyMongoUri`'s `Display`, `Debug`, and `redacted()` always replace the password between the first `:` and `@` in userinfo with `[REDACTED]`. `MongoSafetyError` variants never store raw URIs, raw authorities, or passwords.
|
||||
- **No URI query-option parsing:** beyond authority/remainder splitting and the no-credentials remainder-`@` check, URI query options are intentionally not parsed or validated (matching `apps/stock/config/src/env-safety.ts`).
|
||||
- **Unix domain sockets:** `.sock` Unix-socket hosts (e.g. `%2Ftmp%2Fmongodb-27017.sock`) are never classified as QA targets (same as `env-safety.ts`).
|
||||
|
||||
### Intentional Stricter-than-`env-safety.ts` Differences
|
||||
|
||||
Target classification (`parse_mongo_target` + `is_qa_mongo_target`) mirrors all five `test/unit/environment-safety*.test.ts` suites (including the 42-case `hostSpellings × ports` matrix, the 3,000-iteration seeded percent-encoding sweep, and all 30,000 cases per authority-split fuzz seed `0x7e28` / `0x28e7`) with identical QA / not-QA / rejected outcomes **except for the intentional stricter rules listed below**. `parse_mongo_target`, `is_qa_mongo_target`, and `assert_read_only_mongo_uri` are deliberately stricter than `env-safety.ts` in eight ways for read-only ETL safety:
|
||||
|
||||
1. **Global case-insensitive `trading_admin` ban:** rejects percent-decoded `trading_admin` (ASCII case-insensitive) on **any** host (QA, dev, or remote), even if a caller adds it to `ReadOnlyPolicy::allowed_read_users` (whereas `env-safety.ts` only checks `username === 'trading_admin'` on QA targets for dev `dataPipeline`).
|
||||
2. **Mandatory QA credentials & allowlist:** any QA target must provide a username present in `ReadOnlyPolicy::allowed_read_users` (default: `["studio_stock_bot_read"]`, exact match after percent-decoding); missing credentials and non-allowlisted users are rejected.
|
||||
3. **Rejection of empty, malformed, or invalid bracketed-IPv6 host segments:** URIs like `mongodb://u:p@bad:port,localhost:27017/stock`, `mongodb://u:p@localhost:27018,,localhost:27017/stock`, or `mongodb://u:p@[fe80::g]:27017,localhost:27017/stock` still classify as QA in `parse_mongo_target` / `is_qa_mongo_target` (matching `env-safety.ts`), and are rejected fail-closed with `MalformedHostSegment` by `assert_read_only_mongo_uri` (matching `libs/core/config/src/schemas/database.schema.ts`). Single-seed malformed bracketed IPv6 literals such as `[fe80::g]:27017` are rejected with `NoValidHosts`.
|
||||
4. **Strict `mongodb+srv://` seed rules:** `assert_read_only_mongo_uri` rejects `mongodb+srv://` URIs with multiple hosts or any explicit `:` port suffix (`InvalidSrvTarget`), matching `database.schema.ts`.
|
||||
5. **No-credentials remainder-`@` check and strict username percent-decoding:** rejects unencoded `@` in path/query when authority has no `@` (matching `database.schema.ts`), and rejects invalid percent-encoding in the username (e.g. `%ff`, failing closed with `InvalidUsernameEncoding` instead of falling back to the raw username string).
|
||||
6. **No silent trimming of leading/trailing whitespace:** `env-safety.ts` calls `uri.trim()` before checking `/\s/`, whereas `parse_mongo_target` rejects any Unicode whitespace anywhere in the URI (including leading or trailing spaces) with `ForbiddenWhitespace`.
|
||||
7. **Leading-zero decimal LAN IPs matched against `LocalHosts`:** `is_qa_mongo_target` normalizes 4-part decimal IPv4 spellings with leading zeros (e.g. `192.168.001.050:27017`) before checking `LocalHosts`, flagging them as QA even where `env-safety.ts` does not.
|
||||
8. **Machine's own zoned link-local IPv6 matched against `LocalHosts`:** `is_qa_mongo_target` strips `%zone` suffixes when matching bracketed IPv6 hosts against `LocalHosts` (e.g. `[fe80::1234:5678%25eth0]:27017`), flagging the machine's own link-local IPv6 on port `27017` as QA even where `env-safety.ts` misses it.
|
||||
|
||||
## Driver-Independent MongoDB Raw-BSON Cursor Seam (`M1.2al`)
|
||||
|
||||
Library-only, driver-independent read-only MongoDB raw-BSON cursor seam (`src/mongo_stream.rs`, tested offline in `src/mongo_stream_tests.rs`) bridging the read-only safety model (`src/mongo_safety.rs`) into the existing `bson_stream` zero-copy decoders (`RawBsonChunkReader` and `decode_*_stream`) with zero new dependencies and zero CLI/command wiring yet.
|
||||
|
||||
### 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.
|
||||
|
||||
### Public API & Sealing Guarantees
|
||||
|
||||
- **Closed collection allowlist (`SourceCollection`):** 8 variants matching `RAW_BSON_EXPORT_COLLECTIONS` in `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts` in exact order (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`). No API accepts a free-form collection name string.
|
||||
- **Typed read spec (`MongoReadSpec`, `MongoDateRange`, `FilterDateValue`, `build_filter_document`):** validates `batch_size` (`1..=100_000`, default `4_096`), `limit` (`1..=i64::MAX`), `max_doc_bytes` (`>= 5`, default `16 MiB + 16 KiB`), non-blank `key_eq`, and half-open `[gte, lt)` `date_range` (rejected on `teMarketData`; `qmFilings.timefiled` server-side string ranges require Eastern calendar-day boundaries `YYYY-MM-DD` so neither UTC offsets nor fall-back DST local-string inversions can silently miss filings), building `bson::Document` via `Document::from_iter(...)`.
|
||||
- **Driver-independent seam (`RawDocumentSource`, `SliceRawDocumentSource`, `VecRawDocumentSource`) + bounded-memory `io::Read` adapter (`RawBsonCursorReader<S>`):** validates every raw BSON frame (`len >= 5`, `len <= max_doc_bytes`, 4-byte LE length prefix `== len`, trailing `0x00`), copies directly into the caller's buffer when it fits, spills only the unread tail of a single current document into a reused `pending` buffer, tracks `docs_read()` / `bytes_read()` / `pending_capacity()`, and surfaces mid-stream errors as sticky `io::Error`s carrying `MongoStreamError`.
|
||||
- **Error redaction (`MongoStreamError`, `MongoStreamError::redacted_source`):** never stores raw URIs or passwords; sanitizes raw URI, raw password, percent-decoded password, and embedded `mongodb://` / `mongodb+srv://` userinfo passwords (including passwords containing punctuation such as `,`, `;`, quotes, brackets, or `@`) to `[REDACTED]` (reusing `mongo_safety::redact_mongo_uri_password`).
|
||||
|
||||
### `bench-mongo-stream`
|
||||
|
||||
Offline fixed-seed benchmark comparing decoding `1,000,000` synthetic `eodPrices` documents (`285,639,152` bytes) through plain `io::Cursor<&[u8]>` → `decode_eod_price_stream` vs. `SliceRawDocumentSource` → `RawBsonCursorReader` → `decode_eod_price_stream`:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-mongo-stream 1000000
|
||||
```
|
||||
|
||||
Measured locally (`2026-11-30`, two back-to-back offline runs on the final code with identical stats `decoded=995008`, `rejected=4992`, and checksum `0x05af9d2746d1b5e3`):
|
||||
|
||||
- **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
|
||||
|
||||
- **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).
|
||||
|
||||
## Exporting Input Files (`data-pipeline`)
|
||||
|
||||
All `curate-*` commands read local TSV and concatenated raw-BSON files produced by the read-only exporters in `@stock-bot/data-pipeline`:
|
||||
|
|
|
|||
|
|
@ -16,13 +16,15 @@ use parquet::file::reader::{FileReader, SerializedFileReader};
|
|||
|
||||
use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent};
|
||||
use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume};
|
||||
use crate::bson_eod_prices::{decode_eod_price_buffer, BsonEodDecodeStats};
|
||||
use crate::bson_eod_prices::{decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats};
|
||||
use crate::bson_qm_actions::{
|
||||
decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats,
|
||||
};
|
||||
use crate::bson_stream::{
|
||||
decode_eod_price_chunks, BsonStreamError, BsonStreamOptions, RawBsonChunkReader,
|
||||
decode_eod_price_chunks, decode_eod_price_stream, BsonStreamError, BsonStreamOptions,
|
||||
RawBsonChunkReader,
|
||||
};
|
||||
use crate::mongo_stream::{RawBsonCursorReader, SliceRawDocumentSource};
|
||||
use crate::corporate_actions::{
|
||||
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats,
|
||||
DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent,
|
||||
|
|
@ -87,6 +89,7 @@ pub const PARQUET_CORPORATE_ACTIONS_RAW_ROW_BYTES: usize = 72;
|
|||
pub const DEFAULT_BSON_EOD_PRICES_BENCH_ROWS: usize = 1_000_000;
|
||||
pub const DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS: usize = 1_000_000;
|
||||
pub const DEFAULT_BSON_STREAM_BENCH_ROWS: usize = 2_000_000;
|
||||
pub const DEFAULT_MONGO_STREAM_BENCH_ROWS: usize = 1_000_000;
|
||||
pub const BENCH_KEY_COUNT: usize = 20_000;
|
||||
pub const BENCH_EVENT_COUNT: usize = 19_000;
|
||||
pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000;
|
||||
|
|
@ -3992,6 +3995,150 @@ pub fn run_bson_stream_benchmark(rows: usize) -> Result<BsonStreamBenchReport, B
|
|||
})
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_mongo_stream_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct MongoStreamBenchReport {
|
||||
pub rows: usize,
|
||||
pub bytes: usize,
|
||||
pub plain_elapsed_ms: f64,
|
||||
pub plain_docs_per_sec: f64,
|
||||
pub plain_mib_per_sec: f64,
|
||||
pub cursor_elapsed_ms: f64,
|
||||
pub cursor_docs_per_sec: f64,
|
||||
pub cursor_mib_per_sec: f64,
|
||||
pub cursor_to_plain_ratio: f64,
|
||||
pub peak_pending_capacity: usize,
|
||||
pub checksum: u64,
|
||||
pub stats: BsonEodDecodeStats,
|
||||
}
|
||||
|
||||
/// Runs the offline fixed-seed `RawBsonCursorReader` vs plain in-memory `io::Cursor<&[u8]>`
|
||||
/// decode benchmark for `rows` synthetic `eodPrices` documents.
|
||||
pub fn run_mongo_stream_benchmark(rows: usize) -> Result<MongoStreamBenchReport, BsonStreamError> {
|
||||
if rows == 0 {
|
||||
return Ok(MongoStreamBenchReport {
|
||||
rows: 0,
|
||||
bytes: 0,
|
||||
plain_elapsed_ms: 0.0,
|
||||
plain_docs_per_sec: 0.0,
|
||||
plain_mib_per_sec: 0.0,
|
||||
cursor_elapsed_ms: 0.0,
|
||||
cursor_docs_per_sec: 0.0,
|
||||
cursor_mib_per_sec: 0.0,
|
||||
cursor_to_plain_ratio: 0.0,
|
||||
peak_pending_capacity: 0,
|
||||
checksum: 0,
|
||||
stats: BsonEodDecodeStats::default(),
|
||||
});
|
||||
}
|
||||
|
||||
let buffer = build_bson_eod_prices_bench_buffer(rows);
|
||||
let bytes = buffer.len();
|
||||
|
||||
let mut doc_slices: Vec<&[u8]> = Vec::with_capacity(rows);
|
||||
for doc_res in iter_raw_bson_docs(&buffer) {
|
||||
let raw_doc = doc_res.expect("synthetic benchmark buffer must have valid BSON frames");
|
||||
doc_slices.push(raw_doc.as_bytes());
|
||||
}
|
||||
assert_eq!(doc_slices.len(), rows);
|
||||
|
||||
// Baseline: plain in-memory io::Cursor<&[u8]> -> decode_eod_price_stream.
|
||||
let mut plain_hash = 0u64;
|
||||
let mut plain_err_hash = 0u64;
|
||||
let plain_start = Instant::now();
|
||||
let plain_stats = decode_eod_price_stream(
|
||||
io::Cursor::new(buffer.as_slice()),
|
||||
BsonStreamOptions::default(),
|
||||
|bar| {
|
||||
plain_hash = mix_bytes(plain_hash, bar.eod_search_code.as_bytes());
|
||||
plain_hash = mix_u64(plain_hash, bar.session_date as u64);
|
||||
plain_hash = mix_u64(plain_hash, bar.open.to_bits());
|
||||
plain_hash = mix_u64(plain_hash, bar.high.to_bits());
|
||||
plain_hash = mix_u64(plain_hash, bar.low.to_bits());
|
||||
plain_hash = mix_u64(plain_hash, bar.close.to_bits());
|
||||
plain_hash = mix_u64(plain_hash, bar.adj_volume.to_bits());
|
||||
},
|
||||
|offset, _err| {
|
||||
plain_err_hash = mix_u64(plain_err_hash, offset ^ 0xDEAD_BEEF_CAFE_BABEu64);
|
||||
},
|
||||
)?;
|
||||
let plain_elapsed_secs = plain_start.elapsed().as_secs_f64();
|
||||
let plain_checksum = black_box(plain_hash ^ plain_err_hash);
|
||||
|
||||
// Candidate: in-memory RawDocumentSource -> RawBsonCursorReader -> decode_eod_price_stream.
|
||||
let mut cursor_reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&doc_slices));
|
||||
let mut cursor_hash = 0u64;
|
||||
let mut cursor_err_hash = 0u64;
|
||||
let cursor_start = Instant::now();
|
||||
let cursor_stats = decode_eod_price_stream(
|
||||
&mut cursor_reader,
|
||||
BsonStreamOptions::default(),
|
||||
|bar| {
|
||||
cursor_hash = mix_bytes(cursor_hash, bar.eod_search_code.as_bytes());
|
||||
cursor_hash = mix_u64(cursor_hash, bar.session_date as u64);
|
||||
cursor_hash = mix_u64(cursor_hash, bar.open.to_bits());
|
||||
cursor_hash = mix_u64(cursor_hash, bar.high.to_bits());
|
||||
cursor_hash = mix_u64(cursor_hash, bar.low.to_bits());
|
||||
cursor_hash = mix_u64(cursor_hash, bar.close.to_bits());
|
||||
cursor_hash = mix_u64(cursor_hash, bar.adj_volume.to_bits());
|
||||
},
|
||||
|offset, _err| {
|
||||
cursor_err_hash = mix_u64(cursor_err_hash, offset ^ 0xDEAD_BEEF_CAFE_BABEu64);
|
||||
},
|
||||
)?;
|
||||
let cursor_elapsed_secs = cursor_start.elapsed().as_secs_f64();
|
||||
let cursor_checksum = black_box(cursor_hash ^ cursor_err_hash);
|
||||
let peak_pending_capacity = cursor_reader.pending_capacity();
|
||||
|
||||
assert_eq!(
|
||||
cursor_stats, plain_stats,
|
||||
"cursor reader decode stats must match plain in-memory reader"
|
||||
);
|
||||
assert_eq!(
|
||||
cursor_checksum, plain_checksum,
|
||||
"cursor reader decode checksum must match plain in-memory reader"
|
||||
);
|
||||
assert_eq!(cursor_reader.docs_read(), rows as u64);
|
||||
assert_eq!(cursor_reader.bytes_read(), bytes as u64);
|
||||
|
||||
let plain_elapsed_ms = plain_elapsed_secs * 1_000.0;
|
||||
let (plain_docs_per_sec, _) = compute_rates(rows, plain_elapsed_secs);
|
||||
let plain_mib_per_sec = if plain_elapsed_secs > 0.0 && plain_elapsed_secs.is_finite() {
|
||||
(bytes as f64 / (1024.0 * 1024.0)) / plain_elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let cursor_elapsed_ms = cursor_elapsed_secs * 1_000.0;
|
||||
let (cursor_docs_per_sec, _) = compute_rates(rows, cursor_elapsed_secs);
|
||||
let cursor_mib_per_sec = if cursor_elapsed_secs > 0.0 && cursor_elapsed_secs.is_finite() {
|
||||
(bytes as f64 / (1024.0 * 1024.0)) / cursor_elapsed_secs
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let cursor_to_plain_ratio = if plain_docs_per_sec > 0.0 {
|
||||
cursor_docs_per_sec / plain_docs_per_sec
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
Ok(MongoStreamBenchReport {
|
||||
rows,
|
||||
bytes,
|
||||
plain_elapsed_ms,
|
||||
plain_docs_per_sec,
|
||||
plain_mib_per_sec,
|
||||
cursor_elapsed_ms,
|
||||
cursor_docs_per_sec,
|
||||
cursor_mib_per_sec,
|
||||
cursor_to_plain_ratio,
|
||||
peak_pending_capacity,
|
||||
checksum: cursor_checksum,
|
||||
stats: cursor_stats,
|
||||
})
|
||||
}
|
||||
|
||||
/// Summary metrics produced by [`run_bson_qm_actions_benchmark`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct BsonQmActionsBenchReport {
|
||||
|
|
@ -11188,6 +11335,36 @@ mod tests {
|
|||
assert_eq!(report.stats, BsonEodDecodeStats::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mongo_stream_benchmark_small_run_is_deterministic_with_parity() {
|
||||
let a = run_mongo_stream_benchmark(2_000).expect("mongo-stream bench must succeed");
|
||||
let b = run_mongo_stream_benchmark(2_000).expect("mongo-stream bench must be deterministic");
|
||||
|
||||
assert_eq!(a.rows, 2_000);
|
||||
assert_eq!(a.bytes, b.bytes);
|
||||
assert!(a.bytes > 0);
|
||||
assert_eq!(a.checksum, b.checksum);
|
||||
assert_eq!(a.stats, b.stats);
|
||||
assert_eq!(a.stats.docs_in, 2_000);
|
||||
assert_eq!(a.stats.decoded + a.stats.rejected_total(), a.stats.docs_in);
|
||||
assert!(a.plain_docs_per_sec.is_finite() && a.plain_docs_per_sec >= 0.0);
|
||||
assert!(a.cursor_docs_per_sec.is_finite() && a.cursor_docs_per_sec >= 0.0);
|
||||
assert!(a.cursor_to_plain_ratio.is_finite() && a.cursor_to_plain_ratio >= 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mongo_stream_benchmark_zero_rows_handles_cleanly() {
|
||||
let report = run_mongo_stream_benchmark(0).expect("zero-row mongo-stream bench must succeed");
|
||||
assert_eq!(report.rows, 0);
|
||||
assert_eq!(report.bytes, 0);
|
||||
assert_eq!(report.plain_elapsed_ms, 0.0);
|
||||
assert_eq!(report.cursor_elapsed_ms, 0.0);
|
||||
assert_eq!(report.cursor_to_plain_ratio, 0.0);
|
||||
assert_eq!(report.peak_pending_capacity, 0);
|
||||
assert_eq!(report.checksum, 0);
|
||||
assert_eq!(report.stats, BsonEodDecodeStats::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bson_qm_actions_benchmark_small_run_is_deterministic() {
|
||||
let a = run_bson_qm_actions_benchmark(20_000);
|
||||
|
|
|
|||
|
|
@ -18,7 +18,8 @@ use crate::bench::{
|
|||
DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS,
|
||||
DEFAULT_CURATE_FX_CMD_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS,
|
||||
DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_BARS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS,
|
||||
DEFAULT_PARQUET_FX_BENCH_ROWS, DEFAULT_PARQUET_SHORTS_BENCH_ROWS,
|
||||
DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, DEFAULT_SHORTS_BENCH_ROWS,
|
||||
|
|
@ -65,6 +66,7 @@ pub enum CliAction {
|
|||
BenchBsonEodPrices(usize),
|
||||
BenchBsonQmActions(usize),
|
||||
BenchBsonStream(usize),
|
||||
BenchMongoStream(usize),
|
||||
BenchCurateBars(usize),
|
||||
BenchCurateBarsCmd(usize),
|
||||
BenchCurateShorts(usize),
|
||||
|
|
@ -116,6 +118,7 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
{name} bench-bson-eod-prices [rows] Run fixed-seed eodPrices raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_EOD_PRICES_BENCH_ROWS})\n\
|
||||
{name} bench-bson-qm-actions [rows] Run fixed-seed qmSplits/qmDividends raw BSON zero-copy decode benchmark (default: {DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS})\n\
|
||||
{name} bench-bson-stream [rows] Run fixed-seed eodPrices raw BSON stream vs buffer decode benchmark (default: {DEFAULT_BSON_STREAM_BENCH_ROWS})\n\
|
||||
{name} bench-mongo-stream [rows] Run offline fixed-seed RawBsonCursorReader vs plain in-memory eodPrices decode benchmark (default: {DEFAULT_MONGO_STREAM_BENCH_ROWS})\n\
|
||||
{name} bench-curate-bars [rows] Run fixed-seed bars_1d curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_BARS_BENCH_ROWS})\n\
|
||||
{name} bench-curate-bars-cmd [rows] Run fixed-seed end-to-end curate-bars-1d file->Parquet benchmark (default: {DEFAULT_CURATE_BARS_CMD_BENCH_ROWS})\n\
|
||||
{name} bench-curate-shorts [rows] Run fixed-seed shorts curation + Zstd Parquet benchmark (default: {DEFAULT_CURATE_SHORTS_BENCH_ROWS})\n\
|
||||
|
|
@ -160,6 +163,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} bench-bson-eod-prices [rows]\n\
|
||||
{name} bench-bson-qm-actions [rows]\n\
|
||||
{name} bench-bson-stream [rows]\n\
|
||||
{name} bench-mongo-stream [rows]\n\
|
||||
{name} bench-curate-bars [rows]\n\
|
||||
{name} bench-curate-bars-cmd [rows]\n\
|
||||
{name} bench-curate-shorts [rows]\n\
|
||||
|
|
@ -1057,6 +1061,16 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
["bench-bson-stream", _, ..] => {
|
||||
Err("too many arguments for bench-bson-stream".to_string())
|
||||
}
|
||||
["bench-mongo-stream"] => Ok(CliAction::BenchMongoStream(DEFAULT_MONGO_STREAM_BENCH_ROWS)),
|
||||
["bench-mongo-stream", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchMongoStream(n)),
|
||||
_ => Err(format!(
|
||||
"invalid row count '{raw}' (expected a positive integer)"
|
||||
)),
|
||||
},
|
||||
["bench-mongo-stream", _, ..] => {
|
||||
Err("too many arguments for bench-mongo-stream".to_string())
|
||||
}
|
||||
["bench-curate-bars"] => Ok(CliAction::BenchCurateBars(DEFAULT_CURATE_BARS_BENCH_ROWS)),
|
||||
["bench-curate-bars", raw] => match raw.parse::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchCurateBars(n)),
|
||||
|
|
@ -1512,6 +1526,22 @@ mod tests {
|
|||
assert!(parse_args(&to_args(&["bench-bson-stream", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_and_validates_bench_mongo_stream_args() {
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-mongo-stream"])),
|
||||
Ok(CliAction::BenchMongoStream(DEFAULT_MONGO_STREAM_BENCH_ROWS))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_args(&to_args(&["bench-mongo-stream", "100000"])),
|
||||
Ok(CliAction::BenchMongoStream(100_000))
|
||||
);
|
||||
assert!(parse_args(&to_args(&["bench-mongo-stream", "0"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-mongo-stream", "-5"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-mongo-stream", "abc"])).is_err());
|
||||
assert!(parse_args(&to_args(&["bench-mongo-stream", "10", "20"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_strings_mention_all_benchmarks() {
|
||||
let full = format_usage("curate-etl", "0.1.0");
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ pub mod cli;
|
|||
pub mod corporate_actions;
|
||||
pub mod events;
|
||||
pub mod fx;
|
||||
pub mod mongo_safety;
|
||||
pub mod mongo_stream;
|
||||
pub mod parquet_adj;
|
||||
pub mod parquet_bars;
|
||||
pub mod parquet_corporate_actions;
|
||||
|
|
@ -95,6 +97,16 @@ pub use fx::{
|
|||
build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource,
|
||||
FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD,
|
||||
};
|
||||
pub use mongo_safety::{
|
||||
assert_read_only_mongo_uri, is_qa_mongo_target, parse_mongo_target, LocalHosts,
|
||||
MongoSafetyError, MongoScheme, MongoTarget, MongoTargetHost, ReadOnlyPolicy,
|
||||
ValidatedReadOnlyMongoUri, DEFAULT_ALLOWED_READ_USER, FORBIDDEN_ADMIN_USER, QA_MONGO_PORT,
|
||||
};
|
||||
pub use mongo_stream::{
|
||||
build_filter_document, FilterDateValue, MongoDateRange, MongoReadSpec, MongoStreamError,
|
||||
RawBsonCursorReader, RawDocumentSource, SliceRawDocumentSource, SourceCollection,
|
||||
VecRawDocumentSource, DEFAULT_MONGO_BATCH_SIZE, MAX_MONGO_BATCH_SIZE,
|
||||
};
|
||||
pub use parquet_adj::{
|
||||
adj_factors_parquet_schema, write_adj_factors_dataset, AdjFactorsParquetRow,
|
||||
AdjFactorsWriteOptions, AdjFactorsWriteStats, ParquetAdjError,
|
||||
|
|
|
|||
|
|
@ -11,7 +11,8 @@ use curate_etl::bench::{
|
|||
run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark,
|
||||
run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark,
|
||||
run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark,
|
||||
run_fx_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark,
|
||||
run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark,
|
||||
run_parquet_bars_benchmark,
|
||||
run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark,
|
||||
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
|
||||
run_shorts_benchmark, run_split_benchmark,
|
||||
|
|
@ -656,6 +657,42 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchMongoStream(rows)) => {
|
||||
let report = match run_mongo_stream_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: mongo-stream benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
println!("curate-etl bench-mongo-stream");
|
||||
println!(" input: rows={} bytes={}", report.rows, report.bytes);
|
||||
println!(
|
||||
" decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={}) checksum=0x{:016x}",
|
||||
report.stats.decoded,
|
||||
report.stats.rejected_total(),
|
||||
report.stats.rejected_missing_field,
|
||||
report.stats.rejected_empty_field,
|
||||
report.stats.rejected_wrong_type,
|
||||
report.stats.rejected_malformed_date,
|
||||
report.stats.rejected_invalid_number,
|
||||
report.stats.rejected_corrupt_document,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" plain: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MiB/s",
|
||||
report.plain_elapsed_ms, report.plain_docs_per_sec, report.plain_mib_per_sec
|
||||
);
|
||||
println!(
|
||||
" cursor: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MiB/s ratio={:.3}x peak_pending_capacity={} bytes",
|
||||
report.cursor_elapsed_ms,
|
||||
report.cursor_docs_per_sec,
|
||||
report.cursor_mib_per_sec,
|
||||
report.cursor_to_plain_ratio,
|
||||
report.peak_pending_capacity
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateBars(rows)) => {
|
||||
let report = match run_curate_bars_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
|
|||
1068
tools/curate-etl/src/mongo_safety.rs
Normal file
1068
tools/curate-etl/src/mongo_safety.rs
Normal file
File diff suppressed because it is too large
Load diff
2580
tools/curate-etl/src/mongo_safety_tests.rs
Normal file
2580
tools/curate-etl/src/mongo_safety_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
807
tools/curate-etl/src/mongo_stream.rs
Normal file
807
tools/curate-etl/src/mongo_stream.rs
Normal file
|
|
@ -0,0 +1,807 @@
|
|||
//! Driver-independent read-only MongoDB raw-BSON cursor seam (`M1.2al`).
|
||||
//!
|
||||
//! Provides the closed [`SourceCollection`] allowlist, typed [`MongoReadSpec`]
|
||||
//! filter validation/builder, driver-independent [`RawDocumentSource`] trait,
|
||||
//! bounded-memory [`RawBsonCursorReader`] implementing [`std::io::Read`] for
|
||||
//! the existing zero-copy [`crate::bson_stream`] decoders, and password-redacted
|
||||
//! [`MongoStreamError`] sanitization reusing [`crate::mongo_safety`].
|
||||
//!
|
||||
//! # Safety & Sealing Guarantees
|
||||
//! - Closed [`SourceCollection`] allowlist matching the 8 M1 collections in
|
||||
//! `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`. No API
|
||||
//! accepts a free-form collection name string.
|
||||
//! - Zero MongoDB driver surface in this module yet (no `mongodb::` imports,
|
||||
//! client/database/collection handles, or write/admin/aggregation calls).
|
||||
//! - Password redaction: [`MongoStreamError`] never stores raw URIs or
|
||||
//! passwords; error text is sanitized at the boundary via
|
||||
//! [`crate::mongo_safety::redact_mongo_uri_password`].
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
|
||||
use bson::{Bson, DateTime, Document};
|
||||
|
||||
use crate::bson_stream::{DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES};
|
||||
use crate::events::parse_filing_timefiled;
|
||||
use crate::mongo_safety::{redact_mongo_uri_password, ValidatedReadOnlyMongoUri};
|
||||
|
||||
/// Default MongoDB cursor batch size (matches `DEFAULT_RAW_BSON_BATCH_SIZE`).
|
||||
pub const DEFAULT_MONGO_BATCH_SIZE: u32 = 4_096;
|
||||
|
||||
/// Maximum permitted MongoDB cursor batch size (matches `MAX_RAW_BSON_BATCH_SIZE`).
|
||||
pub const MAX_MONGO_BATCH_SIZE: u32 = 100_000;
|
||||
|
||||
/// Closed allowlist of the 8 M1 MongoDB source collections consumed by `curate-etl`.
|
||||
///
|
||||
/// Order and names match `RAW_BSON_EXPORT_COLLECTIONS` in
|
||||
/// `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum SourceCollection {
|
||||
EodPrices,
|
||||
QmSplits,
|
||||
QmDividends,
|
||||
QmPrices,
|
||||
TeMarketData,
|
||||
CeoShorts,
|
||||
QmFilings,
|
||||
QmEarnings,
|
||||
}
|
||||
|
||||
impl SourceCollection {
|
||||
/// All 8 allowlisted M1 source collections in canonical order.
|
||||
pub const ALL: [SourceCollection; 8] = [
|
||||
Self::EodPrices,
|
||||
Self::QmSplits,
|
||||
Self::QmDividends,
|
||||
Self::QmPrices,
|
||||
Self::TeMarketData,
|
||||
Self::CeoShorts,
|
||||
Self::QmFilings,
|
||||
Self::QmEarnings,
|
||||
];
|
||||
|
||||
/// Exact MongoDB collection name.
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::EodPrices => "eodPrices",
|
||||
Self::QmSplits => "qmSplits",
|
||||
Self::QmDividends => "qmDividends",
|
||||
Self::QmPrices => "qmPrices",
|
||||
Self::TeMarketData => "teMarketData",
|
||||
Self::CeoShorts => "ceoShorts",
|
||||
Self::QmFilings => "qmFilings",
|
||||
Self::QmEarnings => "qmEarnings",
|
||||
}
|
||||
}
|
||||
|
||||
/// Primary provider key field used for exact equality filters (`key_eq`).
|
||||
pub const fn key_field(self) -> &'static str {
|
||||
match self {
|
||||
Self::EodPrices => "eodSearchCode",
|
||||
Self::QmSplits => "qmSearchCode",
|
||||
Self::QmDividends => "qmSearchCode",
|
||||
Self::QmPrices => "qmSearchCode",
|
||||
Self::TeMarketData => "teSymbol",
|
||||
Self::CeoShorts => "symbol",
|
||||
Self::QmFilings => "symbol",
|
||||
Self::QmEarnings => "qmSearchCode",
|
||||
}
|
||||
}
|
||||
|
||||
/// Date/timestamp field used for range filters (`date_range`), or `None`
|
||||
/// for document-per-symbol collections (`teMarketData`).
|
||||
pub const fn date_field(self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::EodPrices => Some("date"),
|
||||
Self::QmSplits => Some("date"),
|
||||
Self::QmDividends => Some("date"),
|
||||
Self::QmPrices => Some("date"),
|
||||
Self::TeMarketData => None,
|
||||
Self::CeoShorts => Some("timestamp"),
|
||||
Self::QmFilings => Some("timefiled"),
|
||||
Self::QmEarnings => Some("reportDate"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for SourceCollection {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed date bound value for [`MongoDateRange`].
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum FilterDateValue {
|
||||
/// Lexicographically ordered ISO-8601 date/timestamp string (e.g. `"2024-01-01"`).
|
||||
IsoString(String),
|
||||
/// BSON UTC `DateTime` expressed as milliseconds since the Unix epoch.
|
||||
BsonDateTimeMillis(i64),
|
||||
}
|
||||
|
||||
impl FilterDateValue {
|
||||
fn to_bson(&self) -> Bson {
|
||||
match self {
|
||||
Self::IsoString(s) => Bson::String(s.clone()),
|
||||
Self::BsonDateTimeMillis(ms) => Bson::DateTime(DateTime::from_millis(*ms)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Half-open `[gte, lt)` date filter for a [`SourceCollection`] with a date field.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MongoDateRange {
|
||||
pub gte: Option<FilterDateValue>,
|
||||
pub lt: Option<FilterDateValue>,
|
||||
}
|
||||
|
||||
/// Typed read specification for a read-only MongoDB cursor query.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MongoReadSpec {
|
||||
/// Optional exact match on [`SourceCollection::key_field`].
|
||||
pub key_eq: Option<String>,
|
||||
/// Optional `[gte, lt)` range on [`SourceCollection::date_field`].
|
||||
pub date_range: Option<MongoDateRange>,
|
||||
/// MongoDB cursor `batchSize` (in `1..=MAX_MONGO_BATCH_SIZE`).
|
||||
pub batch_size: u32,
|
||||
/// Optional maximum number of documents to return (in `1..=i64::MAX`).
|
||||
pub limit: Option<u64>,
|
||||
/// Maximum allowed single raw BSON document length in bytes (`>= MIN_BSON_DOC_BYTES`).
|
||||
pub max_doc_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for MongoReadSpec {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
key_eq: None,
|
||||
date_range: None,
|
||||
batch_size: DEFAULT_MONGO_BATCH_SIZE,
|
||||
limit: None,
|
||||
max_doc_bytes: DEFAULT_MAX_DOC_BYTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MongoReadSpec {
|
||||
/// Validates all read specification invariants for `collection`.
|
||||
pub fn validate(&self, collection: SourceCollection) -> Result<(), MongoStreamError> {
|
||||
if self.batch_size == 0 || self.batch_size > MAX_MONGO_BATCH_SIZE {
|
||||
return Err(MongoStreamError::InvalidBatchSize {
|
||||
batch_size: self.batch_size,
|
||||
max_batch_size: MAX_MONGO_BATCH_SIZE,
|
||||
});
|
||||
}
|
||||
if let Some(limit) = self.limit {
|
||||
if limit == 0 || limit > i64::MAX as u64 {
|
||||
return Err(MongoStreamError::InvalidLimit { limit });
|
||||
}
|
||||
}
|
||||
if self.max_doc_bytes < MIN_BSON_DOC_BYTES {
|
||||
return Err(MongoStreamError::InvalidMaxDocBytes {
|
||||
max_doc_bytes: self.max_doc_bytes,
|
||||
min_doc_bytes: MIN_BSON_DOC_BYTES,
|
||||
});
|
||||
}
|
||||
if let Some(key) = &self.key_eq {
|
||||
if key.trim().is_empty() {
|
||||
return Err(MongoStreamError::InvalidKeyFilter { collection });
|
||||
}
|
||||
}
|
||||
if let Some(range) = &self.date_range {
|
||||
if collection.date_field().is_none() {
|
||||
return Err(MongoStreamError::DateRangeNotSupported { collection });
|
||||
}
|
||||
if range.gte.is_none() && range.lt.is_none() {
|
||||
return Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: "at least one of gte or lt must be set".to_owned(),
|
||||
});
|
||||
}
|
||||
if let Some(FilterDateValue::IsoString(s)) = &range.gte {
|
||||
if s.trim().is_empty() {
|
||||
return Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: "gte ISO string must not be empty or blank".to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(FilterDateValue::IsoString(s)) = &range.lt {
|
||||
if s.trim().is_empty() {
|
||||
return Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: "lt ISO string must not be empty or blank".to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if collection == SourceCollection::QmFilings {
|
||||
let validate_et_calendar_day =
|
||||
|bound: Option<&FilterDateValue>, label: &str| match bound {
|
||||
Some(FilterDateValue::IsoString(s)) => {
|
||||
let is_calendar_day = s.len() == 10
|
||||
&& s.is_ascii()
|
||||
&& parse_filing_timefiled(&format!("{s}T00:00:00 EST")).is_ok();
|
||||
if !is_calendar_day {
|
||||
return Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: format!(
|
||||
"qmFilings.timefiled {label} must be an Eastern \
|
||||
calendar-day boundary (YYYY-MM-DD); intra-day local \
|
||||
timestamps are not monotonic across the fall-back DST \
|
||||
transition and UTC strings do not match stored Eastern \
|
||||
Time strings"
|
||||
),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some(FilterDateValue::BsonDateTimeMillis(_)) => {
|
||||
Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: "qmFilings.timefiled is stored as an Eastern Time string; \
|
||||
only Eastern calendar-day boundaries (YYYY-MM-DD) are \
|
||||
supported for server-side ranges"
|
||||
.to_owned(),
|
||||
})
|
||||
}
|
||||
None => Ok(()),
|
||||
};
|
||||
validate_et_calendar_day(range.gte.as_ref(), "gte")?;
|
||||
validate_et_calendar_day(range.lt.as_ref(), "lt")?;
|
||||
}
|
||||
if let (Some(gte), Some(lt)) = (&range.gte, &range.lt) {
|
||||
match (gte, lt) {
|
||||
(FilterDateValue::IsoString(a), FilterDateValue::IsoString(b)) => {
|
||||
if a >= b {
|
||||
return Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: format!("gte ({a:?}) must be strictly less than lt ({b:?})"),
|
||||
});
|
||||
}
|
||||
}
|
||||
(
|
||||
FilterDateValue::BsonDateTimeMillis(a),
|
||||
FilterDateValue::BsonDateTimeMillis(b),
|
||||
) => {
|
||||
if a >= b {
|
||||
return Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: format!("gte ({a}) must be strictly less than lt ({b})"),
|
||||
});
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(MongoStreamError::InvalidDateRange {
|
||||
collection,
|
||||
detail: "gte and lt must use the same FilterDateValue variant"
|
||||
.to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates `spec` and constructs the corresponding MongoDB `find` filter [`Document`].
|
||||
pub fn build_filter_document(
|
||||
collection: SourceCollection,
|
||||
spec: &MongoReadSpec,
|
||||
) -> Result<Document, MongoStreamError> {
|
||||
spec.validate(collection)?;
|
||||
|
||||
let mut entries: Vec<(String, Bson)> = Vec::with_capacity(2);
|
||||
if let Some(key) = &spec.key_eq {
|
||||
entries.push((collection.key_field().to_owned(), Bson::String(key.clone())));
|
||||
}
|
||||
if let Some(range) = &spec.date_range {
|
||||
if let Some(date_field) = collection.date_field() {
|
||||
let mut range_entries: Vec<(String, Bson)> = Vec::with_capacity(2);
|
||||
if let Some(gte) = &range.gte {
|
||||
range_entries.push(("$gte".to_owned(), gte.to_bson()));
|
||||
}
|
||||
if let Some(lt) = &range.lt {
|
||||
range_entries.push(("$lt".to_owned(), lt.to_bson()));
|
||||
}
|
||||
entries.push((
|
||||
date_field.to_owned(),
|
||||
Bson::Document(Document::from_iter(range_entries)),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Document::from_iter(entries))
|
||||
}
|
||||
|
||||
/// Redacted error type for MongoDB raw-BSON cursor streaming.
|
||||
///
|
||||
/// Intentionally never stores raw URIs or passwords.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MongoStreamError {
|
||||
InvalidBatchSize {
|
||||
batch_size: u32,
|
||||
max_batch_size: u32,
|
||||
},
|
||||
InvalidLimit {
|
||||
limit: u64,
|
||||
},
|
||||
InvalidMaxDocBytes {
|
||||
max_doc_bytes: usize,
|
||||
min_doc_bytes: usize,
|
||||
},
|
||||
InvalidKeyFilter {
|
||||
collection: SourceCollection,
|
||||
},
|
||||
DateRangeNotSupported {
|
||||
collection: SourceCollection,
|
||||
},
|
||||
InvalidDateRange {
|
||||
collection: SourceCollection,
|
||||
detail: String,
|
||||
},
|
||||
InvalidBsonFrame {
|
||||
doc_index: u64,
|
||||
detail: String,
|
||||
},
|
||||
Source {
|
||||
detail: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl MongoStreamError {
|
||||
/// Constructs a [`MongoStreamError::Source`] after stripping any raw URI,
|
||||
/// raw password, percent-decoded password, or embedded MongoDB userinfo
|
||||
/// password from `raw_message`.
|
||||
pub fn redacted_source(raw_message: &str, uri: &ValidatedReadOnlyMongoUri) -> Self {
|
||||
Self::Source {
|
||||
detail: sanitize_driver_error_message(raw_message, uri),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for MongoStreamError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidBatchSize {
|
||||
batch_size,
|
||||
max_batch_size,
|
||||
} => write!(
|
||||
f,
|
||||
"invalid MongoDB batch_size {batch_size}: must be in 1..={max_batch_size}"
|
||||
),
|
||||
Self::InvalidLimit { limit } => write!(
|
||||
f,
|
||||
"invalid MongoDB limit {limit}: must be in 1..={}",
|
||||
i64::MAX
|
||||
),
|
||||
Self::InvalidMaxDocBytes {
|
||||
max_doc_bytes,
|
||||
min_doc_bytes,
|
||||
} => write!(
|
||||
f,
|
||||
"invalid max_doc_bytes {max_doc_bytes}: must be >= {min_doc_bytes}"
|
||||
),
|
||||
Self::InvalidKeyFilter { collection } => write!(
|
||||
f,
|
||||
"invalid key_eq filter for collection {collection}: must not be empty or blank"
|
||||
),
|
||||
Self::DateRangeNotSupported { collection } => write!(
|
||||
f,
|
||||
"date_range filter is not supported for collection {collection}"
|
||||
),
|
||||
Self::InvalidDateRange { collection, detail } => {
|
||||
write!(f, "invalid date_range for collection {collection}: {detail}")
|
||||
}
|
||||
Self::InvalidBsonFrame { doc_index, detail } => {
|
||||
write!(f, "invalid raw BSON frame at doc #{doc_index}: {detail}")
|
||||
}
|
||||
Self::Source { detail } => write!(f, "raw BSON source error: {detail}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for MongoStreamError {}
|
||||
|
||||
/// Driver-independent seam yielding one raw length-prefixed BSON document at a time.
|
||||
pub trait RawDocumentSource {
|
||||
/// Advances to the next raw BSON document and returns its byte slice,
|
||||
/// or `Ok(None)` when the source is exhausted.
|
||||
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError>;
|
||||
}
|
||||
|
||||
/// Zero-copy in-memory [`RawDocumentSource`] over a slice of borrowed raw BSON frames.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SliceRawDocumentSource<'a> {
|
||||
docs: &'a [&'a [u8]],
|
||||
index: usize,
|
||||
}
|
||||
|
||||
impl<'a> SliceRawDocumentSource<'a> {
|
||||
pub fn new(docs: &'a [&'a [u8]]) -> Self {
|
||||
Self { docs, index: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> RawDocumentSource for SliceRawDocumentSource<'a> {
|
||||
#[inline]
|
||||
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError> {
|
||||
let Some(&doc) = self.docs.get(self.index) else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.index += 1;
|
||||
Ok(Some(doc))
|
||||
}
|
||||
}
|
||||
|
||||
/// Owned in-memory [`RawDocumentSource`] over a `Vec<Vec<u8>>` of raw BSON frames.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct VecRawDocumentSource {
|
||||
docs: Vec<Vec<u8>>,
|
||||
index: usize,
|
||||
}
|
||||
|
||||
impl VecRawDocumentSource {
|
||||
pub fn new(docs: Vec<Vec<u8>>) -> Self {
|
||||
Self { docs, index: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl RawDocumentSource for VecRawDocumentSource {
|
||||
#[inline]
|
||||
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError> {
|
||||
if self.index >= self.docs.len() {
|
||||
return Ok(None);
|
||||
}
|
||||
let doc = self.docs[self.index].as_slice();
|
||||
self.index += 1;
|
||||
Ok(Some(doc))
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_raw_bson_frame(
|
||||
doc: &[u8],
|
||||
doc_index: u64,
|
||||
max_doc_bytes: usize,
|
||||
) -> Result<(), MongoStreamError> {
|
||||
if doc.len() < MIN_BSON_DOC_BYTES {
|
||||
return Err(MongoStreamError::InvalidBsonFrame {
|
||||
doc_index,
|
||||
detail: format!(
|
||||
"frame length {} is below minimum BSON document size ({MIN_BSON_DOC_BYTES})",
|
||||
doc.len()
|
||||
),
|
||||
});
|
||||
}
|
||||
if doc.len() > max_doc_bytes {
|
||||
return Err(MongoStreamError::InvalidBsonFrame {
|
||||
doc_index,
|
||||
detail: format!(
|
||||
"frame length {} exceeds max_doc_bytes ({max_doc_bytes})",
|
||||
doc.len()
|
||||
),
|
||||
});
|
||||
}
|
||||
let declared_len = i32::from_le_bytes([doc[0], doc[1], doc[2], doc[3]]);
|
||||
if declared_len < MIN_BSON_DOC_BYTES as i32 || (declared_len as usize) != doc.len() {
|
||||
return Err(MongoStreamError::InvalidBsonFrame {
|
||||
doc_index,
|
||||
detail: format!(
|
||||
"4-byte LE length prefix ({declared_len}) disagrees with byte length ({})",
|
||||
doc.len()
|
||||
),
|
||||
});
|
||||
}
|
||||
let last_byte = doc[doc.len() - 1];
|
||||
if last_byte != 0x00 {
|
||||
return Err(MongoStreamError::InvalidBsonFrame {
|
||||
doc_index,
|
||||
detail: format!("missing trailing 0x00 terminator (got 0x{last_byte:02x})"),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bounded-memory [`io::Read`] adapter that turns any [`RawDocumentSource`]
|
||||
/// into a concatenated raw BSON byte stream for [`crate::bson_stream::RawBsonChunkReader`]
|
||||
/// and `decode_*_stream`.
|
||||
///
|
||||
/// Copies documents directly into the caller's buffer whenever they fit,
|
||||
/// spilling only the unread tail of a single current document into a reused
|
||||
/// `pending` buffer when the caller's buffer is smaller.
|
||||
pub struct RawBsonCursorReader<S: RawDocumentSource> {
|
||||
source: S,
|
||||
max_doc_bytes: usize,
|
||||
pending: Vec<u8>,
|
||||
pending_pos: usize,
|
||||
docs_read: u64,
|
||||
bytes_read: u64,
|
||||
eof: bool,
|
||||
stashed_error: Option<MongoStreamError>,
|
||||
sticky_error: Option<MongoStreamError>,
|
||||
}
|
||||
|
||||
impl<S: RawDocumentSource> RawBsonCursorReader<S> {
|
||||
/// Wraps `source` with the default maximum BSON document size ([`DEFAULT_MAX_DOC_BYTES`]).
|
||||
pub fn new(source: S) -> Self {
|
||||
Self {
|
||||
source,
|
||||
max_doc_bytes: DEFAULT_MAX_DOC_BYTES,
|
||||
pending: Vec::new(),
|
||||
pending_pos: 0,
|
||||
docs_read: 0,
|
||||
bytes_read: 0,
|
||||
eof: false,
|
||||
stashed_error: None,
|
||||
sticky_error: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps `source` with an explicit `max_doc_bytes` ceiling (`>= MIN_BSON_DOC_BYTES`).
|
||||
pub fn with_max_doc_bytes(source: S, max_doc_bytes: usize) -> Result<Self, MongoStreamError> {
|
||||
if max_doc_bytes < MIN_BSON_DOC_BYTES {
|
||||
return Err(MongoStreamError::InvalidMaxDocBytes {
|
||||
max_doc_bytes,
|
||||
min_doc_bytes: MIN_BSON_DOC_BYTES,
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
source,
|
||||
max_doc_bytes,
|
||||
pending: Vec::new(),
|
||||
pending_pos: 0,
|
||||
docs_read: 0,
|
||||
bytes_read: 0,
|
||||
eof: false,
|
||||
stashed_error: None,
|
||||
sticky_error: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Number of valid raw BSON documents accepted from the underlying source.
|
||||
#[inline]
|
||||
pub fn docs_read(&self) -> u64 {
|
||||
self.docs_read
|
||||
}
|
||||
|
||||
/// Total bytes across all valid raw BSON documents accepted from the underlying source.
|
||||
#[inline]
|
||||
pub fn bytes_read(&self) -> u64 {
|
||||
self.bytes_read
|
||||
}
|
||||
|
||||
/// Current allocated capacity of the single-document tail spill buffer.
|
||||
#[inline]
|
||||
pub fn pending_capacity(&self) -> usize {
|
||||
self.pending.capacity()
|
||||
}
|
||||
|
||||
/// Consumes the adapter and returns the underlying source.
|
||||
pub fn into_inner(self) -> S {
|
||||
self.source
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: RawDocumentSource> io::Read for RawBsonCursorReader<S> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if buf.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
if let Some(err) = &self.sticky_error {
|
||||
return Err(io::Error::other(err.clone()));
|
||||
}
|
||||
if let Some(err) = self.stashed_error.take() {
|
||||
self.sticky_error = Some(err.clone());
|
||||
return Err(io::Error::other(err));
|
||||
}
|
||||
|
||||
let mut written = 0usize;
|
||||
while written < buf.len() {
|
||||
if self.pending_pos < self.pending.len() {
|
||||
let avail = self.pending.len() - self.pending_pos;
|
||||
let take = avail.min(buf.len() - written);
|
||||
buf[written..written + take]
|
||||
.copy_from_slice(&self.pending[self.pending_pos..self.pending_pos + take]);
|
||||
self.pending_pos += take;
|
||||
written += take;
|
||||
if self.pending_pos == self.pending.len() {
|
||||
self.pending.clear();
|
||||
self.pending_pos = 0;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if self.eof {
|
||||
break;
|
||||
}
|
||||
|
||||
match self.source.next_raw_document() {
|
||||
Ok(None) => {
|
||||
self.eof = true;
|
||||
break;
|
||||
}
|
||||
Ok(Some(doc)) => {
|
||||
if let Err(err) =
|
||||
validate_raw_bson_frame(doc, self.docs_read, self.max_doc_bytes)
|
||||
{
|
||||
if written > 0 {
|
||||
self.stashed_error = Some(err);
|
||||
return Ok(written);
|
||||
}
|
||||
self.sticky_error = Some(err.clone());
|
||||
return Err(io::Error::other(err));
|
||||
}
|
||||
|
||||
self.docs_read += 1;
|
||||
self.bytes_read += doc.len() as u64;
|
||||
|
||||
let remaining = buf.len() - written;
|
||||
if doc.len() <= remaining {
|
||||
buf[written..written + doc.len()].copy_from_slice(doc);
|
||||
written += doc.len();
|
||||
} else {
|
||||
buf[written..written + remaining].copy_from_slice(&doc[..remaining]);
|
||||
written += remaining;
|
||||
let tail = &doc[remaining..];
|
||||
self.pending.clear();
|
||||
if self.pending.capacity() < tail.len() {
|
||||
self.pending.reserve_exact(tail.len());
|
||||
}
|
||||
self.pending.extend_from_slice(tail);
|
||||
self.pending_pos = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
if written > 0 {
|
||||
self.stashed_error = Some(err);
|
||||
return Ok(written);
|
||||
}
|
||||
self.sticky_error = Some(err.clone());
|
||||
return Err(io::Error::other(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(written)
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_raw_uri_password(uri: &str) -> Option<&str> {
|
||||
let scheme_end = uri.find("://")?;
|
||||
let rest = &uri[scheme_end + 3..];
|
||||
let authority_end = rest.find(['/', '?']).unwrap_or(rest.len());
|
||||
let authority = &rest[..authority_end];
|
||||
let at_idx = authority.find('@')?;
|
||||
let userinfo = &authority[..at_idx];
|
||||
let colon_idx = userinfo.find(':')?;
|
||||
let pass = &userinfo[colon_idx + 1..];
|
||||
if pass.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(pass)
|
||||
}
|
||||
}
|
||||
|
||||
fn percent_decode_best_effort(input: &str) -> Option<String> {
|
||||
let bytes = input.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%' && i + 2 < bytes.len() {
|
||||
let hi = hex_nibble(bytes[i + 1])?;
|
||||
let lo = hex_nibble(bytes[i + 2])?;
|
||||
out.push((hi << 4) | lo);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).ok()
|
||||
}
|
||||
|
||||
fn hex_nibble(b: u8) -> Option<u8> {
|
||||
match b {
|
||||
b'0'..=b'9' => Some(b - b'0'),
|
||||
b'a'..=b'f' => Some(b - b'a' + 10),
|
||||
b'A'..=b'F' => Some(b - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn find_next_mongo_scheme(lower_slice: &str) -> Option<(usize, usize)> {
|
||||
let next_std = lower_slice
|
||||
.find("mongodb://")
|
||||
.map(|i| (i, "mongodb://".len()));
|
||||
let next_srv = lower_slice
|
||||
.find("mongodb+srv://")
|
||||
.map(|i| (i, "mongodb+srv://".len()));
|
||||
match (next_std, next_srv) {
|
||||
(Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }),
|
||||
(Some(a), None) => Some(a),
|
||||
(None, Some(b)) => Some(b),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn redact_embedded_mongo_uris(text: &str) -> String {
|
||||
let mut result = String::with_capacity(text.len());
|
||||
let mut cursor = 0usize;
|
||||
let lower = text.to_ascii_lowercase();
|
||||
|
||||
while cursor < text.len() {
|
||||
let Some((rel_start, scheme_len)) = find_next_mongo_scheme(&lower[cursor..]) else {
|
||||
result.push_str(&text[cursor..]);
|
||||
break;
|
||||
};
|
||||
|
||||
let start = cursor + rel_start;
|
||||
result.push_str(&text[cursor..start]);
|
||||
|
||||
let tail = &text[start..];
|
||||
let after_scheme = &tail[scheme_len..];
|
||||
let after_scheme_lower = &lower[start + scheme_len..];
|
||||
// Authority ends at `/`, `?`, whitespace, or the start of a subsequent
|
||||
// MongoDB URI scheme (e.g., compact JSON `["mongodb://host","mongodb://u:p@host"]`).
|
||||
// Do not stop on punctuation such as `,`, `;`, `)`, `]`, `}`, `"`, `'` before
|
||||
// locating `@`, because embedded passwords (or replica-set host lists) may contain them.
|
||||
let delim_end = after_scheme
|
||||
.find(|c: char| c.is_whitespace() || matches!(c, '/' | '?'))
|
||||
.unwrap_or(after_scheme.len());
|
||||
let next_scheme_end = find_next_mongo_scheme(after_scheme_lower)
|
||||
.map(|(idx, _)| idx)
|
||||
.unwrap_or(after_scheme.len());
|
||||
let authority_end = delim_end.min(next_scheme_end);
|
||||
let authority_region = &after_scheme[..authority_end];
|
||||
|
||||
if let Some(at_idx) = authority_region.rfind('@') {
|
||||
let userinfo = &authority_region[..at_idx];
|
||||
if let Some(colon_idx) = userinfo.find(':') {
|
||||
let prefix_with_at = &tail[..scheme_len + at_idx + 1];
|
||||
if !userinfo.contains('@') {
|
||||
result.push_str(&redact_mongo_uri_password(prefix_with_at));
|
||||
} else {
|
||||
result.push_str(&tail[..scheme_len + colon_idx + 1]);
|
||||
result.push_str("[REDACTED]@");
|
||||
}
|
||||
cursor = start + scheme_len + at_idx + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let advance = scheme_len + authority_end;
|
||||
result.push_str(&tail[..advance]);
|
||||
cursor = start + advance;
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Strips raw URI, raw password, percent-decoded password, and any embedded
|
||||
/// `mongodb://` / `mongodb+srv://` userinfo passwords from driver error text.
|
||||
pub(crate) fn sanitize_driver_error_message(
|
||||
raw_message: &str,
|
||||
uri: &ValidatedReadOnlyMongoUri,
|
||||
) -> String {
|
||||
let redacted_uri = uri.redacted();
|
||||
let mut sanitized = raw_message.split(uri.as_str()).collect::<Vec<_>>().join(&redacted_uri);
|
||||
|
||||
if let Some(raw_pass) = extract_raw_uri_password(uri.as_str()) {
|
||||
sanitized = sanitized.split(raw_pass).collect::<Vec<_>>().join("[REDACTED]");
|
||||
if let Some(decoded_pass) = percent_decode_best_effort(raw_pass) {
|
||||
if !decoded_pass.is_empty() && decoded_pass != raw_pass {
|
||||
sanitized = sanitized
|
||||
.split(&decoded_pass)
|
||||
.collect::<Vec<_>>()
|
||||
.join("[REDACTED]");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
redact_embedded_mongo_uris(&sanitized)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mongo_stream_tests.rs"]
|
||||
mod tests;
|
||||
1906
tools/curate-etl/src/mongo_stream_tests.rs
Normal file
1906
tools/curate-etl/src/mongo_stream_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
322
tools/curate-etl/tests/mongo_stream_qa_contract.rs
Normal file
322
tools/curate-etl/tests/mongo_stream_qa_contract.rs
Normal file
|
|
@ -0,0 +1,322 @@
|
|||
//! QA contract tests for the public `mongo_stream` API (T-126 / M1.2al).
|
||||
//!
|
||||
//! Covers gaps left by `src/mongo_stream_tests.rs`, using only the public crate API and
|
||||
//! in-memory sources (no MongoDB, no network):
|
||||
//! - a source that fails exactly once is never polled again; the reader replays the same
|
||||
//! sticky error (stashed-after-partial-write path and split-document path);
|
||||
//! - an invalid frame after a valid one in the same `read()` is deferred, then sticky, and
|
||||
//! never counted;
|
||||
//! - seeded random documents + random read sizes: concatenated output is byte-identical to
|
||||
//! the inputs, counters match, and `pending` never exceeds the largest single document;
|
||||
//! - `RawBsonChunkReader` frames the adapter's output with the same chunks as a plain cursor;
|
||||
//! - `with_max_doc_bytes` rejects ceilings below the BSON minimum; `into_inner` returns the
|
||||
//! source at its current position;
|
||||
//! - `build_filter_document` emits the exact key / `$gte` / `$lt` shape, and an empty spec
|
||||
//! yields an empty filter;
|
||||
//! - `MongoStreamError::redacted_source` (public path) hides the validated URI's password in
|
||||
//! `Display` and `Debug` even when the raw URI is absent from the message.
|
||||
|
||||
use std::io::{self, Cursor, Read};
|
||||
|
||||
use bson::raw::{cstr, RawDocumentBuf};
|
||||
use bson::{doc, Bson, DateTime};
|
||||
use curate_etl::{
|
||||
assert_read_only_mongo_uri, build_filter_document, FilterDateValue, LocalHosts, MongoDateRange,
|
||||
MongoReadSpec, MongoStreamError, RawBsonChunkReader, RawBsonCursorReader, RawDocumentSource,
|
||||
ReadOnlyPolicy, SliceRawDocumentSource, SourceCollection, VecRawDocumentSource,
|
||||
MIN_BSON_DOC_BYTES,
|
||||
};
|
||||
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next_u64(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next_u64() % n
|
||||
}
|
||||
}
|
||||
|
||||
fn doc_with_payload(tag: u64, payload_len: usize) -> Vec<u8> {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("tag"), tag as i64);
|
||||
doc.append(cstr!("payload"), "x".repeat(payload_len));
|
||||
doc.into_bytes()
|
||||
}
|
||||
|
||||
/// Yields `docs`, fails exactly once at `fail_at`, and counts every poll.
|
||||
struct FailOnceSource {
|
||||
docs: Vec<Vec<u8>>,
|
||||
index: usize,
|
||||
fail_at: usize,
|
||||
failed: bool,
|
||||
polls: usize,
|
||||
}
|
||||
|
||||
impl FailOnceSource {
|
||||
fn new(docs: Vec<Vec<u8>>, fail_at: usize) -> Self {
|
||||
Self {
|
||||
docs,
|
||||
index: 0,
|
||||
fail_at,
|
||||
failed: false,
|
||||
polls: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RawDocumentSource for FailOnceSource {
|
||||
fn next_raw_document(&mut self) -> Result<Option<&[u8]>, MongoStreamError> {
|
||||
self.polls += 1;
|
||||
if self.index == self.fail_at && !self.failed {
|
||||
self.failed = true;
|
||||
return Err(MongoStreamError::Source {
|
||||
detail: "simulated cursor failure".to_owned(),
|
||||
});
|
||||
}
|
||||
if self.index >= self.docs.len() {
|
||||
return Ok(None);
|
||||
}
|
||||
let doc = self.docs[self.index].as_slice();
|
||||
self.index += 1;
|
||||
Ok(Some(doc))
|
||||
}
|
||||
}
|
||||
|
||||
fn downcast_stream_err(err: &io::Error) -> MongoStreamError {
|
||||
err.get_ref()
|
||||
.and_then(|e| e.downcast_ref::<MongoStreamError>())
|
||||
.cloned()
|
||||
.expect("io::Error must carry MongoStreamError")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fail_once_source_after_split_document_is_not_repolled_and_error_is_sticky() {
|
||||
let doc0 = doc_with_payload(0, 40);
|
||||
let docs = vec![doc0.clone(), doc_with_payload(1, 40)];
|
||||
let mut reader = RawBsonCursorReader::new(FailOnceSource::new(docs, 1));
|
||||
|
||||
let mut out = Vec::new();
|
||||
let mut buf = [0u8; 7];
|
||||
let err = loop {
|
||||
match reader.read(&mut buf) {
|
||||
Ok(0) => panic!("reader must not report EOF after a source failure"),
|
||||
Ok(n) => out.extend_from_slice(&buf[..n]),
|
||||
Err(err) => break err,
|
||||
}
|
||||
};
|
||||
assert_eq!(
|
||||
out, doc0,
|
||||
"split document must be fully delivered before the error"
|
||||
);
|
||||
let first = downcast_stream_err(&err);
|
||||
assert!(matches!(first, MongoStreamError::Source { .. }));
|
||||
|
||||
for _ in 0..3 {
|
||||
let again = reader.read(&mut buf).expect_err("error must stay sticky");
|
||||
assert_eq!(downcast_stream_err(&again), first);
|
||||
}
|
||||
assert_eq!(reader.docs_read(), 1);
|
||||
assert_eq!(reader.bytes_read(), doc0.len() as u64);
|
||||
assert_eq!(
|
||||
reader.into_inner().polls,
|
||||
2,
|
||||
"sticky error must be replayed without polling the source again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fail_once_source_after_whole_document_returns_partial_then_sticky_without_repoll() {
|
||||
let doc0 = doc_with_payload(0, 10);
|
||||
let mut reader = RawBsonCursorReader::new(FailOnceSource::new(vec![doc0.clone()], 1));
|
||||
|
||||
let mut buf = [0u8; 4096];
|
||||
let n = reader
|
||||
.read(&mut buf)
|
||||
.expect("first read returns the bytes already written");
|
||||
assert_eq!(&buf[..n], doc0.as_slice());
|
||||
|
||||
let err = reader
|
||||
.read(&mut buf)
|
||||
.expect_err("stashed error surfaces on the next read");
|
||||
let first = downcast_stream_err(&err);
|
||||
let err2 = reader.read(&mut buf).expect_err("error stays sticky");
|
||||
assert_eq!(downcast_stream_err(&err2), first);
|
||||
assert_eq!(reader.docs_read(), 1);
|
||||
assert_eq!(reader.into_inner().polls, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_frame_after_valid_frame_is_deferred_sticky_and_uncounted() {
|
||||
let good = doc_with_payload(7, 3);
|
||||
let mut bad = doc_with_payload(8, 3);
|
||||
let last = bad.len() - 1;
|
||||
bad[last] = 0x01;
|
||||
let docs: Vec<&[u8]> = vec![&good, &bad, &good];
|
||||
let mut reader = RawBsonCursorReader::new(SliceRawDocumentSource::new(&docs));
|
||||
|
||||
let mut buf = [0u8; 4096];
|
||||
let n = reader.read(&mut buf).expect("valid prefix delivered first");
|
||||
assert_eq!(&buf[..n], good.as_slice());
|
||||
|
||||
let err = reader.read(&mut buf).expect_err("bad frame surfaces next");
|
||||
match downcast_stream_err(&err) {
|
||||
MongoStreamError::InvalidBsonFrame { doc_index, .. } => assert_eq!(doc_index, 1),
|
||||
other => panic!("unexpected error: {other:?}"),
|
||||
}
|
||||
assert!(reader.read(&mut buf).is_err(), "error must stay sticky");
|
||||
assert_eq!(reader.docs_read(), 1);
|
||||
assert_eq!(reader.bytes_read(), good.len() as u64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_random_documents_and_read_sizes_round_trip_byte_identically() {
|
||||
let mut rng = SplitMix64(0x5EED_126A);
|
||||
for _round in 0..40 {
|
||||
let doc_count = rng.below(12) as usize;
|
||||
let docs: Vec<Vec<u8>> = (0..doc_count)
|
||||
.map(|i| doc_with_payload(i as u64, rng.below(600) as usize))
|
||||
.collect();
|
||||
let expected: Vec<u8> = docs.concat();
|
||||
let largest = docs.iter().map(Vec::len).max().unwrap_or(0);
|
||||
|
||||
let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
let step = 1 + rng.below(700) as usize;
|
||||
let mut buf = vec![0u8; step];
|
||||
let n = reader.read(&mut buf).expect("valid stream must read");
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
out.extend_from_slice(&buf[..n]);
|
||||
assert!(
|
||||
reader.pending_capacity() <= largest,
|
||||
"pending {} exceeds largest doc {largest}",
|
||||
reader.pending_capacity()
|
||||
);
|
||||
}
|
||||
assert_eq!(out, expected);
|
||||
assert_eq!(reader.docs_read(), doc_count as u64);
|
||||
assert_eq!(reader.bytes_read(), expected.len() as u64);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_reader_frames_cursor_output_identically_to_plain_cursor() {
|
||||
let docs: Vec<Vec<u8>> = (0..50)
|
||||
.map(|i| doc_with_payload(i, (i as usize * 37) % 900))
|
||||
.collect();
|
||||
let concat = docs.concat();
|
||||
|
||||
let collect = |mut chunker: RawBsonChunkReader<Box<dyn Read>>| {
|
||||
let mut chunks = Vec::new();
|
||||
while let Some(chunk) = chunker.next_chunk().expect("framing must succeed") {
|
||||
chunks.push((chunk.start_offset, chunk.bytes.to_vec()));
|
||||
}
|
||||
chunks
|
||||
};
|
||||
let plain = collect(RawBsonChunkReader::new(Box::new(Cursor::new(
|
||||
concat.clone(),
|
||||
))));
|
||||
let via_cursor = collect(RawBsonChunkReader::new(Box::new(RawBsonCursorReader::new(
|
||||
VecRawDocumentSource::new(docs),
|
||||
))));
|
||||
|
||||
let flatten =
|
||||
|chunks: &[(u64, Vec<u8>)]| chunks.iter().flat_map(|c| c.1.clone()).collect::<Vec<u8>>();
|
||||
assert_eq!(flatten(&plain), concat);
|
||||
assert_eq!(flatten(&via_cursor), concat);
|
||||
assert_eq!(via_cursor.first().map(|c| c.0), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_max_doc_bytes_rejects_ceiling_below_bson_minimum() {
|
||||
let empty: [&[u8]; 0] = [];
|
||||
let err = RawBsonCursorReader::with_max_doc_bytes(
|
||||
SliceRawDocumentSource::new(&empty),
|
||||
MIN_BSON_DOC_BYTES - 1,
|
||||
)
|
||||
.err()
|
||||
.expect("ceiling below minimum must be rejected");
|
||||
assert!(matches!(err, MongoStreamError::InvalidMaxDocBytes { .. }));
|
||||
assert!(RawBsonCursorReader::with_max_doc_bytes(
|
||||
SliceRawDocumentSource::new(&empty),
|
||||
MIN_BSON_DOC_BYTES
|
||||
)
|
||||
.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_inner_returns_source_at_current_position() {
|
||||
let docs = vec![doc_with_payload(0, 1), doc_with_payload(1, 1)];
|
||||
let mut reader = RawBsonCursorReader::new(VecRawDocumentSource::new(docs.clone()));
|
||||
let mut buf = vec![0u8; docs[0].len()];
|
||||
reader.read_exact(&mut buf).expect("first doc");
|
||||
let mut source = reader.into_inner();
|
||||
let next = source
|
||||
.next_raw_document()
|
||||
.expect("source ok")
|
||||
.map(<[u8]>::to_vec);
|
||||
assert_eq!(next, Some(docs[1].clone()));
|
||||
assert!(source.next_raw_document().expect("source ok").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_filter_document_emits_exact_key_and_range_shape() {
|
||||
let spec = MongoReadSpec {
|
||||
key_eq: Some("AAPL.US".to_owned()),
|
||||
date_range: Some(MongoDateRange {
|
||||
gte: Some(FilterDateValue::IsoString("2024-01-01".to_owned())),
|
||||
lt: Some(FilterDateValue::IsoString("2025-01-01".to_owned())),
|
||||
}),
|
||||
..MongoReadSpec::default()
|
||||
};
|
||||
let filter = build_filter_document(SourceCollection::EodPrices, &spec).expect("valid spec");
|
||||
assert_eq!(
|
||||
filter,
|
||||
doc! { "eodSearchCode": "AAPL.US", "date": { "$gte": "2024-01-01", "$lt": "2025-01-01" } }
|
||||
);
|
||||
|
||||
let ms_spec = MongoReadSpec {
|
||||
date_range: Some(MongoDateRange {
|
||||
gte: None,
|
||||
lt: Some(FilterDateValue::BsonDateTimeMillis(1_700_000_000_000)),
|
||||
}),
|
||||
..MongoReadSpec::default()
|
||||
};
|
||||
let ms_filter = build_filter_document(SourceCollection::CeoShorts, &ms_spec).expect("valid");
|
||||
assert_eq!(
|
||||
ms_filter.get("timestamp"),
|
||||
Some(&Bson::Document(
|
||||
doc! { "$lt": DateTime::from_millis(1_700_000_000_000) }
|
||||
))
|
||||
);
|
||||
|
||||
let empty = build_filter_document(SourceCollection::TeMarketData, &MongoReadSpec::default())
|
||||
.expect("default spec is valid");
|
||||
assert!(empty.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redacted_source_hides_validated_password_even_without_full_uri_in_message() {
|
||||
let sentinel = "QA_SENTINEL_PW_4242";
|
||||
let uri = assert_read_only_mongo_uri(
|
||||
&format!("mongodb://studio_stock_bot_read:{sentinel}@localhost:27017/stock"),
|
||||
&ReadOnlyPolicy::default(),
|
||||
&LocalHosts::empty(),
|
||||
)
|
||||
.expect("valid read-only URI");
|
||||
let raw = format!("SCRAM failure: password={sentinel}; retry with '{sentinel}'");
|
||||
let err = MongoStreamError::redacted_source(&raw, &uri);
|
||||
for rendered in [format!("{err}"), format!("{err:?}")] {
|
||||
assert!(!rendered.contains(sentinel), "leaked: {rendered}");
|
||||
assert!(rendered.contains("[REDACTED]"));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue