Compare commits

...

25 commits

Author SHA1 Message Date
Studio
b49ed59f40 T-207: M2.2t — tools/curate-etl: curate-macro CLI command (file mode) wiring the existing run_curate_macro into cli.rs + main.rs with parser tests and an end-to-end test (no new crates, no bench changes, no live Mongo) 2026-12-03 23:25:56 -05:00
Studio
9c5138a329 T-207: merge dev 2026-12-03 23:21:44 -05:00
Studio
66a0f99157 T-207: M2.2t — tools/curate-etl: curate-macro CLI command (file mode) wiring the existing run_curate_macro into cli.rs + main.rs with parser tests and an end-to-end test (no new crates, no bench changes, no live Mongo) 2026-12-03 22:56:36 -05:00
Studio
7ef7671a34 T-204: Audit M2 completion status and M3 readiness 2026-12-03 22:08:26 -05:00
Studio
9489d502a1 T-204: tests 2026-12-03 22:04:42 -05:00
Studio
86c30dd23b T-204: Audit M2 completion status and M3 readiness 2026-12-03 21:56:07 -05:00
Studio
448a557805 T-204: Audit M2 completion status and M3 readiness 2026-12-03 21:47:28 -05:00
Studio
1928f3cb77 T-203: Audit M2 exit criteria on master against docs/MILESTONES.md 2026-12-03 19:26:06 -05:00
Studio
8873434914 T-203: tests 2026-12-03 19:22:19 -05:00
Studio
e51c721b24 T-203: Audit M2 exit criteria on master against docs/MILESTONES.md 2026-12-03 19:17:13 -05:00
Studio
4be07930ce T-203: Audit M2 exit criteria on master against docs/MILESTONES.md 2026-12-03 19:11:05 -05:00
Studio
6829a94d5f T-203: Audit M2 exit criteria on master against docs/MILESTONES.md 2026-12-03 19:03:02 -05:00
Studio
19f9bb1e4a T-202: M2.2t (retry of T-201) — tools/curate-etl: curate-macro CLI command (file mode) wiring the existing run_curate_macro into cli.rs + main.rs with parser tests and a binary end-to-end test (no new crates, no bench changes, no live Mongo) 2026-12-03 15:50:45 -05:00
Studio
8b93a58ec7 T-202: tests 2026-12-03 15:46:46 -05:00
Studio
8f3126cf30 T-202: M2.2t (retry of T-201) — tools/curate-etl: curate-macro CLI command (file mode) wiring the existing run_curate_macro into cli.rs + main.rs with parser tests and a binary end-to-end test (no new crates, no bench changes, no live Mongo) 2026-12-03 15:40:00 -05:00
Studio
9279bb0f08 T-202: M2.2t (retry of T-201) — tools/curate-etl: curate-macro CLI command (file mode) wiring the existing run_curate_macro into cli.rs + main.rs with parser tests and a binary end-to-end test (no new crates, no bench changes, no live Mongo) 2026-12-03 15:40:00 -05:00
Studio
ccb37b793b T-200: M2.1t (retry of T-197) — Land the PostgreSQL executor factory for the MCP copilot stdio host: openResearchCopilotExecutor(config) in libs/data/postgres/src/research-copilot-executor.ts, reusing the finished T-197 branch work and completing QA sign-off (no new deps, no DuckDB, no bin, no curate-etl changes) 2026-12-03 15:31:03 -05:00
Studio
267e655e63 T-200: merge dev 2026-12-03 15:23:16 -05:00
Studio
e720c879df T-200: edits made in the worktree 2026-12-03 15:19:01 -05:00
Studio
872debd9c6 T-200: M2.1t (retry of T-197) — Land the PostgreSQL executor factory for the MCP copilot stdio host: openResearchCopilotExecutor(config) in libs/data/postgres/src/research-copilot-executor.ts, reusing the finished T-197 branch work and completing QA sign-off (no new deps, no DuckDB, no bin, no curate-etl changes) 2026-12-03 15:05:06 -05:00
Studio
7bf9bb6c20 T-200: M2.1t (retry of T-197) — Land the PostgreSQL executor factory for the MCP copilot stdio host: openResearchCopilotExecutor(config) in libs/data/postgres/src/research-copilot-executor.ts, reusing the finished T-197 branch work and completing QA sign-off (no new deps, no DuckDB, no bin, no curate-etl changes) 2026-12-03 15:05:06 -05:00
Studio
436616b343 T-199: tests 2026-12-03 14:56:44 -05:00
Studio
fc2312ebeb T-199: M2.2s — tools/curate-etl: file-mode run_curate_macro runner (teData BSON dump + caller-supplied series-map TSV → curate_and_write_macro → macro/part.parquet) in run_curate_macro.rs with lib tests (no new crates, no CLI/bench changes, no live Mongo) 2026-12-03 14:50:00 -05:00
Studio
2a7485a15c T-198: tests 2026-12-03 14:34:19 -05:00
Studio
564f768c8e T-198: M2.2r — tools/curate-etl: curate-fundamentals CLI command (file mode) wiring the existing run_curate_fundamentals into cli.rs + main.rs with parser tests and a binary end-to-end test (no new crates, no bench changes, no live Mongo) 2026-12-03 14:27:13 -05:00
16 changed files with 5263 additions and 14 deletions

View file

@ -14,6 +14,7 @@ Start here. Every document below has a single responsibility; historical sprint
| **[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 |
| **[m2-completion-audit.md](m2-completion-audit.md)** | Read-only Milestone `M2` completion audit, gate results & pending host checks, candidate Auto Mode parking causes, director decisions, and `M3` readiness mapping (`T-204`) | Before closing `M2`, queuing remaining `M2` tasks, or starting `M3` |
---

View file

@ -0,0 +1,122 @@
# Milestone M2 Completion Audit & M3 Readiness Report (T-204)
**Verdict:** **HOLD M3 — M2 is ~70% complete on the audited `feat/audit-m2-completion-status-m3` checkout (branched from `master`; exact `master` commit SHA pending host-side `git` verification), with 7 concrete wiring/contract gaps remaining before M2 closure.**
All sandbox-runnable TypeScript, ESLint, contract, and Rust native gates passed in the programmer's sandboxed run on the review checkout (`0` errors, `0` warnings), and Studio's unsandboxed review-branch runs (`#1597` build and `#1598` test suite) passed. Core M2 building blocks — `send-ilp` (`T-190`), the 6-tool MCP copilot server, file-mode PIT fundamentals/`ceoPosts`/`teData` curaters, QuestDB `10.2.0` schemas, and the TypeScript Feature Library — are landed and tested. However, desktop Claude Code cannot launch the MCP server end-to-end (`T-196` entrypoint is absent from the checkout), `ceoPosts` writes `"post"` instead of `"ceo_post"`, `MarketDataStore` rejects `crossSection`/`macroAsOf`/`fx('1m')`, `curate-qm-bars-1m` has no CLI subcommand, Python `stockbot` lacks `register_signal` and M2 store methods, and the live `quant` QuestDB `10.2.0` preflight, observed split-boundary check, and latency gates remain unverified.
> **Scope & Provenance Notes**
> - **Audit-only:** Zero production code, build config, or CI changes (project CI is off).
> - **Audited checkout & `master` relationship:** Audited in the task worktree on branch `feat/audit-m2-completion-status-m3` (branched from `master` for `T-204`). Because worktree `.git` metadata lives outside the agent sandbox, the exact `master` commit SHA and `studio/auto-*` branch history could not be read here and remain **PENDING** host-side verification. Every deliverable below was verified directly from source files, exports, CLI parsers, and test execution in this checkout.
> - **Documentation path drift:** Milestone and contract docs moved from `docs/` to `design/`, while `AGENTS.md` (lines 43–48), `CLAUDE.md` (lines 3, 7–11), `README.md` (lines 7, 9, 11–13, 142, 264, 435), and `studio.config.json` still reference `docs/*.md`.
> - **Prior M1 deferral:** Per settled director decision (`d52aa20`), M1 equity eligibility classification and cutoff-separated Parquet benchmarking stay deferred in the backlog and do not block M2.
---
## 1. Verification Gate Results & Pending Host Checks
### 1.1 Programmer Sandbox Runs (Review Worktree `feat/audit-m2-completion-status-m3`)
Executed inside the agent sandbox (network disabled; zero contact with QA MongoDB `27017/stock` or QA PostgreSQL `5432/trading_bot`; counts below are attributed to the programmer's sandbox execution without retained log files on disk):
| Gate / Suite | Command | Exit | Programmer-Observed Outcome & Counts |
| --- | --- | :---: | --- |
| Typecheck | `bun run typecheck` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.check.json --noEmit`) |
| Contracts | `bun run test:contracts` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.contracts.json --noEmit`) |
| Lint | `bun run lint:check` | `0` | **PASS** — `0` errors, `0` warnings (`--max-warnings 0`) |
| Utils | `bun run test:utils` | `0` | **PASS** — `32` pass, `0` fail (`59` expects, `3` files) |
| Calculations | `bun run test:calculations` | `0` | **PASS** — `144` pass, `0` fail (`76,602` expects, `12` files) |
| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PASS** — `1,548` passed, `0` failed, `4` ignored across `57` suites (`engine` + `curate-etl`, incl. `tcp_sends_separate_shards_and_half_closes`, `restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2`, and the synthetic `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` fixture) |
| M2 Research, DuckDB, QuestDB & Scripts | `bun test libs/research/ libs/data/duckdb/ libs/data/questdb/ scripts/test/security.test.ts scripts/test/workspace.test.ts` | `0` | **PASS** — `1,032` pass, `0` fail (`80,869` expects, `63` files; includes real-DuckDB `fundamentalsAsOf` restatement fixture and MCP Vault-fence suite) |
| Postgres Copilot Executor & Unit Suites | `bun test libs/data/postgres/test/research-copilot-executor.test.ts libs/data/postgres/test/research-copilot-executor-edge.test.ts test/unit/` | `0` | **PASS** — `640` pass, `0` fail (`734,988` expects, `44` files) |
| Python SDK (`python/tests/`) | `python3 -m pytest` | N/A | **SKIPPED (env)** — `pytest` / `python/.venv` not installed in the sandbox |
### 1.2 Studio Unsandboxed Runs & Remaining Host Verification
| Verification | Scope / Command | Status | Notes |
| --- | --- | :---: | --- |
| **Studio Build `#1597`** | `bun run build` on review branch `feat/audit-m2-completion-status-m3` | **PASS** | Reported green by Studio on the review branch. |
| **Studio Test Run `#1598`** | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` on review branch `feat/audit-m2-completion-status-m3` | **PASS** | Reported green by Studio on the review branch (covers Bun test suites including isolated `stock_bot_safety*` PostgreSQL tests, plus Rust workspace `--lib` tests). |
| **Full Host Check & `master` Provenance** | Record `master` SHA, inspect `studio/auto-*` branches, and run `CARGO_BUILD_JOBS=2 bun run check` (incl. `audit:secrets`, `test:tooling`, `test:integration`, `lint:check`) + `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` with retained logs | **PENDING** | Not covered by Studio runs `#1597`/`#1598`; must be executed on the host against the confirmed `master` revision before M2 closure (see `design/m2-gap-audit.md:118-122`). |
**Research & Financial Invariants Verified Across Passing Suites**
- **Economic ownership & durable inputs:** Quant data curation owns immutable Zstd Parquet partitions (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`, `macro`) and QuestDB ILP v2 shards; PostgreSQL owns append-only `trial_ledger`, `findings`, and `provider_caveats` (`database/postgres/init/37-research-findings.sql:81-99`).
- **Holdout Vault fence:** `createQueryDataTool` (`libs/research/src/mcp/tools/query-data.ts`) and `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:40`) hardcode `vaultOperatorAuthorized: false`, reject `scope`/`vault_evaluation_only` keys, clamp bounds strictly below `vaultCutoffTs`, and drop post-cutoff rows (`libs/research/test/mcp-query-data.test.ts`).
- **PIT & synthetic split conservation:** Both Rust (`tools/curate-etl/src/fundamentals_tests.rs:104`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251,601-626`) prove `known_at <= asOf` and Q1-after-Q2 restatement non-overwrite. **Synthetic** Rust fixtures (`tools/curate-etl/src/bars_1m_tests.rs:107,220` and `tools/curate-etl/src/run_curate_bars_1m_tests.rs:377-402`) prove `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split arithmetic and ex-date boundary handling within `0.5%`, while observed-data comparison against retained raw `bars_1d` closes remains open (`run_curate_bars_1m_tests.rs:396-400`).
- **Database & execution safety:** Read-only MongoDB/Postgres adapters verified; zero paper/live execution write access in research/MCP surfaces.
---
## 2. M2 Deliverables & Exit Criteria Matrix
### 2.1 Deliverables (`design/MILESTONES.md` lines 87–98)
| Area | Status | Landed in Checkout (Exact Evidence) | Concrete Gaps Remaining |
| --- | :---: | --- | --- |
| **M2.1** Research Copilot MCP & Notebook Snapshots | **PARTIAL** | All 6 tools wired in `createResearchCopilotMcpServer` (`libs/research/src/mcp/copilot-server.ts:13-20,48`); stdio host (`libs/research/src/mcp/host/stdio-host.ts`); Postgres adapters (`libs/research/src/mcp/adapters/postgres-copilot.ts`, `postgres-trial-ref.ts`, `library-cards.ts`, `exchange-calendars.ts`, `bar-session-dates.ts`); `openResearchCopilotExecutor` (`libs/data/postgres/src/research-copilot-executor.ts`); `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:33`); SQL schema (`database/postgres/init/37-research-findings.sql`); `exportNotebookSnapshot` (`libs/research/src/notebook-snapshot.ts:594`, `notebook-snapshot-node.ts:67`). | **(1)** `T-196` desktop entrypoint `scripts/research-copilot-mcp.ts` and `"mcp:research-copilot"` in `package.json` are missing; `apps/stock/web-api/src/` has no optional SSE wrapper. **(2)** `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:37`) opens daily DuckDB only instead of composing `createRoutedMarketDataStore` + `createQuestDbIntradayBarsReader` for `1m` queries. **(3)** `analyze_signal` (`libs/research/src/mcp/tools/analyze-signal.ts:121-123`) restricts `signal.source` to `'shorts' \| 'fundamentals'` (no `ceoPosts`, `macro`, or materialized `features`). **(4)** `exportNotebookSnapshot` has no CLI or MCP entrypoint and no end-to-end MCP study + `marimo check`-clean HTML + `file_finding` verification test. |
| **M2.2** PIT Fundamentals, `ceoPosts` & Lagged `teData` | **PARTIAL** | File-mode CLIs `curate-fundamentals`, `curate-posts`, and `curate-macro` wired in `tools/curate-etl/src/cli.rs:99-101,1295,1573,1684` and `main.rs:228,238,250`; Rust Q1-after-Q2 restatement test (`tools/curate-etl/src/fundamentals_tests.rs:104`); real-DuckDB TS `fundamentalsAsOf` implementation & restatement test (`libs/research/src/market-data-store-duckdb.ts:2287`, `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`). | **(1)** `EVENT_KIND_POST = "post"` (`tools/curate-etl/src/parquet_posts.rs:22`) mismatches `'ceo_post'` required by `libs/research/src/market-data-store-duckdb.ts:108`, `libs/research/src/event-panel.ts:63`, and `python/stockbot/data.py:21`, and `run_curate_posts` fails closed (`EventsDatasetExists`, `tools/curate-etl/src/run_curate_posts.rs:133,389`) if `<out>/events` already exists from `curate-events`; both TS (`market-data-store-duckdb.ts:1448`) and Python (`python/stockbot/data.py:71`) only glob `events/year=*/part.parquet`. **(2)** `createDuckDbMarketDataStore().macroAsOf` (`libs/research/src/market-data-store-duckdb.ts:2294-2296`) throws `MarketDataStoreNotImplementedError`, blocking read-back of `macro/part.parquet` (note: per `design/DATA-CONTRACTS.md:26`, `teData` holds final-revised values only and must remain restricted to coarse lagged regime filters, not historical release signals without vintage data). **(3)** `SourceCollection` (`tools/curate-etl/src/mongo_stream.rs:53-62`) allowlists only the 8 M1 collections — no `--from-mongo` streaming for `qmFinancials`, `qmFinancials-old`, `ceoPosts`, or `teData`, and `curate-fundamentals` lacks `--qm-financials-old` merging. **(4)** Python `stockbot.data.MarketDataStore` (`python/stockbot/data.py`) lacks `fundamentals_as_of` and `macro_as_of`. |
| **M2.3** QuestDB `10.2.0` Intraday & `send-ilp` (`T-190`) | **PARTIAL** | `T-190` `send-ilp` CLI landed (`tools/curate-etl/src/cli.rs:102,2290`, `main.rs:260`, `ilp_send.rs`, `ilp_send_tests.rs` loopback `TcpListener` tests); `curate-bars-1m` and `curate-fx-1m` CLIs wired (`cli.rs:97-98`, `main.rs:208,218`); `M2_INTRADAY_SCHEMAS` (`libs/data/questdb/src/schema.ts:13-63`) with `PARTITION BY MONTH`, `WAL`, `SYMBOL CAPACITY 65536 NOCACHE`, `DEDUP UPSERT KEYS`; `docker-compose.quant.yml:35-39,52-53` (`nofile: 1048576`, `QDB_RAM_USAGE_LIMIT_BYTES=21474836480`); synthetic `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split fixtures (`bars_1m_tests.rs:107,220`, `run_curate_bars_1m_tests.rs:377-402`). | **(1)** `run_curate_qm_bars_1m` (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`, `T-185`) is not wired into `cli.rs`/`main.rs` (no `curate-qm-bars-1m` subcommand). **(2)** `MarketDataStore.fx({ timeframe: '1m' })` throws `MarketDataStoreNotImplementedError` in TS (`libs/research/src/market-data-store-duckdb.ts:1529-1530`, delegated unchanged by `createRoutedMarketDataStore` at `libs/research/src/market-data-store-routed.ts:184-186`) and `NotImplementedError` in Python (`python/stockbot/data.py:259`). **(3)** No `--from-mongo` streaming for `eodIntraday1M` (`3.40B` docs) or `qmIntraday` (`173.3M` docs). **(4)** Live `quant` preflight (`vm.max_map_count >= 1048576`, effective container `nofile = 1048576`, WAL DDL), binary-double (`0x10`) TCP ILP v2 acceptance (`tools/curate-etl/src/ilp_send.rs:15-21`), observed `NEXM.V`/`NVDA.US` comparison against retained raw `bars_1d`, and pinned PGWire 1-year `1m` read benchmark (`< 250 ms` warm / `< 1 s` cold) are all unverified. |
| **M2.4** Versioned Feature Library (`D04` / `D11`) | **PARTIAL** | TS `registerSignal`, `runFeatureBatch`, and Zstd Parquet writer landed (`libs/research/src/feature-library.ts`); built-in `RET_1D_V1` (`feature-library.ts:2166`). | **(1)** `createDuckDbMarketDataStore().crossSection` (`libs/research/src/market-data-store-duckdb.ts:2283-2285`) throws `MarketDataStoreNotImplementedError`, blocking read-back of materialized `features/<name>/v<version>/` Parquet. **(2)** `FEATURE_INPUT_DATASETS` (`libs/research/src/feature-library.ts:61-68`) omits `'macro'` (coarse regime filters only per `DATA-CONTRACTS.md:26`) and `'corporate_actions'`, and registers only `'RET_1D_V1'`. **(3)** Python `stockbot` (`python/stockbot/__init__.py`, `data.py`, `signals.py`) lacks `cross_section` and `register_signal` (`D04`/`D11`). |
### 2.2 Exit Criteria (`design/MILESTONES.md` lines 100–103)
| Exit Criterion | Status | Evidence & Remaining Blocker |
| --- | :---: | --- |
| **EC-1:** Desktop Claude Code via MCP runs a fundamental + alt-data signal study and event study end-to-end, exports a `marimo check`-clean static HTML snapshot, and files a finding. | **OPEN** | All 6 MCP tools and `exportNotebookSnapshot` exist as libraries, but `scripts/research-copilot-mcp.ts` / `"mcp:research-copilot"` (`T-196`) is missing, `ceoPosts` cannot be read via `event_study` (`"post"` vs `"ceo_post"`), and no end-to-end MCP → HTML snapshot → `file_finding` verification exists. |
| **EC-2:** Restatement fixture test proves a restated Q1 (`known_at > Q2`) never overwrites Q2 in `fundamentalsAsOf`. | **SATISFIED (Offline Fixture)** | Proven in both Rust (`tools/curate-etl/src/fundamentals_tests.rs:104`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251,601-626`), both passing in sandbox and Studio test run `#1598`. |
| **EC-3:** Split-boundary test on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirms `bars_1m` session closes match raw `bars_1d` closes within `0.5%`, and 1y of `1m` bars loads in `< 250 ms` warm / `< 1 s` cold. | **OPEN (Synthetic Only)** | **Synthetic** Rust fixtures (`tools/curate-etl/src/bars_1m_tests.rs:107,220`, `run_curate_bars_1m_tests.rs:377-402`) pass for split arithmetic only and explicitly leave observed comparison against retained raw `bars_1d` open (`run_curate_bars_1m_tests.rs:396-400`). Still open on `quant`: (1) effective `vm.max_map_count >= 1048576` & container `nofile = 1048576` preflight before bulk load; (2) live QuestDB `10.2.0` binary-double (`0x10`) TCP ILP v2 acceptance; (3) observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` close check (`<= 0.5%`); and (4) pinned 1-year single-listing PGWire benchmark (`QuestDBClient.query` → `createQuestDbIntradayBarsReader`) recording listing ID, date range, cache conditions, and expected vs. actual row counts against `< 250 ms` warm / `< 1 s` cold. |
---
## 3. Candidate Causes: Why M2 Auto Mode May Have Parked 3 Consecutive Tasks
No parked task receipts or Auto Mode run logs are available inside the sandbox, so **none of the four items below can be attributed to a specific parked task yet**. Separating what is directly observed in the checkout from what remains inferred pending host history/log inspection:
1. **Missing `T-196` desktop MCP entrypoint *(observed in checkout; branch-reset cause inferred/unverified)*:** `scripts/research-copilot-mcp.ts` and `"mcp:research-copilot"` in `package.json` are absent from the checkout, whereas `T-190` (`send-ilp`) and `curate-macro` are present. Any Auto Mode task expecting a runnable desktop MCP entrypoint would hit an immediate blocker. Whether `T-196` was dropped during a `studio/auto-*` branch reset remains **unverified** until host-side branch history is inspected (`design/m2-gap-audit.md:119`).
2. **`docs/*` → `design/*` path drift *(observed in checkout; park attribution unverified)*:** `AGENTS.md` (L43–48), `CLAUDE.md` (L3, L7–11), `README.md` (L7, L9, L11–13, L142, L264, L435), `studio.config.json`, and older task prompts still point to `docs/*.md`, which can cause agents to fail path checks against the renamed `design/` directory.
3. **Sandbox boundary friction for `.git`, PostgreSQL, and `quant` *(observed environment constraint; park attribution unverified)*:** Running `bun run check`, `audit:secrets`, worktree-git tests (`scripts/test/`), `PIPELINE_TEST_DATABASE_URL` (`127.0.0.1:5432`) suites, or live `quant` QuestDB checks inside the agent sandbox fails by design; tasks without explicit host/sandbox separation can park on those expected errors.
4. **Unqueued Option B `--from-mongo` extension for M2 collections *(observed in checkout; park attribution unverified)*:** The `2026-11-30` addendum in `design/data-pipeline/rust-migration-evaluation.md` (lines 253–294) locked Option B (`tools/curate-etl --from-mongo`) for M1 and scoped M2's 6 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`) to M2, but `SourceCollection` (`tools/curate-etl/src/mongo_stream.rs:53-62`) still allowlists only the 8 M1 collections.
---
## 4. Concrete Blockers Needing Director Decisions
1. **Option B `--from-mongo` for M2 collections vs. `.bson` staging:** Should we extend `tools/curate-etl` `SourceCollection` with `--from-mongo` streaming for the 6 M2 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`), or close M2 in file-mode `.bson` staging?
- *Recommended:* Extend `--from-mongo` to the 6 M2 collections (reusing the M1 `ReadOnlyMongoClient` + `ChunkedMongoRawDocumentSource` pattern) so `3.40B` `eodIntraday1M` docs never require `~500–832 GiB` of intermediate `.bson` scratch files.
2. **Canonical `ceoPosts` event `kind` & `<out>/events` co-publishing:** Should `tools/curate-etl/src/parquet_posts.rs` switch `EVENT_KIND_POST` from `"post"` to `"ceo_post"` and co-publish alongside `curate-events` under `<out>/events/year=YYYY/` (either by writing `part-posts.parquet` **and updating both readers** — `libs/research/src/market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` — from `events/year=*/part.parquet` to `events/year=*/*.parquet`, or by merging posts into yearly `part.parquet`), or keep posts in a separate curated root?
- *Recommended:* Change `EVENT_KIND_POST` to `"ceo_post"`, write `events/year=YYYY/part-posts.parquet`, **and update both TS (`market-data-store-duckdb.ts:1448`) and Python (`python/stockbot/data.py:71`) readers to glob `events/year=*/*.parquet`** (verified by a combined read-back fixture with filings, earnings, and an edited CEO post in the same curated root) so `curate-events` and `curate-posts` remain independently re-runnable without hiding posts from either reader.
3. **Live `quant` QuestDB `10.2.0` preflight, observed split check & latency gate for M2 closure:** Should M2 closure require an operator-run `quant` QuestDB `10.2.0` verification covering host/container limits (`vm.max_map_count`, `nofile`), binary-double (`0x10`) TCP ILP v2 acceptance, observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` closes (`<= 0.5%`), and a pinned 1-year single-listing PGWire latency benchmark (`< 250 ms` warm / `< 1 s` cold), or accept synthetic-fixture closure and defer all live `quant` checks to an ops follow-up (matching the M1 `d52aa20` precedent)?
- *Recommended:* Require a small-slice (`NEXM.V` + `NVDA.US`, 1 year) operator verification on `quant` covering all four checks above before closing M2, while deferring full `3.40B`-row backfill to an ops runbook.
---
## 5. M3 Readiness Mapping & Recommended Task Order
**Verdict: Do not start M3 yet.** M2 must close first, and M3's core engine, screener, and validation deliverables are unstarted on this checkout.
### 5.1 M3 Deliverables & Exit Criteria Readiness Map (`design/MILESTONES.md` lines 111–128)
| M3 Item | Status | Target Files & Current Checkout Evidence |
| --- | :---: | --- |
| **Tier 1 Columnar Screener** (`MILESTONES.md:112-113`) | **NOT STARTED** | Append-only `trial_ledger` SQL exists (`database/postgres/init/36-trial-ledger.sql`), and `libs/calculations/src/index.ts` exports `deflatedSharpeRatio`, `effectiveIndependentTrials`, `analyzeSignalPanel`, `eventStudy`, `evaluateRecencyGate`. No Polars/DuckDB portfolio sweep, $M_{T \times N}$ writer, or CSCV `PBO` ($S = 16$) yet. |
| **Tier 2 Rust `financial/` Multi-Asset Upgrades** (`MILESTONES.md:114-119`) | **NOT STARTED** | `apps/stock/engine/Cargo.toml` has no `parquet`/`arrow-rs` crates yet; `apps/stock/orchestrator/src/backtest/{native-worker,candidate-sandbox}.ts` still use the single-series JSON/IPC path. Task 1 (retire `backtest_datasets` JSONB/IPC/N-API bar path), atomic timestamp-slice marks (`F06`), simultaneous `Target` sell-netting, feature side-channel, and `USD`/`CAD` Margin + corporate actions/delisting in `apps/stock/engine/src/financial/*` are all unstarted. |
| **Validation Suite & Engine Consolidation** (`MILESTONES.md:120-123`) | **PARTIAL (SQL only)** | `vault_evaluations` table with `<= 10/year` cap & append-only triggers exists (`database/postgres/init/36-trial-ledger.sql:44-138`), and `apps/stock/analytics` / `SimulationExecution` are already absent from the repo. Purged Walk-Forward/CPCV, stability surface, ADV capacity, US/CA factor exposure, human Vault Holdout Gate workflow, and retirement of legacy `f64` `BacktestEngine` (`apps/stock/engine/src/backtest/engine.rs:17`, `apps/stock/engine/src/api/backtest.rs:13`) remain **NOT STARTED**. |
| **M3 EC-1:** Rust unit + differential accounting fixtures (`MILESTONES.md:126`) | **OPEN** | Atomic hedged mark neutrality, 100%-invested `Sell A + Buy B` target rotation, split + dividend 8-decimal conservation, USD/CAD margin interest, TSX board-lot sizing, and `SIVB` delisting liquidation fixtures are not yet implemented. |
| **M3 EC-2:** 20y US+CA daily backtest (`~5,000+` listings) in `< 30 s` on `quant` (`MILESTONES.md:127`) | **OPEN** | Blocked on Tier 2 Parquet/Arrow-rs path + multi-asset engine upgrades. |
| **M3 EC-3:** Real M2 signal via `register_signal` end-to-end (`MILESTONES.md:128`) | **OPEN** | Blocked on M2 Python `register_signal` + `crossSection` read-back and M3 Tier 1/Tier 2/CPCV/Vault gate. |
### 5.2 Ordered Task List to Finish M2 (8 Tasks)
1. **Restore `T-196` desktop MCP entrypoint & wire routed intraday store:** Add `scripts/research-copilot-mcp.ts` + `"mcp:research-copilot"` in `package.json`, and update `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`) to compose `createRoutedMarketDataStore` + `createQuestDbIntradayBarsReader` when QuestDB config is present.
2. **Fix `ceoPosts` `kind = 'ceo_post'`, `<out>/events` co-publishing & reader globs:** Change `EVENT_KIND_POST` in `tools/curate-etl/src/parquet_posts.rs` to `"ceo_post"`, co-publish `ceoPosts` under `<out>/events/year=YYYY/` (either writing `part-posts.parquet` and updating both `libs/research/src/market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` to glob `events/year=*/*.parquet`, or merging into yearly `part.parquet`), and add a combined read-back fixture containing filings, earnings, and an edited CEO post in the same curated root.
3. **Implement `MarketDataStore.macroAsOf`, `crossSection`, and `fx('1m')`:** Implement DuckDB read-back for `macro/part.parquet` (`macroAsOf`, enforcing/documenting the `design/DATA-CONTRACTS.md:26` coarse lagged regime-filter-only limit since `teData` lacks release vintages) and versioned `features/<name>/v<version>/` (`crossSection`) in `libs/research/src/market-data-store-duckdb.ts`, and route `fx({ timeframe: '1m' })` to QuestDB `fx_1m` in `libs/research/src/market-data-store-routed.ts`.
4. **Wire `curate-qm-bars-1m` CLI & expand Feature Library inputs:** Expose `curate-qm-bars-1m` in `tools/curate-etl/src/{cli,main}.rs`, add `'macro'` (restricted to lagged regime filters per `DATA-CONTRACTS.md:26` until vintage data exists) and `'corporate_actions'` to `FEATURE_INPUT_DATASETS` in `libs/research/src/feature-library.ts`, and extend MCP `analyze_signal` to support materialized `features` (and `ceoPosts` / regime-only `macro` as needed).
5. **Add Python `stockbot` M2 parity & `register_signal` (`D04`/`D11`):** Expose `fundamentals_as_of`, `macro_as_of` (regime-only), `cross_section`, `fx(..., timeframe='1m')`, and `register_signal(...)` in `python/stockbot/` with offline `pytest` coverage.
6. **Extend `curate-etl --from-mongo` to the 6 M2 collections (subject to Director Decision 1):** Add `qmFinancials`, `qmFinancials-old` (with `--qm-financials-old` merge), `ceoPosts`, `teData`, `eodIntraday1M`, and `qmIntraday` to `SourceCollection` in `tools/curate-etl/src/mongo_stream.rs`.
7. **Add M2 Exit Criterion 1 end-to-end verification & doc path cleanup:** Add a CLI/MCP wrapper + end-to-end test covering MCP study → `marimo check`-clean HTML snapshot (`exportNotebookSnapshot`) → `file_finding`, and update stale `docs/` links in `AGENTS.md`, `CLAUDE.md`, `README.md`, and `studio.config.json` to `design/`.
8. **Operator `quant` QuestDB `10.2.0` preflight, observed split check & latency benchmark (Exit Criterion 3):** Before bulk load, verify on `quant` effective `vm.max_map_count >= 1048576`, container `ulimits.nofile = 1048576`, memory limits, and `getM2IntradayDDL()` WAL tables; run `send-ilp` on a small `NEXM.V` + `NVDA.US` 1-year slice to verify `0x10` binary-double acceptance and `wal_tables()` health via PGWire; compare observed `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) `bars_1m` session closes against retained raw `bars_1d` closes (`<= 0.5%`); and run a pinned 1-year single-listing `1m` benchmark through `QuestDBClient.query` → `createQuestDbIntradayBarsReader` (re-verifying via `createRoutedMarketDataStore` once wired) recording listing ID, date range, cache conditions, and expected vs. actual row counts against `< 250 ms` warm / `< 1 s` cold.
### 5.3 Initial M3 Prerequisite Sequence (Once M2 Closes)
1. **Retire JSON-over-Postgres/IPC/N-API bar path (M3 Task 1):** Add `parquet`/`arrow-rs` to `apps/stock/engine/Cargo.toml`, store `(hash, manifest, parquet_paths)` in `backtest_datasets`, and lift single-series TS gates in `native-worker.ts`.
2. **Tier 1 Columnar Screener & CSCV PBO (`S = 16`):** Implement CSCV `PBO` and Purged Walk-Forward/CPCV in `libs/calculations`, plus vectorized Polars/DuckDB portfolio sweeps logging $M_{T \times N}$ matrices to `trial_ledger`.
3. **Tier 2 Rust `financial/` multi-asset upgrades & legacy retirement:** Implement atomic timestamp-slice marks (`F06`), simultaneous `Target` sell-netting, feature side-channel, `USD`/`CAD` Margin + corporate-action/delisting accounting (with all 6 M3 EC-1 fixtures), human Vault Holdout Gate workflow, and retirement of legacy `f64` `BacktestEngine`.

133
design/m2-gap-audit.md Normal file
View file

@ -0,0 +1,133 @@
# Milestone M2 Gap Audit Report (T-203)
**Verdict:** **OPEN — M2 is not ready for closure.** Core M2 libraries (`curate-macro`, `send-ilp`, MCP server/adapters with Vault-fenced `query_data`, `fundamentalsAsOf`, QuestDB `10.2.0` primitives, and TS Feature Library) are present in the checked-out worktree and are programmer-reported green in the provisioned sandbox, but six concrete code/wiring gaps remain (including the missing desktop MCP entry point, unwired equity `1m` QuestDB consumer routing, and a `ceo_post` vs `post` event-kind mismatch). Traceable gate verification (with confirmed checkout SHA and retained logs) and all host-only `master` / `quant` / desktop closure gates remain **PENDING**.
> **Scope & Provenance Notes:**
> - Milestone and contract documents live under `design/` (`design/MILESTONES.md`, `design/DATA-CONTRACTS.md`, `design/PLATFORM-PLAN.md`), not `docs/`.
> - **Revision status:** Worktree `.git` metadata lives outside the sandbox boundary, so the exact base `master` SHA and `studio/auto-*` branches could not be inspected inside the sandbox. All local checks below ran against the checked-out worktree on branch `feat/m2-gap-audit` (`/home/boki/.studio/worktrees/stock-bot/slot-1`); authoritative `master` verification remains **PENDING** until the host confirms the `master` SHA.
> - Per settled director decision, **T-127** (M1 equity eligibility / Vault file isolation) stays deferred in the backlog and does not block M2.
> - Project CI is off; no CI workflows were planned, added, or modified.
---
## 1. Verification History & Worktree Gate Results
### 1.1 Earlier Planning-Phase Setup Failures (Recorded in Approved Plan)
During the initial read-only planning pass (unprovisioned environment before worktree dependencies and writable Cargo target were available), all four requested local gates and supplemental tests failed during setup:
| Gate / Suite | Command | Exit Code | Planning-Phase Outcome |
| --- | --- | --- | --- |
| Typecheck | `bun run typecheck` | `2` | **FAIL** — `TS2688` missing `bun-types` |
| Contracts | `bun run test:contracts` | `2` | **FAIL** — `TS2688` missing `bun-types` |
| Lint | `bun run lint:check` | `127` | **FAIL** — `eslint: command not found` |
| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `101` | **FAIL** — `Read-only file system (os error 30)` creating Cargo target path |
| Supplemental M2 `bun test` | copilot server, stdio, snapshot exporter, DuckDB store, ILP writer | `1` | **FAIL** — missing `zod` and `@stock-bot/logger` during import setup |
### 1.2 Programmer-Reported Worktree Sandbox Runs (Verification Pending)
Executed interactively in the provisioned worktree `/home/boki/.studio/worktrees/stock-bot/slot-1` (branch `feat/m2-gap-audit`, Linux sandbox, network disabled).
- **Tested checkout revision:** **Unavailable in sandbox** (worktree `.git` metadata lives outside the sandbox boundary).
- **Retained command log / run reference:** **None** (ephemeral sandbox terminal output only).
- **Verification status:** **PENDING.** Because neither a confirmed checkout SHA nor retained command logs/run IDs are available for these four gates and supplemental suites, the rows below are **programmer-reported** only and do not constitute verified passes on `master` or the audited revision.
| Gate / Suite | Command | Exit Code | Status (Programmer-Reported) |
| --- | --- | --- | --- |
| Typecheck | `bun run typecheck` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors reported |
| Contracts | `bun run test:contracts` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors reported |
| Lint | `bun run lint:check` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors, 0 warnings reported |
| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PROGRAMMER-REPORTED (pending)** — `1,548` passed, `0` failed, `4` ignored across `57` suites |
| MCP `query_data` Vault Fence | `bun test libs/research/test/mcp-query-data.test.ts` | `0` | **PROGRAMMER-REPORTED (pending)** — `13` pass, `0` fail |
| Real-DuckDB M2 Fixtures | `bun test libs/data/duckdb/test/` | `0` | **PROGRAMMER-REPORTED (pending)** — `25` pass, `0` fail across `4` files; includes Exit 2 restatement fixture & `openResearchCopilotStore` |
| Research + QuestDB + Copilot Executor | `bun test libs/research/test/ libs/data/questdb/test/ libs/data/postgres/test/research-copilot-executor.test.ts libs/data/postgres/test/research-copilot-executor-edge.test.ts` | `0` | **PROGRAMMER-REPORTED (pending)** — `999` pass, `0` fail across `59` files |
| Exit 3 Split-Boundary Fixture | `CARGO_BUILD_JOBS=2 cargo test -p curate-etl --offline split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` | `0` | **PROGRAMMER-REPORTED (pending)** — `1` passed, `0` failed |
| Utils | `bun run test:utils` | `0` | **PROGRAMMER-REPORTED (pending)** — `32` pass, `0` fail across `3` files |
| Calculations | `bun run test:calculations` | `0` | **PROGRAMMER-REPORTED (pending)** — `144` pass, `0` fail across `12` files |
- **Prior Studio unsandboxed runs (review branch `feat/m2-gap-audit`):** Studio `build` (`#1589`, `#1591`) and `test` (`#1590`, `#1592`) passed on the review branch. These runs cover separate Studio `build` and `test` commands on the review branch—not the four individual requested gates (`typecheck`, `test:contracts`, `lint:check`, `test:native`)—and do not confirm the audited `master` revision.
- **Verification status:** **PENDING** host confirmation of the exact `master` SHA, retained logs for `CARGO_BUILD_JOBS=2 bun run check`, and the separate `test/postgres/` run (see Section 4.1).
---
## 2. Verified on `master` *(Source Inspection; Traceable Runtime Verification & Host `master` SHA Pending)*
- **PRESENT · MCP Copilot Libraries, Vault-Fenced `query_data` & Snapshot Exporter.**
- `libs/research/src/mcp/copilot-server.ts` exposes all six M2 tools (`search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`).
- `createQueryDataTool` (`libs/research/src/mcp/tools/query-data.ts`) enforces strict Vault fencing: its Zod schema omits `scope` and `vault_evaluation_only` (`.strict()` rejects them with zero store calls), calls `fenceVaultQueryBounds` before any `store.universe` or `store.bars` call (clamping `to`/`asOf` strictly below `vaultCutoffTs` and rejecting ranges starting at/after `vaultCutoffTs` with `VaultHoldoutFenceError`), always passes `scope: 'vault_fenced'`, and applies defense-in-depth row filtering dropping any row where `row.ts >= vaultCutoffTs || row.knownAt >= vaultCutoffTs` (lines 203–210).
- Boundary cases in `libs/research/test/mcp-query-data.test.ts` — rejecting `scope`/`vault_evaluation_only`/unknown keys (L303), rejecting ranges starting at/after `vaultCutoffTs` with `VaultHoldoutFenceError` (L342), clamping straddling `to`/`asOf` below cutoff (L359), dropping leaky post-cutoff `ts`/`knownAt` rows (L386), clamping universe date via `min(to, asOf)` (L508), and DuckDB microsecond-bound + `adj_factors` snapshot checks (L576) — are **programmer-reported passing** in the worktree (`13` pass, `0` fail; traceable verification & host `master` SHA pending).
- `libs/research/src/mcp/adapters/postgres-copilot.ts` (`createPostgresResearchCopilotServer`) wires the read-only Studio library reader, PostgreSQL findings/caveats, trial lookup, and exchange calendars.
- `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`, T-184) and `openResearchCopilotExecutor` (`libs/data/postgres/src/research-copilot-executor.ts`, T-189/T-200) are exported and programmer-reported passing in worktree unit tests (verification pending).
- `exportNotebookSnapshot` (`libs/research/src/notebook-snapshot.ts`) and its Node/Bun adapters (`libs/research/src/notebook-snapshot-node.ts`) implement the `marimo check` → static HTML export sequence.
- **PRESENT · `tools/curate-etl` CLI Subcommands.**
- `tools/curate-etl/src/cli.rs` and `tools/curate-etl/src/main.rs` wire `curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, `curate-fx-1d`, `curate-shorts`, `curate-events`, `curate-bars-1m`, `curate-fx-1m`, `curate-posts`, `curate-fundamentals`, `curate-macro`, and `send-ilp`.
- `curate-macro` (T-194/T-202) connects `run_curate_macro` to `curate_and_write_macro`; `send-ilp` (T-190) connects `run_send_ilp` to shard discovery and one TCP connection per shard. Both are programmer-reported passing in offline native tests in the worktree (verification pending).
- **PRESENT · Exit 2 (PIT Restatement) & Exit 3 (Split-Boundary) Fixtures.**
- `tools/curate-etl/src/fundamentals.rs` builds deduplicated 2D PIT snapshots and 4-quarter TTM with venue lag provenance.
- `libs/data/duckdb/test/duckdb-market-data-store.test.ts` contains the real-DuckDB `fundamentalsAsOf` restatement fixture proving a restated Q1 (`known_at > Q2`) never overwrites Q2 (programmer-reported passing in worktree; verification pending).
- `tools/curate-etl/src/run_curate_bars_1m_tests.rs` contains `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` with the `0.5%` threshold and negative controls (programmer-reported passing in worktree; verification pending).
- **PRESENT · QuestDB `10.2.0` Primitives & TS Feature Library.**
- `docker-compose.yml`, `docker-compose.dev.yml`, and `docker-compose.prod.yml` pin `questdb/questdb:10.2.0`.
- `libs/data/questdb/src/{schema,client,query-builder,ilp-v2-writer}.ts` provide monthly WAL DDL (`M2_INTRADAY_SCHEMAS`, `getM2IntradayDDL`), parameterized PGWire (`QuestDBClient.query`), `LATEST ON`, and the ILP v2 binary batch writer.
- `libs/research/src/feature-library.ts` implements `registerSignal`, `runFeatureBatch`, and Zstd Parquet writing for versioned DuckDB SQL features.
---
## 3. Remaining M2 Code Gaps
1. **FAIL · Desktop MCP Entry Point & Exit 1 Wiring**
- T-196 target `scripts/research-copilot-mcp.ts` and root `package.json` script `mcp:research-copilot` are absent.
- `runResearchCopilotStdioHost` (`libs/research/src/mcp/host/stdio-host.ts`) still requires caller-injected store/executor factories rather than a runnable default entrypoint.
- `apps/stock/web-api/src/` has no MCP/SSE route.
- Impact: Desktop Claude Code cannot yet launch the copilot end-to-end to satisfy M2 Exit Criterion 1.
2. **FAIL · `ceoPosts` Event-Kind & Output-Root Interoperability**
- `tools/curate-etl/src/parquet_posts.rs` emits `EVENT_KIND_POST = "post"`, whereas `libs/research/src/market-data-store.ts` (`EventKind`), `libs/research/src/market-data-store-duckdb.ts` (`EVENT_KINDS`), `libs/research/src/mcp/tools/event-study.ts`, and `python/stockbot/data.py` (`EventKind`) all expect `"ceo_post"`.
- `tools/curate-etl/src/run_curate_posts.rs` writes `<out_dir>/events/year=YYYY/part.parquet` and fails closed (`RunCuratePostsError::EventsDatasetExists`) if `<out_dir>/events` already has `year=*` partitions from `curate-events`, while the copilot store takes a single curated root.
- Impact: Published `ceoPosts` cannot be queried alongside filings and earnings through the DuckDB store or MCP `event_study` as shipped.
3. **PARTIAL · Fundamentals & Macro Contract Gaps**
- `build_fundamentals_rows` (`tools/curate-etl/src/fundamentals.rs`) links filings using listing/fiscal-class plus report-date or filing-window heuristics because sampled filings lack statement period, whereas `design/DATA-CONTRACTS.md` specifies a direct period-end join.
- `run_curate_fundamentals` (`tools/curate-etl/src/run_curate_fundamentals.rs`) takes one caller-prepared financials BSON dump and requires `listing_venues.tsv`, which `exportCurateInputs` (`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts`) does not emit. No physical `fundamentals_bitemporal` writer or `eodFinancialsOLD` backfill path exists.
- `createDuckDbMarketDataStore().macroAsOf` (`libs/research/src/market-data-store-duckdb.ts:2294`) still rejects with `MarketDataStoreNotImplementedError`, so curated `teData` Parquet (`macro/part.parquet`) has no DuckDB reader.
4. **PARTIAL · Intraday Operating Path**
- `run_curate_qm_bars_1m` (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`) is implemented as a library function but has no binary subcommand dispatch in `tools/curate-etl/src/{cli,main}.rs`.
- `curate-bars-1m` and `curate-fx-1m` operate in file-mode BSON only (no `--from-mongo` streaming).
- `tools/curate-etl/src/bars_1m.rs` applies fixed Eastern session tags (venue/date overrides exist in close validation, not curation), and loaders stamp caller-supplied `--known-at-micros` whose historical availability semantics must be defined before as-of studies.
5. **FAIL / PARTIAL · QuestDB Startup Wiring & Intraday Read Path (Equity `1m` + FX `1m`)**
- **Unwired equity `1m` consumer path:** No application entry point constructs `createRoutedMarketDataStore` (`libs/research/src/market-data-store-routed.ts`) with `createQuestDbIntradayBarsReader` (`libs/research/src/market-data-store-questdb.ts`). The documented copilot factory `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`) opens DuckDB alone (`openDuckDbMarketDataStore`), which rejects `timeframe: '1m'` queries with `MarketDataStoreNotImplementedError` before reaching QuestDB.
- **Unwired FX `1m` route:** Even when `createRoutedMarketDataStore` is constructed, `fx()` delegates to the daily store rather than QuestDB `fx_1m`.
- **Startup DDL & legacy writer:** `getM2IntradayDDL` (`libs/data/questdb/src/schema.ts:139`) is opt-in with no checked-in startup caller applying it, and `QuestDBClient` (`libs/data/questdb/src/client.ts:232`) still instantiates legacy `QuestDBInfluxWriter` (`libs/data/questdb/src/influx-writer.ts`).
- **Schema wording drift:** `M2_INTRADAY_SCHEMAS.fx_1m` matches `design/DATA-CONTRACTS.md` (`DEDUP UPSERT KEYS(ts, pair)`), while `design/MILESTONES.md:96` wording can be read as `(ts, listing_id)` for both `bars_1m` and `fx_1m`.
6. **PARTIAL · Feature Library & Documentation Drift**
- `python/stockbot/__init__.py` and `python/stockbot/signals.py` do not expose `register_signal(...)` (only TS `libs/research/src/feature-library.ts` has `registerSignal`).
- `createDuckDbMarketDataStore().crossSection` (`libs/research/src/market-data-store-duckdb.ts:2283`) still rejects with `MarketDataStoreNotImplementedError`.
- `tools/curate-etl/README.md` still describes landed `curate-fundamentals` and `curate-macro` CLI wiring as deferred/follow-up in older stage sections (e.g., lines 1697, 1744, 1752, 1836, 1859).
- `AGENTS.md` and `studio.config.json` still reference `docs/` paths instead of `design/`.
- `design/MILESTONES.md:97` labels the Feature Library `D04` reopened, whereas `design/PLATFORM-PLAN.md` assigns the `register_signal` promotion bridge to `D11`.
---
## 4. Manual Host-Only Closure Gates
These checks cannot run inside the sandbox and must be executed on the host / `quant` before closing M2:
1. **Host Git Revision, Unmerged Branches, Full Check Gate & PostgreSQL Safety Suite**
- Record the exact audited `master` SHA and inspect `studio/auto-*` branches for any unmerged M2 commits (in particular T-196 desktop MCP wiring).
- Run `CARGO_BUILD_JOBS=2 bun run check` outside the sandbox on the confirmed `master` revision (covers `audit:secrets`, `build`, `typecheck`, `test:contracts`, `test:tooling`, `test:utils`, `test:calculations`, `test:integration`, `test:native`, and `lint:check`) and retain the command output/log alongside the `master` SHA.
- Because `scripts/check.ts` (`bun run check`) does **not** invoke `test:postgres` or discover `test/postgres/`, run the fixture-backed PostgreSQL safety suite separately using `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` (against isolated `stock_bot_safety*`) and record its result and log alongside `bun run check`.
- Never mutate QA MongoDB (`localhost:27017/stock`) or QA PostgreSQL (`localhost:5432/trading_bot`).
2. **Desktop Claude Code End-to-End Verification (Exit 1)**
- After runnable MCP entry-point wiring lands, connect desktop Claude Code against the read-only Studio library (`~/repos/studio/catalog/quant/library/library.yml`) and isolated PostgreSQL.
- Exercise all six MCP tools: run a PIT fundamentals + alt-data signal study and an event study, verify actual `marimo check`-clean static HTML export, and retrieve the filed finding with its trial and artifact references.
3. **Live `quant` QuestDB `10.2.0` Preflight, Load & Latency Verification (Exit 3)**
- **Host & schema precheck:** Verify on `quant`: QuestDB `10.2.0` image, `vm.max_map_count >= 1048576`, container `ulimits.nofile = 1048576`, memory limits, and pre-created `PARTITION BY MONTH` WAL tables with documented dedup keys (`(ts, listing_id)` for `bars_1m`, `(ts, pair)` for `fx_1m`).
- **Small live preflight per shard type (before bulk load):** Because `tools/curate-etl/src/cli.rs:175` documents that ILP v2 binary double encoding over TCP on QuestDB `10.2.0` is still unverified live, send one small sample shard for each shard type (`bars_1m`, `bars_1m_qm`, `fx_1m`) via `send-ilp` first. Confirm committed row counts, decoded OHLCV/FX numeric values and timestamps, and healthy WAL state (`wal_tables()`) through PGWire before starting the bulk load.
- **Full bulk load & reconciliation:** Run `send-ilp` for `bars_1m`, `bars_1m_qm`, and `fx_1m`; reconcile source counts vs. QuestDB PGWire row counts and WAL state (TCP `send-ilp` success confirms socket delivery only, not committed rows), and verify overlapping EOD/QM bar dedup and repeat-load idempotency.
- **Split-boundary verification:** Compare `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split-boundary `bars_1m` session closes against independently sourced raw `bars_1d` closes (`<= 0.5%`).
- **Read latency benchmark & explicit scope:** Benchmark a pinned 1-year single-listing `1m` read (`adjustment: 'raw'`) at **`< 250 ms` warm / `< 1 s` cold** using the real PGWire-backed reader path: `QuestDBClient.query(sql, params)` (`libs/data/questdb/src/client.ts`) injected as `QuestDbQueryExecutor` into `createQuestDbIntradayBarsReader` (`libs/research/src/market-data-store-questdb.ts`), optionally composed via `createRoutedMarketDataStore({ daily, intraday })`. Record listing ID, date range, row count, elapsed times, and cache conditions. **Scope note:** Until equity `1m` routing is wired into `openResearchCopilotStore` and the desktop MCP entrypoint (Section 3, item 5), this benchmark measures the **standalone PGWire-backed reader path**, not a running copilot application; re-verify through the running application once consumer wiring lands.

View file

@ -59,6 +59,8 @@ const STRIPPED_TIMEOUT_PARAMS: ReadonlySet<string> = new Set([
'connectiontimeoutmillis',
]);
const POSTGRES_URL_PREFIX_RE = /^postgres(?:ql)?:\/\//i;
const PORT_DIGITS_RE = /^\d+$/;
const CONTROL_CHAR_RE = /[\r\n\0]/;
/**
@ -112,13 +114,28 @@ function invalidConfigError(): ResearchCopilotExecutorError {
return new ResearchCopilotExecutorError('INVALID_CONFIG', ERROR_MESSAGES.INVALID_CONFIG);
}
function assertValidPort(rawPort: string): void {
if (!PORT_DIGITS_RE.test(rawPort)) {
throw invalidConfigError();
}
const portNum = Number(rawPort);
if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
throw invalidConfigError();
}
}
function parseAndNormalizePoolConfig(config: ResearchCopilotExecutorConfig): PoolConfig {
if (typeof config !== 'object' || config === null || typeof config.postgresUrl !== 'string') {
throw invalidConfigError();
}
const rawUrl = config.postgresUrl;
if (rawUrl.length === 0 || rawUrl !== rawUrl.trim() || CONTROL_CHAR_RE.test(rawUrl)) {
if (
rawUrl.length === 0 ||
rawUrl !== rawUrl.trim() ||
CONTROL_CHAR_RE.test(rawUrl) ||
!POSTGRES_URL_PREFIX_RE.test(rawUrl)
) {
throw invalidConfigError();
}
@ -160,10 +177,15 @@ function parseAndNormalizePoolConfig(config: ResearchCopilotExecutorConfig): Poo
}
if (parsed.port.length > 0) {
const portNum = Number(parsed.port);
if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) {
throw invalidConfigError();
}
assertValidPort(parsed.port);
}
const portQueryParams = parsed.searchParams.getAll('port');
if (portQueryParams.length > 1) {
throw invalidConfigError();
}
if (portQueryParams.length === 1) {
assertValidPort((portQueryParams[0] as string).trim());
}
if (!parsed.pathname.startsWith('/') || parsed.pathname.length <= 1) {

View file

@ -62,6 +62,9 @@ function assertNoSecretsLeaked(error: unknown): void {
expect(error).toBeInstanceOf(ResearchCopilotExecutorError);
const typed = error as ResearchCopilotExecutorError;
expect((typed as { cause?: unknown }).cause).toBeUndefined();
expect('cause' in typed).toBe(false);
expect('detail' in typed).toBe(false);
expect('extraDiag' in typed).toBe(false);
const message = typed.message;
for (const needle of [
VALID_URL,
@ -162,13 +165,21 @@ describe('openResearchCopilotExecutor', () => {
'not-a-url',
`http://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`,
`mysql://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:3306/research_db`,
'postgres:/research_db?host=%2Ftmp',
'postgresql:/research_db?host=%2Ftmp',
'postgres:///research_db',
'postgres:///research_db?host=',
'postgres:///research_db?host=%20%20',
'postgres:///research_db?host=/var/run/postgresql&host=/tmp',
'postgres:///research_db?HOST=/var/run/postgresql',
'postgres://copilot@db.example/?dbname=research',
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=/a&host=/b`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=0`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=70000`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=abc`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=5432&port=5433`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/`,
`postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%20%20`,
@ -288,8 +299,9 @@ describe('openResearchCopilotExecutor', () => {
await handle.close();
});
test('preserves SQLSTATE 23505 on sanitized unique-violation query errors', async () => {
test('preserves SQLSTATE 23505 on sanitized unique-violation query errors without leaking cause or driver fields', async () => {
let callCount = 0;
const rawCause = new Error(`nested pgpass secret ${SECRET_PASS}`);
const fake = createFakePool({
async onQuery() {
callCount += 1;
@ -297,8 +309,14 @@ describe('openResearchCopilotExecutor', () => {
return { rows: [{ '?column?': 1 }] };
}
const pgErr = Object.assign(
new Error(`duplicate key value violates unique constraint on ${SECRET_HOST} raw-pg-secret`),
{ code: '23505', detail: `Key (id)=(dup-1) already exists (${SECRET_PASS})` }
new Error(`duplicate key value violates unique constraint on ${SECRET_HOST} raw-pg-secret`, {
cause: rawCause,
}),
{
code: '23505',
detail: `Key (id)=(dup-1) already exists (${SECRET_PASS})`,
extraDiag: 'sensitive-driver-field',
}
);
throw pgErr;
},
@ -321,8 +339,9 @@ describe('openResearchCopilotExecutor', () => {
await handle.close();
});
test('sanitizes generic query errors to QUERY_FAILED with no cause or raw text', async () => {
test('sanitizes generic query errors to QUERY_FAILED with no cause, extra fields, or raw text', async () => {
let callCount = 0;
const rawCause = new Error(`nested env PGPASSWORD=${SECRET_PASS}`);
const fake = createFakePool({
async onQuery() {
callCount += 1;
@ -330,8 +349,10 @@ describe('openResearchCopilotExecutor', () => {
return { rows: [{ '?column?': 1 }] };
}
throw Object.assign(
new Error(`relation "missing" does not exist on ${VALID_URL} raw-pg-secret`),
{ code: '42P01' }
new Error(`relation "missing" does not exist on ${VALID_URL} raw-pg-secret`, {
cause: rawCause,
}),
{ code: '42P01', detail: 'driver-detail', extraDiag: 'sensitive-driver-field' }
);
},
});

View file

@ -0,0 +1,101 @@
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'bun:test';
// Guards the T-203 M2 gap audit (design/m2-gap-audit.md) against citation rot:
// every repo path it cites must resolve, and every symbol it reports as
// "present" must still live in the file it names. Gaps the audit reports as
// missing are deliberately NOT asserted, so landing a fix never breaks this test.
const repoRoot = fileURLToPath(new URL('../../', import.meta.url));
const auditPath = join(repoRoot, 'design/m2-gap-audit.md');
const audit = readFileSync(auditPath, 'utf8');
// Paths the audit cites as absent (the gap itself) or as the wrong location.
const CITED_AS_ABSENT = new Set(['scripts/research-copilot-mcp.ts', 'docs/']);
function expandBraces(path: string): string[] {
const match = /^(.*)\{([^}]+)\}(.*)$/.exec(path);
if (!match) return [path];
const [, prefix, options, suffix] = match;
return options!.split(',').flatMap((option) => expandBraces(`${prefix}${option}${suffix}`));
}
function citedRepoPaths(markdown: string): string[] {
const spans = [...markdown.matchAll(/`([^`\s]+)`/g)].map((m) => m[1]!);
const pathLike = spans.filter(
(span) =>
/^(apps|libs|tools|python|scripts|design|test|docs)\//.test(span) ||
/^[A-Za-z0-9_.-]+\.(md|json|yml)$/.test(span)
);
return [...new Set(pathLike.map((span) => span.replace(/:\d+$/, '')).flatMap(expandBraces))].sort();
}
describe('design/m2-gap-audit.md citations', () => {
test('cites only repo paths that exist, except those it reports as absent', () => {
const cited = citedRepoPaths(audit);
expect(cited.length).toBeGreaterThan(30);
const missing = cited.filter((p) => !CITED_AS_ABSENT.has(p) && !existsSync(join(repoRoot, p)));
expect(missing).toEqual([]);
});
test('every path listed as absent is actually absent in the audited checkout or is the docs/ relocation note', () => {
// docs/ is cited because milestone docs moved to design/; it must stay absent for that note to hold.
expect(existsSync(join(repoRoot, 'docs'))).toBe(false);
expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true);
});
// Symbols the audit reports as PRESENT, keyed by the file it attributes them to.
const presentSymbols: Array<[file: string, symbol: string | RegExp]> = [
['libs/research/src/mcp/tools/query-data.ts', 'createQueryDataTool'],
['libs/research/src/mcp/tools/query-data.ts', 'fenceVaultQueryBounds'],
['libs/research/src/mcp/tools/query-data.ts', "'vault_fenced'"],
['libs/research/src/mcp/adapters/postgres-copilot.ts', 'createPostgresResearchCopilotServer'],
['libs/data/duckdb/src/research-copilot-store.ts', 'openResearchCopilotStore'],
['libs/data/postgres/src/research-copilot-executor.ts', 'openResearchCopilotExecutor'],
['libs/research/src/notebook-snapshot.ts', 'exportNotebookSnapshot'],
['libs/research/src/mcp/host/stdio-host.ts', 'runResearchCopilotStdioHost'],
['libs/research/src/feature-library.ts', 'registerSignal'],
['libs/research/src/feature-library.ts', 'runFeatureBatch'],
['libs/data/questdb/src/schema.ts', 'M2_INTRADAY_SCHEMAS'],
['libs/data/questdb/src/schema.ts', 'getM2IntradayDDL'],
['libs/research/src/market-data-store-routed.ts', 'createRoutedMarketDataStore'],
['libs/research/src/market-data-store-questdb.ts', 'createQuestDbIntradayBarsReader'],
['tools/curate-etl/src/cli.rs', 'CurateMacro('],
['tools/curate-etl/src/cli.rs', 'SendIlp('],
['tools/curate-etl/src/cli.rs', 'CuratePosts('],
['tools/curate-etl/src/cli.rs', 'CurateFundamentals('],
['tools/curate-etl/src/cli.rs', 'CurateBars1m('],
['tools/curate-etl/src/cli.rs', 'CurateFx1m('],
['tools/curate-etl/src/run_curate_bars_1m_tests.rs', 'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes'],
['tools/curate-etl/src/run_curate_posts.rs', 'EventsDatasetExists'],
['tools/curate-etl/src/run_curate_qm_bars_1m.rs', /pub fn run_curate_qm_bars_1m\b/],
['tools/curate-etl/src/fundamentals.rs', 'build_fundamentals_rows'],
];
test.each(presentSymbols)('%s defines %p as the audit reports', (file, symbol) => {
const source = readFileSync(join(repoRoot, file), 'utf8');
if (typeof symbol === 'string') expect(source).toContain(symbol);
else expect(source).toMatch(symbol);
});
test('pins QuestDB 10.2.0 in every compose file the audit cites', () => {
for (const file of ['docker-compose.yml', 'docker-compose.dev.yml', 'docker-compose.prod.yml']) {
expect(readFileSync(join(repoRoot, file), 'utf8')).toContain('questdb/questdb:10.2.0');
}
});
test('lists the three closure-checklist sections the task requires', () => {
expect(audit).toMatch(/^## 2\. Verified on `master`/m);
expect(audit).toMatch(/^## 3\. Remaining M2 Code Gaps/m);
expect(audit).toMatch(/^## 4\. Manual Host-Only Closure Gates/m);
});
test('keeps master verification pending rather than claiming unverified passes', () => {
expect(audit).toContain('**OPEN');
expect(audit).toMatch(/PENDING/);
expect(audit).not.toMatch(/\|\s*\*\*PASS\*\*\s*\|/);
});
});

View file

@ -271,7 +271,7 @@ describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () =>
expect(listed[0]?.id).toBe('finding-pgoptions-0001');
});
test('supports migrated findings writes, reads, and idempotent same-ID 23505 replay', async () => {
test('supports migrated findings writes, reads, idempotent replay, and real 23505 preservation', async () => {
const f = await createIsolatedFixture();
const appName = `copilot_findings_${randomUUID().slice(0, 8)}`;
const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName);
@ -306,7 +306,7 @@ describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () =>
createdAt: FIXED_TS,
});
// Same ID + same idempotency key collides on PK (23505) and must replay cleanly.
// Same-ID, same-key replay must return the original finding and timestamp.
const replay = await writePort.appendFinding(record, 'idem-key-0001');
expect(replay).toEqual({
status: 'replayed',
@ -314,6 +314,19 @@ describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () =>
createdAt: FIXED_TS,
});
// Unkeyed duplicate-PK insert hits PostgreSQL's primary-key constraint directly;
// verify the executor preserves SQLSTATE 23505 without leaking driver fields.
let pkCollisionErr: unknown;
try {
await writePort.appendFinding(record);
} catch (err) {
pkCollisionErr = err;
}
expect(pkCollisionErr).toBeInstanceOf(ResearchCopilotExecutorError);
expect((pkCollisionErr as ResearchCopilotExecutorError).code).toBe('23505');
expect('cause' in (pkCollisionErr as object)).toBe(false);
expect('detail' in (pkCollisionErr as object)).toBe(false);
const listed = await readers.listFindings({ query: 'Executor integration' });
expect(listed).toHaveLength(1);
expect(listed[0]?.id).toBe('finding-exec-0001');

View file

@ -0,0 +1,175 @@
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'bun:test';
// Guards the T-204 M2 completion audit (design/m2-completion-audit.md) against
// citation rot: every repo path it cites must resolve, every symbol it reports as
// landed must still live in the file it names, and the report must keep host-only
// verification marked pending. Gaps the audit reports as missing are deliberately
// NOT asserted, so landing an M2 fix never breaks this test.
const repoRoot = fileURLToPath(new URL('../../', import.meta.url));
const audit = readFileSync(join(repoRoot, 'design/m2-completion-audit.md'), 'utf8');
const designIndex = readFileSync(join(repoRoot, 'design/README.md'), 'utf8');
// Cited as the gap itself (absent today), as already-retired code, as a sandbox env
// note, or as the stale pre-rename docs/ location.
const CITED_AS_ABSENT = new Set([
'scripts/research-copilot-mcp.ts',
'apps/stock/analytics',
'python/.venv',
'docs',
'docs/',
'docs/*.md',
]);
function expandBraces(path: string): string[] {
const match = /^(.*)\{([^}]+)\}(.*)$/.exec(path);
if (!match) {return [path];}
const [, prefix, options, suffix] = match;
return options!.split(',').flatMap((option) => expandBraces(`${prefix}${option}${suffix}`));
}
function citedRepoPaths(markdown: string): string[] {
const spans = [...markdown.matchAll(/`([^`\s]+)`/g)].map((m) => m[1]!);
const pathLike = spans.filter(
(span) =>
/^(apps|libs|tools|python|scripts|design|test|database|docs)\//.test(span) ||
/^[A-Za-z0-9_.-]+\.(md|json|yml)$/.test(span)
);
return [
...new Set(
pathLike
// Strip `:line`, `:a-b`, and `:a-b,c` suffixes and trailing globs.
.map((span) => span.replace(/:[\d,-]+$/, '').replace(/\/\*$/, ''))
.flatMap(expandBraces)
),
].sort();
}
describe('design/m2-completion-audit.md citations', () => {
test('cites only repo paths that exist, except those it reports as absent', () => {
const cited = citedRepoPaths(audit);
expect(cited.length).toBeGreaterThan(40);
const missing = cited.filter((p) => !CITED_AS_ABSENT.has(p) && !existsSync(join(repoRoot, p)));
expect(missing).toEqual([]);
});
test('docs/ stays absent so the documentation path-drift note holds', () => {
expect(existsSync(join(repoRoot, 'docs'))).toBe(false);
expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true);
});
// Symbols the audit reports as LANDED, keyed by the file it attributes them to.
const landedSymbols: Array<[file: string, symbol: string | RegExp]> = [
['libs/research/src/mcp/copilot-server.ts', 'createResearchCopilotMcpServer'],
['libs/research/src/mcp/host/stdio-host.ts', 'runResearchCopilotStdioHost'],
['libs/data/postgres/src/research-copilot-executor.ts', 'openResearchCopilotExecutor'],
['libs/data/duckdb/src/research-copilot-store.ts', 'openResearchCopilotStore'],
['libs/data/duckdb/src/research-copilot-store.ts', 'vaultOperatorAuthorized: false'],
['libs/research/src/mcp/tools/query-data.ts', 'createQueryDataTool'],
['libs/research/src/notebook-snapshot.ts', 'exportNotebookSnapshot'],
['libs/research/src/notebook-snapshot-node.ts', 'exportNotebookSnapshot'],
['libs/research/src/market-data-store-duckdb.ts', 'fundamentalsAsOf'],
['libs/research/src/market-data-store-routed.ts', 'createRoutedMarketDataStore'],
['libs/research/src/market-data-store-questdb.ts', 'createQuestDbIntradayBarsReader'],
['libs/research/src/feature-library.ts', 'registerSignal'],
['libs/research/src/feature-library.ts', 'runFeatureBatch'],
['libs/research/src/feature-library.ts', 'export const RET_1D_V1'],
['libs/research/src/feature-library.ts', 'export const FEATURE_INPUT_DATASETS'],
['libs/data/questdb/src/schema.ts', 'M2_INTRADAY_SCHEMAS'],
['libs/data/questdb/src/schema.ts', 'getM2IntradayDDL'],
// The schema is declarative; DDL keywords are rendered from these fields.
['libs/data/questdb/src/schema.ts', "capacity: 65536, cache: false"],
['libs/data/questdb/src/schema.ts', "partitionBy: 'MONTH'"],
['libs/data/questdb/src/schema.ts', 'dedupUpsertKeys'],
['tools/curate-etl/src/cli.rs', 'SendIlp('],
['tools/curate-etl/src/cli.rs', 'CurateFundamentals('],
['tools/curate-etl/src/cli.rs', 'CuratePosts('],
['tools/curate-etl/src/cli.rs', 'CurateMacro('],
['tools/curate-etl/src/cli.rs', 'CurateBars1m('],
['tools/curate-etl/src/cli.rs', 'CurateFx1m('],
['tools/curate-etl/src/main.rs', 'run_send_ilp('],
['tools/curate-etl/src/mongo_stream.rs', 'pub enum SourceCollection'],
['tools/curate-etl/src/run_curate_posts.rs', 'EventsDatasetExists'],
['tools/curate-etl/src/run_curate_qm_bars_1m.rs', /pub fn run_curate_qm_bars_1m\b/],
['tools/curate-etl/src/ilp_send_tests.rs', 'fn tcp_sends_separate_shards_and_half_closes'],
[
'tools/curate-etl/src/fundamentals_tests.rs',
'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2',
],
[
'tools/curate-etl/src/run_curate_bars_1m_tests.rs',
'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes',
],
['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 'restatement non-overwrite'],
['docker-compose.quant.yml', 'hard: 1048576'],
['docker-compose.quant.yml', 'QDB_RAM_USAGE_LIMIT_BYTES=21474836480'],
['database/postgres/init/37-research-findings.sql', 'provider_caveats'],
['database/postgres/init/36-trial-ledger.sql', 'vault_evaluations'],
];
test.each(landedSymbols)('%s contains %p as the audit reports', (file, symbol) => {
const source = readFileSync(join(repoRoot, file), 'utf8');
if (typeof symbol === 'string') {expect(source).toContain(symbol);}
else {expect(source).toMatch(symbol);}
});
test('every MCP tool the audit counts is registered in the copilot server', () => {
const server = readFileSync(join(repoRoot, 'libs/research/src/mcp/copilot-server.ts'), 'utf8');
const tools = ['search_symbols', 'query_data', 'analyze_signal', 'event_study', 'file_finding', 'read_knowledge'];
for (const tool of tools) {expect(server).toContain(`'${tool}'`);}
expect(audit).toContain('6 MCP tools');
});
test('the synthetic split fixture still documents the observed-data comparison as open', () => {
// The audit's EC-3 "synthetic only" status rests on this scope note.
const fixture = readFileSync(join(repoRoot, 'tools/curate-etl/src/run_curate_bars_1m_tests.rs'), 'utf8');
expect(fixture).toMatch(/Does NOT prove .* against retained `bars_1d` data/);
expect(audit).toMatch(/OPEN \(Synthetic Only\)/);
});
});
describe('design/m2-completion-audit.md structure and honesty', () => {
test('holds M3 and covers every section the task requires', () => {
expect(audit).toMatch(/HOLD M3/);
expect(audit).toMatch(/^## 1\. Verification Gate Results/m);
expect(audit).toMatch(/^## 2\. M2 Deliverables & Exit Criteria Matrix/m);
expect(audit).toMatch(/^## 3\. Candidate Causes/m);
expect(audit).toMatch(/^## 4\. Concrete Blockers Needing Director Decisions/m);
expect(audit).toMatch(/^## 5\. M3 Readiness Mapping/m);
});
test('covers all four M2 deliverables and all three M2 exit criteria', () => {
for (const area of ['M2.1', 'M2.2', 'M2.3', 'M2.4']) {expect(audit).toContain(`**${area}**`);}
for (const ec of ['EC-1', 'EC-2', 'EC-3']) {expect(audit).toContain(`**${ec}:**`);}
for (const ec of ['M3 EC-1', 'M3 EC-2', 'M3 EC-3']) {expect(audit).toContain(`**${ec}:**`);}
});
test('keeps host-only verification pending and parking causes unattributed', () => {
expect(audit).toMatch(/\|\s*\*\*PENDING\*\*\s*\|/);
expect(audit).toContain('none of the four items below can be attributed to a specific parked task');
expect(audit).not.toMatch(/EC-3[^|]*\|\s*\*\*SATISFIED/);
});
test('asks the director three decisions, each with a recommendation', () => {
const decisions = audit.split(/^## 4\./m)[1]!.split(/^## 5\./m)[0]!;
expect(decisions.match(/^\d\. \*\*/gm)?.length).toBe(3);
expect(decisions.match(/\*Recommended:\*/g)?.length).toBe(3);
});
test('carries the teData regime-filter-only limit into macro follow-ups', () => {
expect(audit).toContain('design/DATA-CONTRACTS.md:26');
expect(readFileSync(join(repoRoot, 'design/DATA-CONTRACTS.md'), 'utf8').split('\n')[25]).toContain(
'final-revised values only'
);
});
test('is indexed exactly once in design/README.md', () => {
const rows = designIndex.split('\n').filter((line) => line.includes('(m2-completion-audit.md)'));
expect(rows).toHaveLength(1);
expect(rows[0]).toMatch(/^\| \*\*\[m2-completion-audit\.md\]\(m2-completion-audit\.md\)\*\* \|.*\|.*\|$/);
});
});

View file

@ -1571,6 +1571,59 @@ Inputs, defaults, and output rules:
Both `--flag value` and `--flag=value` forms are accepted. Missing required flags, invalid `--timestamp-unit`, duplicate flags, unknown flags (including `--from-mongo`), positional arguments, blank field names or `--mapping-source`, and colliding field-name roles (checked after applying defaults) exit non-zero with usage on stderr.
## `curate-fundamentals` Command (`M2.2r`)
End-to-end file-to-Parquet CLI command (`src/run_curate_fundamentals.rs`, wired in `src/cli.rs` and `src/main.rs`) streaming concatenated raw BSON `qmFinancials` and `qmFilings` dumps alongside `provider_mapping.tsv` and `listing_venues.tsv` into atomically published `<out>/fundamentals_pit/year=YYYY/part.parquet` partitions with zero extra crates and no database connections (**file mode only** — `--from-mongo` and `--mongo-uri*` are not supported and are rejected as unknown flags).
### Invocation
```bash
curate-etl curate-fundamentals \
--qm-financials qmFinancials.bson \
--qm-filings qmFilings.bson \
--provider-mapping provider_mapping.tsv \
--listing-venues listing_venues.tsv \
--out ./out \
--currency-field currency \
--filings-form-type-field formType \
--k 4 \
--quarterly-tokens Q1,Q2,Q3,Q4 \
--annual-tokens FY \
--revenue-field IncomeStatement.revenue \
--net-income-field IncomeStatement.netIncome \
--operating-cash-flow-field CashFlow.operatingCashFlow \
--total-assets-field BalanceSheet.totalAssets \
--total-equity-field BalanceSheet.totalEquity \
--shares-outstanding-field BalanceSheet.sharesOutstanding
```
Inputs, explicit configuration, defaults, and output rules:
- **Required flags (no defaults, because live `qmFinancials`/`qmFilings` field names and token strings are unverified in the repository):**
- `--qm-financials <path>`: concatenated raw BSON (`mongodump` `qmFinancials.bson`).
- `--qm-filings <path>`: concatenated raw BSON (`mongodump` `qmFilings.bson`).
- `--provider-mapping <path>`: headerless 5-column TSV (`source<TAB>provider_key<TAB>effective_from<TAB>effective_to<TAB>listing_id`, same format as `curate-bars-1d`).
- `--listing-venues <path>`: headerless 2-column TSV (`listing_id<TAB>venue`, where `listing_id` is a strictly positive ASCII integer and `venue` is exact `us_tsx` or `tsxv_cse`).
- `--out <dir>`: dataset root where `<out>/fundamentals_pit/year=YYYY/part.parquet` is atomically published.
- `--currency-field <name>`: dotted BSON path to the reporting currency in `qmFinancials`.
- `--filings-form-type-field <name>`: BSON field name for periodic filing form type in `qmFilings`.
- `--k <N>`: strict positive integer (`>= 1`) snapshot period limit.
- **Fiscal-period mode (mutually exclusive; supply exactly one mode):**
- `--fiscal-period <quarterly|annual>` to assign a fixed period to every decoded document, **or**
- `--quarterly-tokens <a,b,..>` and/or `--annual-tokens <a,b,..>` (comma-separated exact tokens preserving spelling and whitespace; empty/blank or overlapping tokens fail closed).
- **Optional flags with verified defaults:**
- `--financials-key-field` (default `qmSearchCode`)
- `--period-end-field` (default `periodEndDate`)
- `--report-date-field` (default `reportDate`)
- `--report-period-field` (default `reportPeriod`)
- `--filings-key-field` (default `symbol`)
- `--filings-timefiled-field` (default `timefiled`)
- `--mapping-source` (default `qm`)
- **Optional flags defaulting to `None` (unconfigured metrics emit `NULL` in Parquet):**
- `--revenue-field <path>`, `--net-income-field <path>`, `--operating-cash-flow-field <path>`, `--total-assets-field <path>`, `--total-equity-field <path>`, `--shares-outstanding-field <path>`
- `--filings-filing-id-field <name>`, `--filings-url-field <name>`
Both `--flag value` and `--flag=value` forms are accepted. Missing required flags, combining or omitting fiscal-period modes, invalid `--k` (`0`, signs, non-digits, overflow), duplicate flags, unknown flags (including `--from-mongo` and `--mongo-uri*`), positional arguments, malformed dotted paths, overlapping `qmFilings` field names, or blank/overlapping fiscal tokens fail closed before touching `--out`, exiting non-zero with a single-line diagnostic error and usage on stderr. On success, stdout prints `format_curate_fundamentals_report`.
## 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.
@ -1780,7 +1833,7 @@ curate-etl send-ilp \
- **Governance & provenance:** Quant Research owns the coarse regime-use policy; the caller owns the explicit `(country_iso, indicator)` lag mapping. TradingEconomics indicator names are **not** hardcoded because live `teIndicators` / `teData` names are unverified in this crate. Because `teData` carries final-revised `{d, v}` values without verified release dates or historical vintages, availability starts strictly at `known_at` (`00:00:00 UTC` of `period_date + lag_days`), tagged `known_at_source = "publication_lag_estimate"` (`MACRO_KNOWN_AT_SOURCE`).
- **Locked lag classes (`MacroLagClass`):** `PolicyRate` (`+1d`, `POLICY_RATE_LAG_DAYS`), `MonthlyRelease` (`+35d`, `MONTHLY_RELEASE_LAG_DAYS`), `Gdp65` (`+65d`, `GDP65_LAG_DAYS`), and `Gdp90` (`+90d`, `GDP90_LAG_DAYS`).
- **Fail-closed filtering, deduplication & overflow:** Unmapped `(country_iso, indicator)` pairs are skipped first (`skipped_unmapped_indicator`) and never given a default lag; non-finite values on mapped pairs are skipped (`skipped_non_finite_value`). Surviving rows are sorted by `(country_iso, indicator, period_date)`; bitwise-identical (`f64::to_bits()`) duplicates collapse (`skipped_duplicate`), while conflicting values (including `+0.0` vs. `-0.0`) return `MacroError::ConflictingDuplicate`. Checked `i32` date addition and `i64` microsecond scaling return `MacroError::KnownAtOverflow` rather than panicking. `MacroBuildStats` satisfies `input == emitted + skipped_unmapped_indicator + skipped_non_finite_value + skipped_duplicate`.
- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow<K>>`) atomically to `<out_dir>/macro/part.parquet` (6-column Zstd contract schema); deferred: file-to-file runner, CLI command, `macroAsOf` DuckDB reader, and live MongoDB access.
- **Parquet writer (`M2.2o`) & deferred items:** `write_macro_dataset` (`src/parquet_macro.rs`, tested in `src/parquet_macro_tests.rs`) writes `MacroParquetRow` (via `From<&MacroRow<K>>`) atomically to `<out_dir>/macro/part.parquet` (6-column Zstd contract schema); deferred: `macroAsOf` DuckDB reader and live MongoDB access.
## Zero-Copy `teData` BSON Decoder (`M2.2p`)
@ -1796,3 +1849,26 @@ curate-etl send-ilp \
- **Explicit caller-supplied series map:** Maps verbatim `(te_symbol, country, category)` triples to `Option<MacroSeriesTarget { country_iso, indicator, lag_class }>`; unmapped points are dropped into `dropped_unmapped_series` with no default lag, and conflicting lag classes targeting the same `(country_iso, indicator)` fail closed with `CurateMacroError::ConflictingLagClass` independent of input order before writing.
- **Delegated builder & atomic publish:** Delegates filtering, sorting, deduplication, and `known_at` calculation unchanged to `build_macro_rows`, emits strictly ascending unique `MacroParquetRow`s with reconciling `CurateMacroStats` (`points_in == dropped_unmapped_series + builder.input`, `rows_out == builder.emitted`), and leaves `<out_dir>/macro/part.parquet` untouched on empty/all-unmapped input or any curation error.
## `run_curate_macro` File-to-File Runner (`M2.2s`)
`run_curate_macro` and `run_curate_macro_with_readers` (`src/run_curate_macro.rs`, tested in `src/run_curate_macro_tests.rs`) connect a concatenated length-prefixed raw BSON `teData` dump (`te_data`) and a caller-supplied series-map TSV (`series_map`) through `decode_te_data_buffer` and `curate_and_write_macro` into `<out_dir>/macro/part.parquet`:
- **Caller-owned series-map TSV (`load_macro_series_map_tsv`):** Requires the exact line-1 header `te_symbol<TAB>country<TAB>category<TAB>country_iso<TAB>indicator<TAB>lag_class` (LF or CRLF line endings). Each data row must have 6 nonempty tab-separated columns with verbatim `(te_symbol, country, category)` keys (no trimming, no case folding), unique key triples (duplicates fail closed even when targets match), and an exact `lag_class` token in `policy_rate`, `monthly_release`, `gdp65`, or `gdp90`. There is no hardcoded default mapping or default lag class.
- **Buffering, decode & fail-closed behavior:** Validates the full series map first, buffers the concatenated `teData` BSON input in memory (memory grows with dump size), counts per-document/per-point semantic rejects in `BsonTeDataDecodeStats`, and fails closed on the first structural BSON error (`TruncatedDocument`, `CorruptDocumentLength`, `CorruptBson`, `CorruptPointBson`) before publishing. Any I/O, TSV, structural BSON, or curation error (such as `ConflictingLagClass`) returns a single-line `RunCurateMacroError` and leaves `out_dir` and any pre-existing `<out_dir>/macro/part.parquet` byte-identical. Empty or all-unmapped inputs preserve `curate_and_write_macro`'s zero-row no-op.
- **Governance, provenance & reproducibility:** Quant Research owns the coarse regime-use policy and the caller owns the mapping. Because `teData` carries final-revised `{d, v}` values without verified release timestamps or historical vintages, observations become available strictly at the estimated `known_at` (`00:00:00 UTC` of `period_date + lag_days`, `known_at_source = "publication_lag_estimate"`) for coarse regime use. For reproducible checks, pin the `teData` BSON dump and series-map TSV together against the pure stage and fixed expected rows. Real QA `teData` provider-label verification remains a manual host check, and `--from-mongo` streaming remains a separate follow-up.
## `curate-macro` Command (`M2.2t`)
File-mode CLI command wiring `run_curate_macro` into the `curate-etl` binary to curate a local `teData` raw BSON dump and caller-supplied series-map TSV into `<out>/macro/part.parquet`:
```bash
curate-etl curate-macro \
--te-data ./teData.bson \
--series-map ./series-map.tsv \
--out ./out
```
- **Required flags (no defaults):** `--te-data <teData.bson>`, `--series-map <series-map.tsv>`, and `--out <dir>` are all required (accepting both `--flag value` and `--flag=value`). Duplicate flags, empty values, positional arguments, and unknown flags (including `--from-mongo` and `--mongo-uri*`) are rejected at parse time before touching `--out`.
- **Series-map TSV & lag tokens:** `--series-map` must start with the exact 6-column header `te_symbol<TAB>country<TAB>category<TAB>country_iso<TAB>indicator<TAB>lag_class` with verbatim keys and `lag_class` in `{policy_rate, monthly_release, gdp65, gdp90}`; no country, indicator, or lag-class defaults are built in.
- **Output, fail-closed & zero-row behavior:** Prints `format_curate_macro_report` to stdout on exit `0` and atomically publishes `<out>/macro/part.parquet` (empty or all-unmapped inputs succeed as a zero-row no-op without writing). Runtime errors (missing input, invalid TSV, structural BSON corruption, or curation error) print a single-line `error: ...` to stderr and exit non-zero without creating `--out` or modifying any pre-existing `<out>/macro/part.parquet`; CLI parse errors print `error: ...` followed by `Usage:` to stderr and exit non-zero.

File diff suppressed because it is too large Load diff

View file

@ -388,6 +388,13 @@ pub use run_curate_fundamentals::{
CurateFundamentalsRunReport, RunCurateFundamentalsError, DEFAULT_FUNDAMENTALS_MAPPING_SOURCE,
};
pub mod run_curate_macro;
pub use run_curate_macro::{
format_curate_macro_report, load_macro_series_map_tsv, run_curate_macro,
run_curate_macro_with_readers, CurateMacroArgs, CurateMacroRunReport, MacroSeriesMap,
RunCurateMacroError, MACRO_SERIES_MAP_HEADER,
};
pub mod run_curate_shorts;
pub use run_curate_shorts::{
format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader,

View file

@ -29,8 +29,12 @@ use curate_etl::run_curate_corporate_actions::{
format_curate_corporate_actions_report, run_curate_corporate_actions,
};
use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events};
use curate_etl::run_curate_fundamentals::{
format_curate_fundamentals_report, run_curate_fundamentals,
};
use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d};
use curate_etl::run_curate_fx_1m::{format_curate_fx_1m_report, run_curate_fx_1m};
use curate_etl::run_curate_macro::{format_curate_macro_report, run_curate_macro};
use curate_etl::run_curate_posts::{format_curate_posts_report, run_curate_posts};
use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts};
use curate_etl::run_mongo::{
@ -231,6 +235,28 @@ fn main() -> ExitCode {
ExitCode::FAILURE
}
},
Ok(CliAction::CurateFundamentals(curate_args)) => {
match run_curate_fundamentals(&curate_args) {
Ok(report) => {
println!("{}", format_curate_fundamentals_report(&report));
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("error: {err}");
ExitCode::FAILURE
}
}
}
Ok(CliAction::CurateMacro(curate_args)) => match run_curate_macro(&curate_args) {
Ok(report) => {
println!("{}", format_curate_macro_report(&report));
ExitCode::SUCCESS
}
Err(err) => {
eprintln!("error: {err}");
ExitCode::FAILURE
}
},
Ok(CliAction::SendIlp(send_args)) => match run_send_ilp(&send_args) {
Ok(report) => {
println!("{}", format_ilp_send_report(&report));

View file

@ -0,0 +1,657 @@
//! File-to-file `curate-macro` runner (`M2.2s`).
//!
//! Reads a concatenated length-prefixed raw BSON `teData` dump and a caller-supplied
//! series-map TSV into an atomically published `<out_dir>/macro/part.parquet` dataset via
//! [`curate_and_write_macro`].
//!
//! # Governance & Series-Map Contract
//! - **Caller-owned mapping (no defaults):** Every row in the series-map TSV maps a verbatim
//! `(te_symbol, country, category)` triple (no trimming, no case folding) to a
//! [`MacroSeriesTarget`] (`country_iso`, `indicator`, `lag_class`). No country-to-ISO,
//! indicator-name, or lag-class mapping is hardcoded here because live `teData` labels are
//! unverified and Quant Research owns the coarse regime-use policy.
//! - **Strict TSV format (`load_macro_series_map_tsv`):**
//! - Required exact line-1 header:
//! `te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class`
//! - LF (`\n`) and CRLF (`\r\n`) line endings are accepted; bare/embedded `\r` and invalid UTF-8
//! fail closed with the 1-based physical line number.
//! - Every data row must have exactly 6 nonempty tab-separated fields, verbatim keys, an exact
//! `lag_class` token in `{policy_rate, monthly_release, gdp65, gdp90}`, and unique
//! `(te_symbol, country, category)` triples (duplicates fail closed even when targets match).
//!
//! # Decode, Buffering & Fail-Closed Policy
//! - **Series-map validation first:** The entire series map is parsed and validated before any
//! `teData` bytes are decoded or `out_dir` is touched.
//! - **In-memory file-mode buffering:** `run_curate_macro_with_readers` buffers the concatenated
//! `teData` BSON input and collects borrowed [`TeDataPoint`] views from
//! [`decode_te_data_buffer`] before calling [`curate_and_write_macro`], so memory usage grows
//! with input size.
//! - **Decode error policy (matching `run_curate_fx.rs`):** Per-document and per-point semantic
//! rejects (missing/empty/wrong-type `teSymbol`, `country`, `category`, `data`, non-document
//! points, invalid point dates/values) are counted in [`BsonTeDataDecodeStats`] and skipped so
//! valid points continue. Structural BSON framing or element corruption
//! ([`BsonTeDataError::TruncatedDocument`], [`BsonTeDataError::CorruptDocumentLength`],
//! [`BsonTeDataError::CorruptBson`], [`BsonTeDataError::CorruptPointBson`]) is captured on the
//! first occurrence and returned as [`RunCurateMacroError::CorruptTeDataBson`] before publishing,
//! preventing partial datasets from a truncated or corrupt tail.
//! - **Atomic publish & zero-row preservation:** Any series-map, I/O, structural BSON, or curation
//! error (such as [`crate::curate_macro::CurateMacroError::ConflictingLagClass`]) returns before
//! writing, leaving `out_dir` and any pre-existing `<out_dir>/macro/part.parquet` byte-identical.
//! Empty or all-unmapped inputs preserve [`curate_and_write_macro`]'s zero-row success no-op.
//!
//! # Counter Conservation Invariants
//! Every successful [`CurateMacroRunReport`] satisfies:
//! - `decode_stats.docs_in == decode_stats.docs_accepted + decode_stats.docs_rejected_total()`
//! - `decode_stats.points_in == decode_stats.points_decoded + decode_stats.rejected_total()`
//! - `decode_stats.points_decoded == curate_stats.points_in`
//! - `curate_stats.points_in == curate_stats.dropped_unmapped_series + curate_stats.builder.input`
//! - `curate_stats.rows_out == curate_stats.builder.emitted == write_stats.rows_written`
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt::{self, Write as _};
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::{Path, PathBuf};
use crate::bson_te_data::{
decode_te_data_buffer, BsonTeDataDecodeStats, BsonTeDataError, TeDataPoint,
};
use crate::curate_macro::{
curate_and_write_macro, CurateMacroError, CurateMacroStats, CurateMacroWriteError,
MacroSeriesTarget,
};
use crate::macro_series::MacroLagClass;
use crate::parquet_macro::{MacroWriteOptions, MacroWriteStats, ParquetMacroError};
/// Required exact header line (line 1) for the macro series-map TSV.
pub const MACRO_SERIES_MAP_HEADER: &str =
"te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class";
const ROLE_TE_DATA: &str = "te-data";
const ROLE_SERIES_MAP: &str = "series-map";
const SERIES_MAP_COLUMN_COUNT: usize = 6;
const SERIES_MAP_COLUMNS: [&str; SERIES_MAP_COLUMN_COUNT] = [
"te_symbol",
"country",
"category",
"country_iso",
"indicator",
"lag_class",
];
/// File-mode arguments for [`run_curate_macro`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CurateMacroArgs {
pub te_data: PathBuf,
pub series_map: PathBuf,
pub out_dir: PathBuf,
}
/// Validated caller-owned lookup from verbatim `(te_symbol, country, category)` triples to
/// [`MacroSeriesTarget`], loaded by [`load_macro_series_map_tsv`].
///
/// Backed by nested [`BTreeMap`]s so lookups accept borrowed `&str` slices with zero allocation.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MacroSeriesMap {
entries: BTreeMap<String, BTreeMap<String, BTreeMap<String, MacroSeriesTarget>>>,
len: usize,
}
impl MacroSeriesMap {
/// Returns the number of mapped series entries.
#[inline]
pub fn len(&self) -> usize {
self.len
}
/// Returns `true` if the series map contains no entries.
#[inline]
pub fn is_empty(&self) -> bool {
self.len == 0
}
/// Looks up a verbatim `(te_symbol, country, category)` triple without trimming or case folding.
#[inline]
pub fn get(
&self,
te_symbol: &str,
country: &str,
category: &str,
) -> Option<&MacroSeriesTarget> {
self.entries
.get(te_symbol)
.and_then(|by_country| by_country.get(country))
.and_then(|by_category| by_category.get(category))
}
fn insert(
&mut self,
te_symbol: String,
country: String,
category: String,
target: MacroSeriesTarget,
) -> bool {
let by_category = self
.entries
.entry(te_symbol)
.or_default()
.entry(country)
.or_default();
if by_category.contains_key(&category) {
return false;
}
by_category.insert(category, target);
self.len += 1;
true
}
}
/// Full run report produced by [`run_curate_macro`] and [`run_curate_macro_with_readers`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CurateMacroRunReport {
pub series_map_entries: usize,
pub decode_stats: BsonTeDataDecodeStats,
pub curate_stats: CurateMacroStats,
pub write_stats: MacroWriteStats,
}
/// Typed errors returned by [`load_macro_series_map_tsv`], [`run_curate_macro`], and
/// [`run_curate_macro_with_readers`].
///
/// Every variant's `Display` output is guaranteed to be a single line (CR and LF in dynamic
/// strings, paths, and wrapped error messages are escaped as `\r` and `\n`).
#[derive(Debug)]
pub enum RunCurateMacroError {
/// Failed to open a file-mode input (`te-data` or `series-map`).
OpenInput {
role: &'static str,
path: PathBuf,
source: io::Error,
},
/// Failed to read bytes from an input stream (`te-data` or `series-map`).
ReadInput {
role: &'static str,
path: Option<PathBuf>,
source: io::Error,
},
/// Series-map TSV line contained invalid UTF-8 or a bare/embedded carriage return.
SeriesMapMalformedLine { line: usize, detail: &'static str },
/// Series-map TSV was empty or line 1 did not match [`MACRO_SERIES_MAP_HEADER`] verbatim.
SeriesMapBadHeader { line: usize, found: Option<String> },
/// Series-map TSV data row did not contain exactly 6 tab-separated columns.
SeriesMapWrongColumnCount {
line: usize,
expected: usize,
actual: usize,
},
/// Series-map TSV data row contained an empty (or blank) required field.
SeriesMapEmptyField { line: usize, column: &'static str },
/// Series-map TSV data row contained an unknown `lag_class` token.
SeriesMapUnknownLagClass { line: usize, value: String },
/// Series-map TSV contained a duplicate `(te_symbol, country, category)` triple.
SeriesMapDuplicateKey {
line: usize,
te_symbol: String,
country: String,
category: String,
},
/// Structural BSON framing or element corruption in `teData` input.
CorruptTeDataBson {
path: Option<PathBuf>,
offset: usize,
source: BsonTeDataError,
},
/// Error returned by [`curate_and_write_macro`] (curation or Parquet write).
CurateWrite(CurateMacroWriteError),
}
impl RunCurateMacroError {
fn with_input_paths(self, te_data: &Path, series_map: &Path) -> Self {
match self {
Self::ReadInput {
role,
path: None,
source,
} => {
let path = match role {
ROLE_TE_DATA => Some(te_data.to_path_buf()),
ROLE_SERIES_MAP => Some(series_map.to_path_buf()),
_ => None,
};
Self::ReadInput { role, path, source }
}
Self::CorruptTeDataBson {
path: None,
offset,
source,
} => Self::CorruptTeDataBson {
path: Some(te_data.to_path_buf()),
offset,
source,
},
other => other,
}
}
}
struct SingleLineWriter<'a, 'b> {
f: &'a mut fmt::Formatter<'b>,
}
impl fmt::Write for SingleLineWriter<'_, '_> {
fn write_str(&mut self, s: &str) -> fmt::Result {
let mut rest = s;
while let Some(idx) = rest.find(['\n', '\r']) {
let (head, tail) = rest.split_at(idx);
if !head.is_empty() {
self.f.write_str(head)?;
}
let mut chars = tail.chars();
match chars.next() {
Some('\n') => self.f.write_str("\\n")?,
Some('\r') => self.f.write_str("\\r")?,
_ => unreachable!(),
}
rest = chars.as_str();
}
if !rest.is_empty() {
self.f.write_str(rest)?;
}
Ok(())
}
}
impl fmt::Display for RunCurateMacroError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut w = SingleLineWriter { f };
match self {
Self::OpenInput { role, path, source } => {
write!(w, "failed to open {role} '{}': {source}", path.display())
}
Self::ReadInput { role, path, source } => match path {
Some(path) => write!(w, "failed to read {role} '{}': {source}", path.display()),
None => write!(w, "failed to read {role}: {source}"),
},
Self::SeriesMapMalformedLine { line, detail } => {
write!(w, "series-map TSV line {line}: {detail}")
}
Self::SeriesMapBadHeader { line, found } => match found {
Some(found) => write!(
w,
"series-map TSV line {line}: invalid header {found:?}; expected exact {MACRO_SERIES_MAP_HEADER:?}"
),
None => write!(
w,
"series-map TSV line {line}: missing required header {MACRO_SERIES_MAP_HEADER:?}"
),
},
Self::SeriesMapWrongColumnCount {
line,
expected,
actual,
} => write!(
w,
"series-map TSV line {line}: expected {expected} tab-separated columns, got {actual}"
),
Self::SeriesMapEmptyField { line, column } => {
write!(
w,
"series-map TSV line {line}: field '{column}' must not be empty"
)
}
Self::SeriesMapUnknownLagClass { line, value } => write!(
w,
"series-map TSV line {line}: unknown lag_class {value:?}; expected one of 'policy_rate', 'monthly_release', 'gdp65', 'gdp90'"
),
Self::SeriesMapDuplicateKey {
line,
te_symbol,
country,
category,
} => write!(
w,
"series-map TSV line {line}: duplicate series key ({te_symbol:?}, {country:?}, {category:?})"
),
Self::CorruptTeDataBson {
path,
offset,
source,
} => match path {
Some(path) => write!(
w,
"corrupt {ROLE_TE_DATA} BSON '{}' at byte offset {offset}: {source}",
path.display()
),
None => write!(
w,
"corrupt {ROLE_TE_DATA} BSON at byte offset {offset}: {source}"
),
},
Self::CurateWrite(source) => write!(w, "{source}"),
}
}
}
impl Error for RunCurateMacroError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::OpenInput { source, .. } | Self::ReadInput { source, .. } => Some(source),
Self::CorruptTeDataBson { source, .. } => Some(source),
Self::CurateWrite(source) => Some(source),
Self::SeriesMapMalformedLine { .. }
| Self::SeriesMapBadHeader { .. }
| Self::SeriesMapWrongColumnCount { .. }
| Self::SeriesMapEmptyField { .. }
| Self::SeriesMapUnknownLagClass { .. }
| Self::SeriesMapDuplicateKey { .. } => None,
}
}
}
impl From<CurateMacroWriteError> for RunCurateMacroError {
fn from(err: CurateMacroWriteError) -> Self {
Self::CurateWrite(err)
}
}
impl From<CurateMacroError> for RunCurateMacroError {
fn from(err: CurateMacroError) -> Self {
Self::CurateWrite(CurateMacroWriteError::Curate(err))
}
}
impl From<ParquetMacroError> for RunCurateMacroError {
fn from(err: ParquetMacroError) -> Self {
Self::CurateWrite(CurateMacroWriteError::Parquet(err))
}
}
#[inline]
fn parse_lag_class_token(token: &str) -> Option<MacroLagClass> {
match token {
"policy_rate" => Some(MacroLagClass::PolicyRate),
"monthly_release" => Some(MacroLagClass::MonthlyRelease),
"gdp65" => Some(MacroLagClass::Gdp65),
"gdp90" => Some(MacroLagClass::Gdp90),
_ => None,
}
}
#[inline]
fn is_structural_te_data_bson_error(err: &BsonTeDataError) -> bool {
matches!(
err,
BsonTeDataError::TruncatedDocument { .. }
| BsonTeDataError::CorruptDocumentLength { .. }
| BsonTeDataError::CorruptBson { .. }
| BsonTeDataError::CorruptPointBson { .. }
)
}
/// Parses and validates a caller-supplied macro series-map TSV into a [`MacroSeriesMap`].
///
/// Format:
/// - Line 1 must be the exact header
/// `te_symbol\tcountry\tcategory\tcountry_iso\tindicator\tlag_class`.
/// - Each subsequent line must have 6 nonempty tab-separated fields, preserved verbatim (no
/// trimming or case folding), with `lag_class` in
/// `{"policy_rate", "monthly_release", "gdp65", "gdp90"}` and unique
/// `(te_symbol, country, category)` keys.
pub fn load_macro_series_map_tsv<R: io::Read>(
reader: R,
) -> Result<MacroSeriesMap, RunCurateMacroError> {
let mut buf_reader = BufReader::new(reader);
let mut raw_buf: Vec<u8> = Vec::with_capacity(256);
let mut line_no: usize = 0;
let mut map = MacroSeriesMap::default();
let mut saw_header = false;
loop {
raw_buf.clear();
let bytes_read = buf_reader.read_until(b'\n', &mut raw_buf).map_err(|source| {
RunCurateMacroError::ReadInput {
role: ROLE_SERIES_MAP,
path: None,
source,
}
})?;
if bytes_read == 0 {
break;
}
line_no += 1;
let mut slice = raw_buf.as_slice();
if slice.ends_with(b"\n") {
slice = &slice[..slice.len() - 1];
if slice.ends_with(b"\r") {
slice = &slice[..slice.len() - 1];
}
}
if slice.contains(&b'\r') {
return Err(RunCurateMacroError::SeriesMapMalformedLine {
line: line_no,
detail: "unexpected carriage return inside TSV line",
});
}
let line = std::str::from_utf8(slice).map_err(|_| {
RunCurateMacroError::SeriesMapMalformedLine {
line: line_no,
detail: "invalid UTF-8 in TSV line",
}
})?;
if !saw_header {
if line != MACRO_SERIES_MAP_HEADER {
return Err(RunCurateMacroError::SeriesMapBadHeader {
line: 1,
found: Some(line.to_owned()),
});
}
saw_header = true;
continue;
}
let cols: Vec<&str> = line.split('\t').collect();
if cols.len() != SERIES_MAP_COLUMN_COUNT {
return Err(RunCurateMacroError::SeriesMapWrongColumnCount {
line: line_no,
expected: SERIES_MAP_COLUMN_COUNT,
actual: cols.len(),
});
}
for (idx, (&col, &col_name)) in cols.iter().zip(SERIES_MAP_COLUMNS.iter()).enumerate() {
let is_empty = if idx == 5 {
col.is_empty()
} else {
col.trim().is_empty()
};
if is_empty {
return Err(RunCurateMacroError::SeriesMapEmptyField {
line: line_no,
column: col_name,
});
}
}
let te_symbol = cols[0];
let country = cols[1];
let category = cols[2];
let country_iso = cols[3];
let indicator = cols[4];
let lag_token = cols[5];
let lag_class = parse_lag_class_token(lag_token).ok_or_else(|| {
RunCurateMacroError::SeriesMapUnknownLagClass {
line: line_no,
value: lag_token.to_owned(),
}
})?;
let target = MacroSeriesTarget {
country_iso: country_iso.to_owned(),
indicator: indicator.to_owned(),
lag_class,
};
if !map.insert(
te_symbol.to_owned(),
country.to_owned(),
category.to_owned(),
target,
) {
return Err(RunCurateMacroError::SeriesMapDuplicateKey {
line: line_no,
te_symbol: te_symbol.to_owned(),
country: country.to_owned(),
category: category.to_owned(),
});
}
}
if !saw_header {
return Err(RunCurateMacroError::SeriesMapBadHeader {
line: 1,
found: None,
});
}
Ok(map)
}
/// Runs file-mode `curate-macro` from arbitrary [`io::Read`] streams for `teData` BSON and
/// the series-map TSV, publishing `<out_dir>/macro/part.parquet` via [`curate_and_write_macro`].
///
/// The series map is validated in full before `te_data` is decoded or `out_dir` is touched. Any
/// map, I/O, structural BSON, or curation error returns before publishing and leaves `out_dir` and
/// any pre-existing `<out_dir>/macro/part.parquet` untouched.
pub fn run_curate_macro_with_readers<RT: io::Read, RM: io::Read>(
mut te_data: RT,
series_map: RM,
out_dir: &Path,
) -> Result<CurateMacroRunReport, RunCurateMacroError> {
let map = load_macro_series_map_tsv(series_map)?;
let mut te_data_buf = Vec::new();
te_data
.read_to_end(&mut te_data_buf)
.map_err(|source| RunCurateMacroError::ReadInput {
role: ROLE_TE_DATA,
path: None,
source,
})?;
let mut points: Vec<TeDataPoint<'_>> = Vec::new();
let mut structural_err: Option<(usize, BsonTeDataError)> = None;
let decode_stats = decode_te_data_buffer(
&te_data_buf,
|point| points.push(point),
|offset, err| {
if structural_err.is_none() && is_structural_te_data_bson_error(&err) {
structural_err = Some((offset, err));
}
},
);
if let Some((offset, source)) = structural_err {
return Err(RunCurateMacroError::CorruptTeDataBson {
path: None,
offset,
source,
});
}
let write_report = curate_and_write_macro(
out_dir,
points,
|te_symbol, country, category| map.get(te_symbol, country, category).cloned(),
MacroWriteOptions::default(),
)?;
Ok(CurateMacroRunReport {
series_map_entries: map.len(),
decode_stats,
curate_stats: write_report.curate_stats,
write_stats: write_report.write_stats,
})
}
/// Runs file-mode `curate-macro` by opening `args.series_map` and `args.te_data` and delegating
/// to [`run_curate_macro_with_readers`].
///
/// File open, read, and structural BSON errors attach the offending role (`te-data` or
/// `series-map`) and path. Any error returns before writing to `args.out_dir`.
pub fn run_curate_macro(args: &CurateMacroArgs) -> Result<CurateMacroRunReport, RunCurateMacroError> {
let series_map_file =
File::open(&args.series_map).map_err(|source| RunCurateMacroError::OpenInput {
role: ROLE_SERIES_MAP,
path: args.series_map.clone(),
source,
})?;
let te_data_file =
File::open(&args.te_data).map_err(|source| RunCurateMacroError::OpenInput {
role: ROLE_TE_DATA,
path: args.te_data.clone(),
source,
})?;
run_curate_macro_with_readers(te_data_file, series_map_file, &args.out_dir)
.map_err(|err| err.with_input_paths(&args.te_data, &args.series_map))
}
/// Formats [`CurateMacroRunReport`] into deterministic multi-line `key=value` text.
pub fn format_curate_macro_report(report: &CurateMacroRunReport) -> String {
let d = &report.decode_stats;
let c = &report.curate_stats;
let b = &c.builder;
let w = &report.write_stats;
format!(
"curate-etl curate-macro\n\
\x20 map: entries={}\n\
\x20 decode: docs_in={} docs_accepted={} docs_rejected={} (missing_symbol={} empty_symbol={} wrong_symbol_type={} missing_country={} empty_country={} wrong_country_type={} missing_category={} empty_category={} wrong_category_type={} data_missing={} data_not_array={} corrupt_doc={}) points_in={} points_decoded={} points_rejected={} (not_doc={} invalid_date={} invalid_value={} corrupt_point={})\n\
\x20 builder: input={} emitted={} skipped_unmapped_indicator={} skipped_non_finite_value={} skipped_duplicate={}\n\
\x20 curate: points_in={} rows_out={} dropped_unmapped_series={} series_out={}\n\
\x20 write: files={} row_groups={} rows_written={} bytes_written={}",
report.series_map_entries,
d.docs_in,
d.docs_accepted,
d.docs_rejected_total(),
d.rejected_missing_symbol,
d.rejected_empty_symbol,
d.rejected_wrong_symbol_type,
d.rejected_missing_country,
d.rejected_empty_country,
d.rejected_wrong_country_type,
d.rejected_missing_category,
d.rejected_empty_category,
d.rejected_wrong_category_type,
d.rejected_data_missing,
d.rejected_data_not_array,
d.rejected_corrupt_document,
d.points_in,
d.points_decoded,
d.rejected_total(),
d.rejected_point_not_document,
d.rejected_invalid_date,
d.rejected_invalid_value,
d.rejected_corrupt_point,
b.input,
b.emitted,
b.skipped_unmapped_indicator,
b.skipped_non_finite_value,
b.skipped_duplicate,
c.points_in,
c.rows_out,
c.dropped_unmapped_series,
c.series_out,
w.files_written,
w.row_groups_written,
w.rows_written,
w.bytes_written,
)
}
#[cfg(test)]
#[path = "run_curate_macro_tests.rs"]
mod tests;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,718 @@
//! End-to-end tests for the file-mode `curate-fundamentals` CLI.
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use bson::raw::{cstr, RawDocumentBuf};
use curate_etl::fundamentals::FundamentalsFields;
use curate_etl::run_curate_fundamentals::{
format_curate_fundamentals_report, run_curate_fundamentals, CurateFundamentalsArgs,
CurateFundamentalsFiscalPeriod,
};
use curate_etl::shorts::et_to_utc_micros;
use curate_etl::split::ymd_to_epoch_days;
use parquet::file::reader::{FileReader, SerializedFileReader};
use parquet::record::{Field, Row};
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new(label: &str) -> Self {
let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"curate-fundamentals-cli-{label}-{}-{seq}",
std::process::id()
));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create isolated test directory");
Self(path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn cli() -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_curate-etl"));
command.arg("curate-fundamentals");
command
}
fn make_financials_doc(
key: &str,
period_end: &str,
report_date: &str,
report_period: &str,
currency: &str,
fields: FundamentalsFields,
) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("qmSearchCode"), key);
doc.append(cstr!("periodEndDate"), period_end);
doc.append(cstr!("reportDate"), report_date);
doc.append(cstr!("reportPeriod"), report_period);
doc.append(cstr!("currency"), currency);
let mut income = RawDocumentBuf::new();
if let Some(v) = fields.revenue {
income.append(cstr!("revenue"), v);
}
if let Some(v) = fields.net_income {
income.append(cstr!("netIncome"), v);
}
doc.append(cstr!("IncomeStatement"), income);
let mut cashflow = RawDocumentBuf::new();
if let Some(v) = fields.operating_cash_flow {
cashflow.append(cstr!("operatingCashFlow"), v);
}
doc.append(cstr!("CashFlow"), cashflow);
let mut balance = RawDocumentBuf::new();
if let Some(v) = fields.total_assets {
balance.append(cstr!("totalAssets"), v);
}
if let Some(v) = fields.total_equity {
balance.append(cstr!("totalEquity"), v);
}
if let Some(v) = fields.shares_outstanding {
balance.append(cstr!("sharesOutstanding"), v);
}
doc.append(cstr!("BalanceSheet"), balance);
doc.into_bytes()
}
fn make_filing_doc(key: &str, timefiled: &str, form_type: &str, filing_id: &str) -> Vec<u8> {
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("symbol"), key);
doc.append(cstr!("timefiled"), timefiled);
doc.append(cstr!("formType"), form_type);
doc.append(cstr!("filingId"), filing_id);
doc.into_bytes()
}
fn read_parquet_partitions(out_dir: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
let dataset_root = out_dir.join("fundamentals_pit");
let mut files = BTreeMap::new();
for entry in fs::read_dir(&dataset_root).expect("read fundamentals_pit dir") {
let entry = entry.expect("dir entry");
let name = entry.file_name();
let part_path = entry.path().join("part.parquet");
assert!(
part_path.is_file(),
"expected part.parquet in {}",
entry.path().display()
);
let rel = PathBuf::from(&name).join("part.parquet");
files.insert(rel, fs::read(&part_path).expect("read parquet bytes"));
}
files
}
fn write_restatement_fixture(dir: &Path) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
let fin_path = dir.join("qmFinancials.bson");
let fil_path = dir.join("qmFilings.bson");
let map_path = dir.join("provider_mapping.tsv");
let venues_path = dir.join("listing_venues.tsv");
fs::write(&map_path, "qm\tACME\t2020-01-01\t\t301\n").unwrap();
fs::write(&venues_path, "301\tus_tsx\n").unwrap();
// Specimen dates and field shapes from `run_curate_fundamentals_tests`:
// four contiguous quarters (Q3 2023 .. Q2 2024) plus a late Q1 2024 restatement (10-Q/A on
// 2024-09-15) and an unmapped observation.
let mut fin_bytes = Vec::new();
for (key, pe, rd, rp, rev, ni, ocf, ta, te, sh) in [
(
"ACME",
"2023-09-30",
"2023-11-05",
"Q3",
90.0,
8.0,
10.0,
460.0,
275.0,
20.0,
),
(
"ACME",
"2023-12-31",
"2024-02-20",
"Q4",
110.0,
11.0,
14.0,
480.0,
288.0,
20.0,
),
(
"ACME",
"2024-03-31",
"2024-05-05",
"Q1",
100.0,
10.0,
12.0,
500.0,
300.0,
20.0,
),
(
"ACME",
"2024-06-30",
"2024-08-05",
"Q2",
250.0,
30.0,
35.0,
550.0,
330.0,
20.0,
),
(
"ACME",
"2024-03-31",
"2024-09-15",
"Q1",
88.0,
4.0,
9.0,
490.0,
294.0,
20.0,
),
(
"UNMAPPED",
"2024-06-30",
"2024-08-05",
"Q2",
50.0,
5.0,
6.0,
100.0,
60.0,
10.0,
),
] {
fin_bytes.extend_from_slice(&make_financials_doc(
key,
pe,
rd,
rp,
"USD",
FundamentalsFields {
revenue: Some(rev),
net_income: Some(ni),
operating_cash_flow: Some(ocf),
total_assets: Some(ta),
total_equity: Some(te),
shares_outstanding: Some(sh),
},
));
}
fs::write(&fin_path, fin_bytes).unwrap();
let mut fil_bytes = Vec::new();
for (key, ts, form, id) in [
("ACME", "2023-11-05T16:10:00 EST", "10-Q", "q3-2023-1"),
("ACME", "2024-02-20T16:10:00 EST", "10-Q", "q4-2023-1"),
("ACME", "2024-05-05T16:10:00 EDT", "10-Q", "q1-2024-1"),
("ACME", "2024-08-05T16:15:00 EDT", "10-Q", "q2-2024-1"),
("ACME", "2024-09-15T16:20:00 EDT", "10-Q/A", "q1-2024-a"),
] {
fil_bytes.extend_from_slice(&make_filing_doc(key, ts, form, id));
}
fs::write(&fil_path, fil_bytes).unwrap();
(fin_path, fil_path, map_path, venues_path)
}
#[test]
fn cli_publishes_runner_equivalent_fundamentals_and_preserves_pit_restatement() {
let dir = TempDir::new("e2e");
let (fin_path, fil_path, map_path, venues_path) = write_restatement_fixture(&dir.0);
let baseline_dir = dir.0.join("baseline");
let mut baseline_args = CurateFundamentalsArgs::with_verified_defaults(
fin_path.clone(),
fil_path.clone(),
map_path.clone(),
venues_path.clone(),
baseline_dir.clone(),
"currency",
Some("IncomeStatement.revenue".to_string()),
Some("IncomeStatement.netIncome".to_string()),
Some("CashFlow.operatingCashFlow".to_string()),
Some("BalanceSheet.totalAssets".to_string()),
Some("BalanceSheet.totalEquity".to_string()),
Some("BalanceSheet.sharesOutstanding".to_string()),
CurateFundamentalsFiscalPeriod::ByTokens {
quarterly: vec![
"Q1".to_string(),
"Q2".to_string(),
"Q3".to_string(),
"Q4".to_string(),
],
annual: vec!["FY".to_string()],
},
"formType",
4,
);
baseline_args.filings_filing_id_field = Some("filingId".to_string());
let baseline_report = run_curate_fundamentals(&baseline_args).expect("run library baseline");
let expected_report = format_curate_fundamentals_report(&baseline_report);
let baseline_partitions = read_parquet_partitions(&baseline_dir);
assert!(
baseline_partitions.contains_key(Path::new("year=2024/part.parquet")),
"expected nonempty 2024 partition"
);
let cli_out = dir.0.join("cli_out");
let result = cli()
.current_dir(&dir.0)
.args([
"--qm-financials",
"qmFinancials.bson",
"--qm-filings=qmFilings.bson",
"--provider-mapping",
"provider_mapping.tsv",
"--listing-venues=listing_venues.tsv",
"--out",
"cli_out",
"--currency-field=currency",
"--filings-form-type-field",
"formType",
"--filings-filing-id-field=filingId",
"--k",
"4",
"--quarterly-tokens=Q1,Q2,Q3,Q4",
"--annual-tokens",
"FY",
"--revenue-field",
"IncomeStatement.revenue",
"--net-income-field=IncomeStatement.netIncome",
"--operating-cash-flow-field",
"CashFlow.operatingCashFlow",
"--total-assets-field=BalanceSheet.totalAssets",
"--total-equity-field",
"BalanceSheet.totalEquity",
"--shares-outstanding-field=BalanceSheet.sharesOutstanding",
])
.output()
.expect("run curate-fundamentals");
assert!(result.status.success(), "{result:?}");
assert!(
result.stderr.is_empty(),
"unexpected stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout");
let actual_lines: Vec<&str> = stdout.lines().collect();
let expected_lines: Vec<&str> = expected_report.lines().collect();
assert_eq!(actual_lines.len(), expected_lines.len(), "{stdout}");
assert_eq!(
&actual_lines[..actual_lines.len() - 1],
&expected_lines[..expected_lines.len() - 1],
"deterministic report lines must match library baseline"
);
let timing_line = *actual_lines.last().unwrap();
let elapsed_str = timing_line
.strip_prefix(" timing: elapsed_secs=")
.unwrap_or_else(|| panic!("unexpected timing line: {timing_line:?}"));
let elapsed: f64 = elapsed_str.parse().expect("valid elapsed_secs float");
assert!(elapsed.is_finite() && elapsed >= 0.0, "{timing_line}");
let cli_partitions = read_parquet_partitions(&cli_out);
assert_eq!(
cli_partitions.keys().collect::<Vec<_>>(),
baseline_partitions.keys().collect::<Vec<_>>(),
"partition paths must match baseline"
);
for (rel, expected_bytes) in &baseline_partitions {
assert_eq!(
cli_partitions.get(rel).unwrap(),
expected_bytes,
"Parquet bytes differ for {}",
rel.display()
);
}
// Read the 2024 partition and verify listing, currency, metric value, filing-derived known_at,
// and PIT restatement isolation (Q1 restatement only visible at 2024-09-15).
let part_2024 = cli_out.join("fundamentals_pit/year=2024/part.parquet");
let reader = SerializedFileReader::new(File::open(&part_2024).unwrap()).unwrap();
let rows: Vec<_> = reader
.get_row_iter(None)
.unwrap()
.map(Result::unwrap)
.collect();
assert_eq!(
rows.len(),
4,
"expected Q4-23, Q1-24, Q2-24, and Q1-24/A snapshots in 2024"
);
let q2_filed_micros =
et_to_utc_micros(ymd_to_epoch_days(2024, 8, 5).unwrap(), 16, 15, 0).unwrap();
let restate_filed_micros =
et_to_utc_micros(ymd_to_epoch_days(2024, 9, 15).unwrap(), 16, 20, 0).unwrap();
fn col<'a>(row: &'a Row, name: &str) -> &'a Field {
row.get_column_iter()
.find(|(col_name, _)| col_name.as_str() == name)
.unwrap_or_else(|| panic!("missing Parquet column '{name}'"))
.1
}
let q2_row = &rows[2];
assert_eq!(col(q2_row, "listing_id"), &Field::Int(301));
assert_eq!(
col(q2_row, "effective_known_at"),
&Field::TimestampMicros(q2_filed_micros)
);
assert_eq!(
col(q2_row, "known_at_source"),
&Field::Str("filing_timestamp".to_string())
);
assert_eq!(
col(q2_row, "period_end"),
&Field::Date(ymd_to_epoch_days(2024, 6, 30).unwrap())
);
assert_eq!(col(q2_row, "currency"), &Field::Str("USD".to_string()));
assert_eq!(col(q2_row, "revenue"), &Field::Double(250.0));
assert_eq!(col(q2_row, "ttm_revenue"), &Field::Double(550.0));
let restated_row = &rows[3];
assert_eq!(col(restated_row, "listing_id"), &Field::Int(301));
assert_eq!(
col(restated_row, "effective_known_at"),
&Field::TimestampMicros(restate_filed_micros)
);
assert_eq!(
col(restated_row, "known_at_source"),
&Field::Str("filing_timestamp".to_string())
);
// Latest period remains Q2 2024 (250.0 revenue) while TTM revenue reflects the -12.0 Q1 restatement.
assert_eq!(
col(restated_row, "period_end"),
&Field::Date(ymd_to_epoch_days(2024, 6, 30).unwrap())
);
assert_eq!(
col(restated_row, "currency"),
&Field::Str("USD".to_string())
);
assert_eq!(col(restated_row, "revenue"), &Field::Double(250.0));
assert_eq!(col(restated_row, "ttm_revenue"), &Field::Double(538.0));
}
#[test]
fn cli_fails_closed_without_creating_out_dir_on_invalid_flags() {
let dir = TempDir::new("fail-closed");
let (_fin_path, _fil_path, _map_path, _venues_path) = write_restatement_fixture(&dir.0);
let out_missing_k = dir.0.join("out_missing_k");
let res_missing_k = cli()
.current_dir(&dir.0)
.args([
"--qm-financials",
"qmFinancials.bson",
"--qm-filings",
"qmFilings.bson",
"--provider-mapping",
"provider_mapping.tsv",
"--listing-venues",
"listing_venues.tsv",
"--out",
"out_missing_k",
"--currency-field",
"currency",
"--filings-form-type-field",
"formType",
"--fiscal-period",
"quarterly",
])
.output()
.expect("run curate-fundamentals missing --k");
assert_eq!(res_missing_k.status.code(), Some(1));
assert!(res_missing_k.stdout.is_empty());
let stderr_k = String::from_utf8(res_missing_k.stderr).unwrap();
let mut lines_k = stderr_k.lines();
assert_eq!(lines_k.next(), Some("error: missing required flag '--k'"));
assert_eq!(lines_k.next(), Some("Usage:"));
assert!(
stderr_k.contains("curate-fundamentals --qm-financials"),
"{stderr_k}"
);
assert!(!out_missing_k.exists(), "out_missing_k must not be created");
let out_from_mongo = dir.0.join("out_from_mongo");
let res_mongo = cli()
.current_dir(&dir.0)
.args([
"--from-mongo",
"--qm-financials",
"qmFinancials.bson",
"--qm-filings",
"qmFilings.bson",
"--provider-mapping",
"provider_mapping.tsv",
"--listing-venues",
"listing_venues.tsv",
"--out",
"out_from_mongo",
"--currency-field",
"currency",
"--filings-form-type-field",
"formType",
"--k",
"4",
"--fiscal-period",
"quarterly",
])
.output()
.expect("run curate-fundamentals with --from-mongo");
assert_eq!(res_mongo.status.code(), Some(1));
assert!(res_mongo.stdout.is_empty());
let stderr_mongo = String::from_utf8(res_mongo.stderr).unwrap();
let mut lines_mongo = stderr_mongo.lines();
assert_eq!(
lines_mongo.next(),
Some("error: unknown flag '--from-mongo' for curate-fundamentals")
);
assert_eq!(lines_mongo.next(), Some("Usage:"));
assert!(
stderr_mongo.contains("curate-fundamentals --qm-financials"),
"{stderr_mongo}"
);
assert!(
!out_from_mongo.exists(),
"out_from_mongo must not be created"
);
}
const FIXTURE_REQUIRED_ARGS: [&str; 14] = [
"--qm-financials",
"qmFinancials.bson",
"--qm-filings",
"qmFilings.bson",
"--provider-mapping",
"provider_mapping.tsv",
"--listing-venues",
"listing_venues.tsv",
"--currency-field",
"currency",
"--filings-form-type-field",
"formType",
"--k",
"4",
];
fn assert_single_line_error_then_usage(stderr: &[u8], expected_error: &str) {
let text = String::from_utf8(stderr.to_vec()).expect("utf-8 stderr");
let mut lines = text.lines();
assert_eq!(lines.next(), Some(expected_error), "{text}");
assert_eq!(lines.next(), Some("Usage:"), "{text}");
assert!(
text.contains("curate-fundamentals --qm-financials"),
"{text}"
);
}
#[test]
fn cli_fixed_fiscal_period_without_metric_fields_matches_runner_and_writes_null_metrics() {
let dir = TempDir::new("fixed-null-metrics");
let (fin_path, fil_path, map_path, venues_path) = write_restatement_fixture(&dir.0);
let baseline_dir = dir.0.join("baseline");
let baseline_args = CurateFundamentalsArgs::with_verified_defaults(
fin_path,
fil_path,
map_path,
venues_path,
baseline_dir.clone(),
"currency",
None,
None,
None,
None,
None,
None,
CurateFundamentalsFiscalPeriod::Fixed(curate_etl::fundamentals::FiscalPeriod::Quarterly),
"formType",
4,
);
let baseline_report = run_curate_fundamentals(&baseline_args).expect("run library baseline");
let expected_report = format_curate_fundamentals_report(&baseline_report);
let baseline_partitions = read_parquet_partitions(&baseline_dir);
let result = cli()
.current_dir(&dir.0)
.args(FIXTURE_REQUIRED_ARGS)
.args(["--out=cli_out", "--fiscal-period=quarterly"])
.output()
.expect("run curate-fundamentals");
assert!(result.status.success(), "{result:?}");
assert!(result.stderr.is_empty(), "{result:?}");
let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout");
let actual: Vec<&str> = stdout.lines().collect();
let expected: Vec<&str> = expected_report.lines().collect();
assert_eq!(actual.len(), expected.len(), "{stdout}");
assert_eq!(actual[..actual.len() - 1], expected[..expected.len() - 1]);
let cli_partitions = read_parquet_partitions(&dir.0.join("cli_out"));
assert_eq!(cli_partitions, baseline_partitions);
let part_2024 = dir
.0
.join("cli_out/fundamentals_pit/year=2024/part.parquet");
let reader = SerializedFileReader::new(File::open(&part_2024).unwrap()).unwrap();
let rows: Vec<Row> = reader
.get_row_iter(None)
.unwrap()
.map(Result::unwrap)
.collect();
assert!(!rows.is_empty(), "expected nonempty 2024 partition");
for row in &rows {
let revenue = row
.get_column_iter()
.find(|(name, _)| name.as_str() == "revenue")
.expect("revenue column")
.1;
assert_eq!(revenue, &Field::Null, "unconfigured metric must be NULL");
let currency = row
.get_column_iter()
.find(|(name, _)| name.as_str() == "currency")
.expect("currency column")
.1;
assert_eq!(currency, &Field::Str("USD".to_string()));
}
}
#[test]
fn cli_rerun_into_fresh_out_dir_is_byte_deterministic() {
let dir = TempDir::new("rerun");
write_restatement_fixture(&dir.0);
for out in ["run_a", "run_b"] {
let result = cli()
.current_dir(&dir.0)
.args(FIXTURE_REQUIRED_ARGS)
.args(["--out", out, "--quarterly-tokens", "Q1,Q2,Q3,Q4"])
.args(["--revenue-field", "IncomeStatement.revenue"])
.output()
.expect("run curate-fundamentals");
assert!(result.status.success(), "{result:?}");
}
let a = read_parquet_partitions(&dir.0.join("run_a"));
let b = read_parquet_partitions(&dir.0.join("run_b"));
assert!(!a.is_empty());
assert_eq!(
a, b,
"identical inputs must publish identical Parquet bytes"
);
}
#[test]
fn cli_runner_failure_on_missing_input_exits_nonzero_single_line_without_usage_or_output() {
let dir = TempDir::new("missing-input");
write_restatement_fixture(&dir.0);
fs::remove_file(dir.0.join("qmFilings.bson")).unwrap();
let result = cli()
.current_dir(&dir.0)
.args(FIXTURE_REQUIRED_ARGS)
.args(["--out", "out", "--fiscal-period", "quarterly"])
.output()
.expect("run curate-fundamentals");
assert_eq!(result.status.code(), Some(1));
assert!(result.stdout.is_empty());
let stderr = String::from_utf8(result.stderr).unwrap();
assert_eq!(stderr.lines().count(), 1, "{stderr}");
assert!(stderr.starts_with("error: "), "{stderr}");
assert!(stderr.contains("qmFilings.bson"), "{stderr}");
assert!(!stderr.contains("Usage:"), "{stderr}");
assert!(!dir.0.join("out").exists(), "out must not be created");
}
#[test]
fn cli_truncated_financials_dump_fails_closed_without_publishing() {
let dir = TempDir::new("truncated");
write_restatement_fixture(&dir.0);
fs::write(dir.0.join("qmFinancials.bson"), [0x10u8, 0x00, 0x00]).unwrap();
let result = cli()
.current_dir(&dir.0)
.args(FIXTURE_REQUIRED_ARGS)
.args(["--out", "out", "--fiscal-period", "quarterly"])
.output()
.expect("run curate-fundamentals");
assert_eq!(result.status.code(), Some(1));
assert!(result.stdout.is_empty());
let stderr = String::from_utf8(result.stderr).unwrap();
assert_eq!(stderr.lines().count(), 1, "{stderr}");
assert!(stderr.starts_with("error: "), "{stderr}");
assert!(!dir.0.join("out/fundamentals_pit").exists());
}
#[test]
fn cli_parse_time_config_errors_fail_closed_before_touching_out() {
let dir = TempDir::new("config-errors");
write_restatement_fixture(&dir.0);
let cases: [(&[&str], &str); 4] = [
(
&["--quarterly-tokens", "Q1,FY", "--annual-tokens", "FY"],
"error: invalid qmFinancials fiscal period configuration: report_period token 'FY' cannot appear in both quarterly and annual lists",
),
(
&["--fiscal-period", "quarterly", "--quarterly-tokens", "Q1"],
"error: cannot combine '--fiscal-period' with '--quarterly-tokens' or '--annual-tokens'",
),
(
&["--fiscal-period", "quarterly", "--mongo-uri", "mongodb://localhost:27017/stock"],
"error: unknown flag '--mongo-uri' for curate-fundamentals",
),
(
&["--fiscal-period", "quarterly", "--k", "0"],
"error: duplicate flag '--k'",
),
];
for (idx, (extra, expected_error)) in cases.iter().enumerate() {
let out = format!("out_{idx}");
let result = cli()
.current_dir(&dir.0)
.args(FIXTURE_REQUIRED_ARGS)
.args(["--out", out.as_str()])
.args(*extra)
.output()
.expect("run curate-fundamentals");
assert_eq!(result.status.code(), Some(1), "case {idx}");
assert!(result.stdout.is_empty(), "case {idx}");
assert_single_line_error_then_usage(&result.stderr, expected_error);
assert!(
!dir.0.join(&out).exists(),
"case {idx}: out must not be created"
);
}
}

View file

@ -0,0 +1,776 @@
//! End-to-end tests for the file-mode `curate-macro` CLI.
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, Ordering};
use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf};
use bson::DateTime;
use curate_etl::macro_series::{
MACRO_KNOWN_AT_SOURCE, MONTHLY_RELEASE_LAG_DAYS, POLICY_RATE_LAG_DAYS,
};
use curate_etl::run_curate_macro::{
format_curate_macro_report, run_curate_macro, CurateMacroArgs, MACRO_SERIES_MAP_HEADER,
};
use curate_etl::split::ymd_to_epoch_days;
use parquet::file::reader::{FileReader, SerializedFileReader};
use parquet::record::{Field, Row};
const MICROS_PER_DAY: i64 = 86_400_000_000;
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new(label: &str) -> Self {
let seq = TEMP_SEQ.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"curate-macro-cli-{label}-{}-{seq}",
std::process::id()
));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("create isolated test directory");
Self(path)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
fn cli() -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_curate-etl"));
command.arg("curate-macro");
command
}
fn day(y: i32, m: u32, d: u32) -> i32 {
ymd_to_epoch_days(y, m, d).expect("valid date")
}
fn make_point_doc(d: &str, v: f64) -> RawDocumentBuf {
let mut pt = RawDocumentBuf::new();
pt.append(cstr!("d"), d);
pt.append(cstr!("v"), v);
pt
}
fn make_te_data_doc(
te_symbol: &str,
country: &str,
category: &str,
data_points: &[(&str, f64)],
forecast_points: &[(&str, f64)],
) -> RawDocumentBuf {
let mut data_arr = RawArrayBuf::new();
for &(d, v) in data_points {
data_arr.push(make_point_doc(d, v));
}
let mut forecast_arr = RawArrayBuf::new();
for &(d, v) in forecast_points {
forecast_arr.push(make_point_doc(d, v));
}
let mut doc = RawDocumentBuf::new();
doc.append(cstr!("teSymbol"), te_symbol);
doc.append(cstr!("name"), format!("{country} {category}"));
doc.append(cstr!("unit"), "percent");
doc.append(cstr!("source"), "TradingEconomics");
doc.append(cstr!("frequency"), "Monthly");
doc.append(cstr!("country"), country);
doc.append(cstr!("category"), category);
doc.append(cstr!("data"), data_arr);
doc.append(cstr!("forecast"), forecast_arr);
doc.append(
cstr!("lastUpdated"),
DateTime::from_millis(1_710_000_000_000),
);
doc.append(cstr!("createdAt"), DateTime::from_millis(1_700_000_000_000));
doc
}
fn write_macro_fixture(dir: &Path) -> (PathBuf, PathBuf) {
let te_data_path = dir.join("teData.bson");
let series_map_path = dir.join("series-map.tsv");
let map_tsv = format!(
"{MACRO_SERIES_MAP_HEADER}\n\
USIR\tUnited States\tInterest Rate\tUS\tpolicy_rate\tpolicy_rate\n\
CACPI\tCanada\tInflation Rate\tCA\tcpi_yoy\tmonthly_release\n"
);
fs::write(&series_map_path, map_tsv).unwrap();
// Fixture covers:
// - US policy_rate (+1d lag) with 2 valid points + 1 invalid date + forecast sentinel points
// - CA monthly_release (+35d lag) with 2 valid points + forecast sentinel points
// - One unmapped series whose points must be dropped into `dropped_unmapped_series`
let docs = [
make_te_data_doc(
"USIR",
"United States",
"Interest Rate",
&[
("2024-03-20", 5.5),
("not-a-date", 99.0),
("2024-01-31", 5.25),
],
&[("2025-12-31", 999.25)],
),
make_te_data_doc(
"CACPI",
"Canada",
"Inflation Rate",
&[("2024-02-29", 2.8), ("2024-01-31", 2.9)],
&[("2025-06-30", 888.5)],
),
make_te_data_doc(
"UNMAPPED",
"Germany",
"GDP",
&[("2024-03-31", 1.2)],
&[("2025-03-31", 777.0)],
),
];
let mut raw_bson = Vec::new();
for doc in &docs {
raw_bson.extend_from_slice(doc.as_bytes());
}
fs::write(&te_data_path, raw_bson).unwrap();
(te_data_path, series_map_path)
}
fn write_policy_rate_fixture(dir: &Path) -> (PathBuf, PathBuf) {
let te_data_path = dir.join("teData.bson");
let series_map_path = dir.join("macro_series_map.tsv");
let doc = make_te_data_doc(
"FDTR",
"United States",
"Interest Rate",
&[("2024-03-20", 5.5)],
&[("2025-01-01", 99.0)],
);
fs::write(&te_data_path, doc.as_bytes()).expect("write teData.bson");
let tsv = format!(
"{MACRO_SERIES_MAP_HEADER}\nFDTR\tUnited States\tInterest Rate\tUS\tfed_funds_rate\tpolicy_rate\n"
);
fs::write(&series_map_path, tsv).expect("write macro_series_map.tsv");
(te_data_path, series_map_path)
}
fn col<'a>(row: &'a Row, name: &str) -> &'a Field {
row.get_column_iter()
.find(|(col_name, _)| col_name.as_str() == name)
.unwrap_or_else(|| panic!("missing Parquet column '{name}'"))
.1
}
#[test]
fn cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage() {
let dir = TempDir::new("e2e");
let (te_data_path, series_map_path) = write_macro_fixture(&dir.0);
let baseline_dir = dir.0.join("baseline");
let baseline_args = CurateMacroArgs {
te_data: te_data_path,
series_map: series_map_path,
out_dir: baseline_dir.clone(),
};
let baseline_report = run_curate_macro(&baseline_args).expect("run library baseline");
// Verify fixture counts and conservation equations.
assert_eq!(baseline_report.series_map_entries, 2);
let d = &baseline_report.decode_stats;
let c = &baseline_report.curate_stats;
let w = &baseline_report.write_stats;
assert_eq!(d.docs_in, 3);
assert_eq!(d.docs_accepted, 3);
assert_eq!(d.docs_rejected_total(), 0);
assert_eq!(d.docs_in, d.docs_accepted + d.docs_rejected_total());
assert_eq!(d.points_in, 6);
assert_eq!(d.points_decoded, 5);
assert_eq!(d.rejected_invalid_date, 1);
assert_eq!(d.points_in, d.points_decoded + d.rejected_total());
assert_eq!(d.points_decoded, c.points_in);
assert_eq!(c.dropped_unmapped_series, 1);
assert_eq!(c.builder.input, 4);
assert_eq!(c.points_in, c.dropped_unmapped_series + c.builder.input);
assert_eq!(c.rows_out, 4);
assert_eq!(c.rows_out, c.builder.emitted);
assert_eq!(c.rows_out, w.rows_written);
assert_eq!(c.series_out, 2);
assert_eq!(w.files_written, 1);
let expected_stdout = format!("{}\n", format_curate_macro_report(&baseline_report));
let baseline_parquet = fs::read(baseline_dir.join("macro/part.parquet"))
.expect("read baseline macro/part.parquet");
// First CLI run (mixed space and `=` flag forms).
let cli_out = dir.0.join("cli_out");
let result = cli()
.current_dir(&dir.0)
.args([
"--te-data",
"teData.bson",
"--series-map=series-map.tsv",
"--out",
"cli_out",
])
.output()
.expect("run curate-macro");
assert!(result.status.success(), "{result:?}");
assert!(
result.stderr.is_empty(),
"unexpected stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout");
assert_eq!(stdout, expected_stdout);
let cli_parquet_path = cli_out.join("macro/part.parquet");
assert!(cli_parquet_path.is_file(), "expected macro/part.parquet");
let cli_parquet = fs::read(&cli_parquet_path).expect("read cli macro/part.parquet");
assert_eq!(
cli_parquet, baseline_parquet,
"CLI Parquet output must be byte-identical to library baseline"
);
// Second fresh CLI run must also be byte-identical.
let cli_out_2 = dir.0.join("cli_out_2");
let result_2 = cli()
.current_dir(&dir.0)
.args([
"--out=cli_out_2",
"--series-map",
"series-map.tsv",
"--te-data=teData.bson",
])
.output()
.expect("run curate-macro second time");
assert!(result_2.status.success(), "{result_2:?}");
assert!(result_2.stderr.is_empty());
assert_eq!(
String::from_utf8(result_2.stdout).unwrap(),
expected_stdout
);
let cli_parquet_2 =
fs::read(cli_out_2.join("macro/part.parquet")).expect("read second macro/part.parquet");
assert_eq!(
cli_parquet_2, cli_parquet,
"repeat CLI run must publish byte-identical Parquet"
);
// Verify exact 6-column schema, ascending order, PIT lag math, and zero forecast leakage.
let reader = SerializedFileReader::new(File::open(&cli_parquet_path).unwrap()).unwrap();
let rows: Vec<Row> = reader
.get_row_iter(None)
.unwrap()
.map(Result::unwrap)
.collect();
assert_eq!(rows.len(), 4);
let expected_rows: [(&str, &str, i32, i32, f64); 4] = [
("CA", "cpi_yoy", day(2024, 1, 31), MONTHLY_RELEASE_LAG_DAYS, 2.9),
("CA", "cpi_yoy", day(2024, 2, 29), MONTHLY_RELEASE_LAG_DAYS, 2.8),
("US", "policy_rate", day(2024, 1, 31), POLICY_RATE_LAG_DAYS, 5.25),
("US", "policy_rate", day(2024, 3, 20), POLICY_RATE_LAG_DAYS, 5.5),
];
for (row, &(country, indicator, period_date, lag_days, value)) in
rows.iter().zip(expected_rows.iter())
{
assert_eq!(row.len(), 6, "expected 6 columns in macro/part.parquet");
assert_eq!(col(row, "country_iso"), &Field::Str(country.to_string()));
assert_eq!(col(row, "indicator"), &Field::Str(indicator.to_string()));
assert_eq!(col(row, "period_date"), &Field::Date(period_date));
let expected_known_at = i64::from(period_date + lag_days) * MICROS_PER_DAY;
assert_eq!(
col(row, "known_at"),
&Field::TimestampMicros(expected_known_at)
);
assert_eq!(
col(row, "known_at_source"),
&Field::Str(MACRO_KNOWN_AT_SOURCE.to_string())
);
assert_eq!(col(row, "value"), &Field::Double(value));
// Sentinel forecast values (999.25, 888.5, 777.0) must never appear.
assert!(value < 100.0, "unexpected forecast sentinel value {value}");
}
}
#[test]
fn cli_runner_failures_fail_closed_without_creating_or_modifying_output() {
let dir = TempDir::new("runner-failures");
write_macro_fixture(&dir.0);
// Pre-seed a sentinel macro/part.parquet to prove failed runs never overwrite existing output.
let seeded_out = dir.0.join("seeded_out");
let seeded_parquet = seeded_out.join("macro/part.parquet");
fs::create_dir_all(seeded_parquet.parent().unwrap()).unwrap();
let sentinel_bytes = b"pre-existing-macro-parquet-sentinel".to_vec();
fs::write(&seeded_parquet, &sentinel_bytes).unwrap();
// Case 1: missing --te-data file (fresh --out not created).
let missing_te_out = dir.0.join("out_missing_te");
let res_missing_te = cli()
.current_dir(&dir.0)
.args([
"--te-data",
"does-not-exist.bson",
"--series-map",
"series-map.tsv",
"--out",
"out_missing_te",
])
.output()
.expect("run curate-macro missing teData");
assert_eq!(res_missing_te.status.code(), Some(1));
assert!(res_missing_te.stdout.is_empty());
let stderr_te = String::from_utf8(res_missing_te.stderr).unwrap();
assert_eq!(stderr_te.lines().count(), 1, "{stderr_te}");
assert!(stderr_te.starts_with("error: "), "{stderr_te}");
assert!(stderr_te.contains("does-not-exist.bson"), "{stderr_te}");
assert!(!stderr_te.contains("Usage:"), "{stderr_te}");
assert!(!missing_te_out.exists(), "out dir must not be created");
// Case 2: missing --series-map file (pre-seeded output preserved).
let res_missing_map = cli()
.current_dir(&dir.0)
.args([
"--te-data",
"teData.bson",
"--series-map",
"missing-map.tsv",
"--out",
"seeded_out",
])
.output()
.expect("run curate-macro missing series-map");
assert_eq!(res_missing_map.status.code(), Some(1));
assert!(res_missing_map.stdout.is_empty());
let stderr_map = String::from_utf8(res_missing_map.stderr).unwrap();
assert_eq!(stderr_map.lines().count(), 1, "{stderr_map}");
assert!(stderr_map.starts_with("error: "), "{stderr_map}");
assert!(stderr_map.contains("missing-map.tsv"), "{stderr_map}");
assert!(!stderr_map.contains("Usage:"), "{stderr_map}");
assert_eq!(
fs::read(&seeded_parquet).unwrap(),
sentinel_bytes,
"pre-seeded macro/part.parquet must remain byte-identical"
);
// Case 3: truncated/corrupt BSON (pre-seeded output preserved, fresh out not created).
let corrupt_path = dir.0.join("corrupt.bson");
fs::write(&corrupt_path, [0x10u8, 0x00, 0x00]).unwrap();
let corrupt_out = dir.0.join("out_corrupt");
let res_corrupt = cli()
.current_dir(&dir.0)
.args([
"--te-data",
"corrupt.bson",
"--series-map",
"series-map.tsv",
"--out",
"out_corrupt",
])
.output()
.expect("run curate-macro corrupt BSON");
assert_eq!(res_corrupt.status.code(), Some(1));
assert!(res_corrupt.stdout.is_empty());
let stderr_corrupt = String::from_utf8(res_corrupt.stderr).unwrap();
assert_eq!(stderr_corrupt.lines().count(), 1, "{stderr_corrupt}");
assert!(stderr_corrupt.starts_with("error: "), "{stderr_corrupt}");
assert!(!stderr_corrupt.contains("Usage:"), "{stderr_corrupt}");
assert!(!corrupt_out.exists(), "out dir must not be created");
let res_corrupt_seeded = cli()
.current_dir(&dir.0)
.args([
"--te-data",
"corrupt.bson",
"--series-map",
"series-map.tsv",
"--out",
"seeded_out",
])
.output()
.expect("run curate-macro corrupt BSON against seeded out");
assert_eq!(res_corrupt_seeded.status.code(), Some(1));
assert!(res_corrupt_seeded.stdout.is_empty());
assert_eq!(
fs::read(&seeded_parquet).unwrap(),
sentinel_bytes,
"pre-seeded macro/part.parquet must remain byte-identical on corrupt BSON"
);
}
#[test]
fn cli_invalid_flags_print_error_and_usage_without_touching_out() {
let dir = TempDir::new("invalid-flags");
write_macro_fixture(&dir.0);
let cases: [(&[&str], &str); 2] = [
(
&[
"--from-mongo",
"--te-data",
"teData.bson",
"--series-map",
"series-map.tsv",
"--out",
"out_from_mongo",
],
"error: unknown flag '--from-mongo' for curate-macro",
),
(
&[
"--te-data",
"teData.bson",
"--series-map",
"series-map.tsv",
],
"error: missing required flag '--out'",
),
];
for (idx, (argv, expected_error)) in cases.iter().enumerate() {
let result = cli()
.current_dir(&dir.0)
.args(*argv)
.output()
.expect("run curate-macro invalid flags");
assert_eq!(result.status.code(), Some(1), "case {idx}");
assert!(result.stdout.is_empty(), "case {idx}");
let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr");
let mut lines = stderr.lines();
assert_eq!(lines.next(), Some(*expected_error), "{stderr}");
assert_eq!(lines.next(), Some("Usage:"), "{stderr}");
assert!(
stderr.contains("curate-macro --te-data <path> --series-map <path> --out <dir>"),
"{stderr}"
);
}
assert!(
!dir.0.join("out_from_mongo").exists(),
"out_from_mongo must not be created"
);
}
#[test]
fn cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel() {
let dir = TempDir::new("e2e-policy-rate");
let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0);
let baseline_out = dir.0.join("baseline_out");
let baseline_report = run_curate_macro(&CurateMacroArgs {
te_data: te_data_path.clone(),
series_map: series_map_path.clone(),
out_dir: baseline_out.clone(),
})
.expect("run library baseline");
let expected_stdout = format!("{}\n", format_curate_macro_report(&baseline_report));
let cli_out = dir.0.join("cli_out");
let result = cli()
.current_dir(&dir.0)
.args([
"--te-data",
"teData.bson",
"--series-map=macro_series_map.tsv",
"--out",
"cli_out",
])
.output()
.expect("run curate-macro");
assert!(result.status.success(), "{result:?}");
assert!(
result.stderr.is_empty(),
"unexpected stderr: {}",
String::from_utf8_lossy(&result.stderr)
);
let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout");
assert_eq!(stdout, expected_stdout);
let cli_parquet = cli_out.join("macro/part.parquet");
let baseline_parquet = baseline_out.join("macro/part.parquet");
assert!(cli_parquet.is_file(), "expected {}", cli_parquet.display());
assert_eq!(
fs::read(&cli_parquet).expect("read cli parquet"),
fs::read(&baseline_parquet).expect("read baseline parquet"),
"CLI Parquet output must match library runner bytes"
);
let reader = SerializedFileReader::new(File::open(&cli_parquet).expect("open parquet"))
.expect("open parquet reader");
let rows: Vec<Row> = reader
.get_row_iter(None)
.expect("row iter")
.map(|row| row.expect("decode row"))
.collect();
assert_eq!(
rows.len(),
1,
"expected exactly one mapped policy-rate row and no forecast sentinel row"
);
let expected_period_date = ymd_to_epoch_days(2024, 3, 20).expect("valid date");
let expected_known_at = i64::from(expected_period_date + POLICY_RATE_LAG_DAYS) * MICROS_PER_DAY;
assert_eq!(POLICY_RATE_LAG_DAYS, 1);
let row = &rows[0];
assert_eq!(col(row, "country_iso"), &Field::Str("US".to_string()));
assert_eq!(
col(row, "indicator"),
&Field::Str("fed_funds_rate".to_string())
);
assert_eq!(col(row, "period_date"), &Field::Date(expected_period_date));
assert_eq!(
col(row, "known_at"),
&Field::TimestampMicros(expected_known_at)
);
assert_eq!(
col(row, "known_at_source"),
&Field::Str("publication_lag_estimate".to_string())
);
assert_eq!(col(row, "value"), &Field::Double(5.5));
}
#[test]
fn cli_missing_te_data_exits_nonzero_with_single_line_escaped_error_and_no_parquet() {
let dir = TempDir::new("missing-te-data");
let (_, series_map_path) = write_policy_rate_fixture(&dir.0);
let missing_path = dir.0.join("missing\nte_data\r.bson");
let cli_out = dir.0.join("cli_out");
let result = cli()
.arg("--te-data")
.arg(&missing_path)
.arg("--series-map")
.arg(&series_map_path)
.arg("--out")
.arg(&cli_out)
.output()
.expect("run curate-macro");
assert_eq!(result.status.code(), Some(1), "{result:?}");
assert!(
result.stdout.is_empty(),
"unexpected stdout: {}",
String::from_utf8_lossy(&result.stdout)
);
let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr");
assert_eq!(
stderr.lines().count(),
1,
"expected 1 stderr line: {stderr:?}"
);
assert!(!stderr.contains('\r'), "stderr must escape CR: {stderr:?}");
assert!(stderr.starts_with("error: "), "{stderr:?}");
assert!(stderr.contains("te-data"), "{stderr:?}");
assert!(
stderr.contains("missing\\nte_data\\r.bson"),
"expected escaped path in stderr: {stderr:?}"
);
assert!(!stderr.contains("Usage:"), "{stderr:?}");
assert!(
!cli_out.join("macro/part.parquet").exists(),
"macro/part.parquet must not be written on failure"
);
assert!(!cli_out.exists(), "out dir must not be created on failure");
}
// ---- QA edge cases (T-202) ----
fn run_cli_paths(te_data: &Path, series_map: &Path, out: &Path) -> std::process::Output {
cli()
.arg("--te-data")
.arg(te_data)
.arg("--series-map")
.arg(series_map)
.arg("--out")
.arg(out)
.output()
.expect("run curate-macro")
}
#[test]
fn cli_help_lists_curate_macro_and_parse_errors_print_usage_without_writing() {
let help = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
.arg("--help")
.output()
.expect("run --help");
assert!(help.status.success(), "{help:?}");
let help_text = String::from_utf8(help.stdout).expect("utf-8 help");
assert!(
help_text.contains("curate-macro --te-data <path> --series-map <path> --out <dir>"),
"{help_text}"
);
let dir = TempDir::new("parse-error");
let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0);
let cli_out = dir.0.join("cli_out");
// `--mongo-uri` is not a file-mode flag; it must be rejected before any run.
let result = cli()
.arg("--te-data")
.arg(&te_data_path)
.arg("--series-map")
.arg(&series_map_path)
.arg("--out")
.arg(&cli_out)
.args(["--mongo-uri", "mongodb://user:secret@host:27017/stock"])
.output()
.expect("run curate-macro");
assert_eq!(result.status.code(), Some(1), "{result:?}");
assert!(result.stdout.is_empty(), "{result:?}");
let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr");
assert!(
stderr.starts_with("error: unknown flag '--mongo-uri' for curate-macro\n"),
"{stderr:?}"
);
assert!(stderr.contains("Usage:"), "{stderr:?}");
assert!(
!stderr.contains("secret"),
"rejected flag value must not be echoed: {stderr:?}"
);
assert!(
!cli_out.exists(),
"out dir must not be created on parse error"
);
}
#[test]
fn cli_runtime_failures_keep_existing_parquet_byte_identical() {
let dir = TempDir::new("preserve");
let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0);
let out = dir.0.join("out");
let first = run_cli_paths(&te_data_path, &series_map_path, &out);
assert!(first.status.success(), "{first:?}");
let parquet = out.join("macro/part.parquet");
let original = fs::read(&parquet).expect("read published parquet");
let bad_header = dir.0.join("bad_header.tsv");
fs::write(&bad_header, "not\ta\theader\n").expect("write bad tsv");
let corrupt_bson = dir.0.join("corrupt.bson");
// Declares a 64-byte document but provides only 8 bytes.
fs::write(&corrupt_bson, [64u8, 0, 0, 0, 1, 2, 3, 4]).expect("write corrupt bson");
let missing_map = dir.0.join("missing_map.tsv");
for (label, te, map, role) in [
("bad series-map header", &te_data_path, &bad_header, None),
(
"truncated teData",
&corrupt_bson,
&series_map_path,
Some("te-data"),
),
(
"missing series-map",
&te_data_path,
&missing_map,
Some("series-map"),
),
] {
let result = run_cli_paths(te, map, &out);
assert_eq!(result.status.code(), Some(1), "{label}: {result:?}");
assert!(result.stdout.is_empty(), "{label}: {result:?}");
let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr");
assert_eq!(stderr.lines().count(), 1, "{label}: {stderr:?}");
assert!(stderr.starts_with("error: "), "{label}: {stderr:?}");
assert!(!stderr.contains("Usage:"), "{label}: {stderr:?}");
if let Some(role) = role {
assert!(stderr.contains(role), "{label}: {stderr:?}");
}
assert_eq!(
fs::read(&parquet).expect("re-read parquet"),
original,
"{label}: failed run must not touch the published parquet"
);
}
}
#[test]
fn cli_rerun_on_same_inputs_is_byte_deterministic() {
let dir = TempDir::new("rerun");
let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0);
let out_a = dir.0.join("out_a");
let out_b = dir.0.join("out_b");
let a = run_cli_paths(&te_data_path, &series_map_path, &out_a);
let b = run_cli_paths(&te_data_path, &series_map_path, &out_b);
assert!(a.status.success() && b.status.success(), "{a:?} {b:?}");
assert_eq!(a.stdout, b.stdout);
assert_eq!(
fs::read(out_a.join("macro/part.parquet")).expect("read a"),
fs::read(out_b.join("macro/part.parquet")).expect("read b")
);
// Republishing into the same directory replaces the file with identical bytes.
let again = run_cli_paths(&te_data_path, &series_map_path, &out_a);
assert!(again.status.success(), "{again:?}");
assert_eq!(
fs::read(out_a.join("macro/part.parquet")).expect("read a again"),
fs::read(out_b.join("macro/part.parquet")).expect("read b")
);
}
#[test]
fn cli_unmapped_only_input_succeeds_and_matches_runner_report() {
let dir = TempDir::new("unmapped");
let te_data_path = dir.0.join("teData.bson");
let series_map_path = dir.0.join("macro_series_map.tsv");
let doc = make_te_data_doc(
"UNMAPPED",
"Atlantis",
"Interest Rate",
&[("2024-03-20", 1.25)],
&[],
);
fs::write(&te_data_path, doc.as_bytes()).expect("write teData");
fs::write(
&series_map_path,
format!(
"{MACRO_SERIES_MAP_HEADER}\nFDTR\tUnited States\tInterest Rate\tUS\tfed_funds_rate\tpolicy_rate\n"
),
)
.expect("write tsv");
let baseline_out = dir.0.join("baseline_out");
let baseline = run_curate_macro(&CurateMacroArgs {
te_data: te_data_path.clone(),
series_map: series_map_path.clone(),
out_dir: baseline_out.clone(),
})
.expect("library run");
assert_eq!(baseline.curate_stats.rows_out, 0);
let cli_out = dir.0.join("cli_out");
let result = run_cli_paths(&te_data_path, &series_map_path, &cli_out);
assert!(result.status.success(), "{result:?}");
assert!(result.stderr.is_empty(), "{result:?}");
assert_eq!(
String::from_utf8(result.stdout).expect("utf-8 stdout"),
format!("{}\n", format_curate_macro_report(&baseline))
);
assert_eq!(
cli_out.join("macro/part.parquet").exists(),
baseline_out.join("macro/part.parquet").exists(),
"CLI and runner must agree on zero-row publication"
);
}