T-124: M1.2aj — Spike: evidence-based evaluation of moving apps/stock/data-pipeline into Rust (written recommendation in design/data-pipeline/rust-migration-evaluation.md, no code changes)
This commit is contained in:
parent
8560b22c71
commit
4f09c6596d
1 changed files with 23 additions and 19 deletions
|
|
@ -9,7 +9,7 @@
|
|||
**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` rows through intermediate `.bson` files forces an unnecessary full NVMe write + read of hundreds of GiB to ~1 TiB of scratch data 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.
|
||||
- **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.
|
||||
|
||||
---
|
||||
|
|
@ -22,7 +22,7 @@ Measured directly from the repository working tree (no database connections). Ev
|
|||
| --- | ---: | ---: | ---: | ---: | --- |
|
||||
| `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 (`exchanges`, `symbols` queues), read-only MongoDB reads, PostgreSQL master reads/writes via `PipelineSyncRepository` |
|
||||
| `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`) |
|
||||
|
|
@ -43,7 +43,7 @@ Separately from production LOC, `apps/stock/data-pipeline/benchmarks/` holds **5
|
|||
### 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` (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`.
|
||||
- **`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
|
||||
|
|
@ -128,13 +128,16 @@ The binary already implements all **six M1 curation commands** (`curate-bars-1d`
|
|||
| `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` / `bars` / `provider_mapping` builders | `tools/curate-etl/README.md` (date omitted in README) | `bench-split`, `bench-bars`, `bench-provider-mapping` | `split`: `27.22M rows/s` (`10M` in `367.40 ms`); `bars`: `11.87M rows/s` (`10M` in `842.38 ms`); `provider_mapping`: `22.36M lookups/s` (`10M` in `447.14 ms`) |
|
||||
| `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=.../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 `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`)** |
|
||||
|
||||
---
|
||||
|
|
@ -152,14 +155,14 @@ Row volumes come from the measured 2026-11-26 QA MongoDB inventory in `design/da
|
|||
| 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.40B` docs through a local `.bson` file is a ~0.5–1 TiB NVMe bottleneck** |
|
||||
| **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:
|
||||
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):
|
||||
|
||||
- At the synthetic average `eodPrices` frame size of `161.7–285.6 B/doc` (`bench-curate-bars-cmd` / `bench-bson-eod-prices`), `845.7M` `eodPrices` docs represent roughly **137–242 GiB** of intermediate scratch data written and re-read (before `qmPrices` `51.5M` and `qmFilings` `30.5M`).
|
||||
- In M2, `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` docs at similar `~150–250 B/doc` scale represent roughly **~535–890 GiB** of intermediate `.bson` scratch files 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 both wall time and ~1 TB of NVMe wear/capacity. *(Actual live document sizes are unverified; see Section 7.)*
|
||||
- **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.)*
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -168,11 +171,11 @@ Even though `export-raw-bson.ts` avoids JS object deserialization (`3.57M–3.83
|
|||
| 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` | **Small (~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, `mongodb` read-only cursor wrapper (`RawDocumentBuf`), CLI `--mongo-uri` / `--collection` source selection alongside existing file flags | **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 |
|
||||
| **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 write+read penalty for intermediate `.bson` files (~140–240 GiB M1, ~535–890 GiB M2 estimated) | **Eliminates the entire `.bson` write+read stage** and TS process hop on bulk collections (`845.7M` `eodPrices`, `30.5M` `qmFilings`, `3.40B` `eodIntraday1M`), saving ~100% of bulk scratch NVMe I/O and overlapping MongoDB wire reads with Rust decode/Parquet/ILP writes. 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.40B` `eodIntraday1M` 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. **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 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` → 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`) and `qmIntraday` (`173.3M`) directly from read-only MongoDB → split un-adjustment → multi-socket QuestDB ILP v2 (`bars_1m`) with bounded RAM and zero `.bson` scratch files; 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 |
|
||||
| **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`.
|
||||
|
||||
|
|
@ -219,16 +222,17 @@ 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` mode into `curate-bars-1d` and `curate-events` (keeping file mode intact):** Allow bulk M1 commands to stream directly from read-only QA MongoDB without intermediate `.bson` files while preserving `--eod-prices <path>` file mode for deterministic offline tests and `mongodump` replay.
|
||||
4. **Reuse the Rust cursor adapter for M2 `curate-bars-1m` (QuestDB `10.2.0` ILP v2) and `curate-ceo-posts`:** Stream `3.40B` `eodIntraday1M`, `173.3M` `qmIntraday`, and `14.8M` `ceoPosts` directly from read-only MongoDB with zero `.bson` scratch files.
|
||||
5. **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 is verified on `quant`.
|
||||
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 `exchanges`/`symbols` queue consumers, `PipelineSyncRepository`, and Hono `GET /health` tightly integrated with `@stock-bot/di`, `@stock-bot/queue`, `@stock-bot/types`, and `web-api`.
|
||||
- **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`.
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -236,8 +240,8 @@ If the director approves Option B, the concrete follow-up sequence is:
|
|||
|
||||
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:** 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 depends on WiredTiger disk reads (`--wiredTigerCacheSizeGB 16`), localhost TCP framing, and BSON wire overhead on `stock` (`~638 GB`).
|
||||
2. **Real BSON document sizes & NVMe scratch footprint:** The intermediate `.bson` size estimates (`137–242 GiB` for `845.7M` `eodPrices`, `535–890 GiB` for `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday`) extrapolate from synthetic document byte sizes (`123.9–285.6 B/doc`); actual uncompressed BSON sizes in QA MongoDB are unmeasured.
|
||||
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`.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue