diff --git a/design/README.md b/design/README.md index 978b8c69..c7dfa150 100644 --- a/design/README.md +++ b/design/README.md @@ -14,6 +14,8 @@ 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)** | Historical read-only Milestone `M2` completion audit prior to `T-205`–`T-207` (`T-204`; superseded by `m2-master-audit.md`) | Historical reference for pre-`T-205` M2 state | +| **[m2-master-audit.md](m2-master-audit.md)** | Current read-only Milestone `M2` audit against `master` (post-`T-205`/`T-206`/`T-207`), Done/Partial/Missing matrix, director trade-offs, and 7-task M2 closure backlog (`T-208`) | Before closing `M2`, queuing remaining `M2` tasks, or starting `M3` | --- diff --git a/design/m2-completion-audit.md b/design/m2-completion-audit.md new file mode 100644 index 00000000..19e06e5d --- /dev/null +++ b/design/m2-completion-audit.md @@ -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 `/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//v/` 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` & `/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 `/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'`, `/events` co-publishing & reader globs:** Change `EVENT_KIND_POST` in `tools/curate-etl/src/parquet_posts.rs` to `"ceo_post"`, co-publish `ceoPosts` under `/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//v/` (`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`. diff --git a/design/m2-gap-audit.md b/design/m2-gap-audit.md new file mode 100644 index 00000000..2f39185f --- /dev/null +++ b/design/m2-gap-audit.md @@ -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 `/events/year=YYYY/part.parquet` and fails closed (`RunCuratePostsError::EventsDatasetExists`) if `/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. diff --git a/design/m2-master-audit.md b/design/m2-master-audit.md new file mode 100644 index 00000000..8ec2b0c4 --- /dev/null +++ b/design/m2-master-audit.md @@ -0,0 +1,127 @@ +# Milestone M2 Master Audit & Closure Plan (T-208) + +**Bottom Line:** **HOLD M2 CLOSURE / HOLD M3 — Core M2 infrastructure is ~80% landed on current `master` (including `T-190` `send-ilp`, `T-205` `mcp:research-copilot`, `T-206` `curate-qm-bars-1m`, and `T-207` `curate-macro`), with 6 concrete code/wiring gaps and 1 host/`quant` verification gate remaining before M2 can close.** + +All sandbox-runnable TypeScript, ESLint, contract, and Rust native gates passed on local fixtures (including loopback TCP, with zero external network or QA DB contact; `0` errors, `0` warnings; `1,563` Rust tests across `58` suites and `1,050` targeted M2 Bun tests across `65` files). Exit Criterion 2 (2D PIT Q1-after-Q2 restatement non-overwrite) is **Done** in both Rust and real-DuckDB TypeScript fixtures; Exit Criteria 1 and 3 remain **Partial** pending event-kind/glob alignment, `MarketDataStore` read-path completions (`macroAsOf`, `crossSection`, `fx('1m')`), Python `stockbot` M2 parity, `notebook:snapshot` CLI + E2E test, and operator-run host/`quant` QuestDB `10.2.0` verification. + +> **Scope, Provenance & Constraints** +> - **Read-only, docs-only audit:** Only `design/m2-master-audit.md` and `design/README.md` are modified. Zero production code, schema, test, build config, or CI changes (project CI is off; zero CI workflows proposed). +> - **Audited `master` baseline vs. review branch:** Audited against `master` and `dev` at verified commit `d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52` (with accepted M1 `d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1` confirmed as an ancestor). The review branch is `feat/m2-audit` (prior review HEAD `efd73bda3b9937274be6a47663ac20010922cfbd`, superseded by this revision). When checking the audited baseline outside the sandbox, run `git rev-parse master` — not `git rev-parse HEAD` (which returns the `feat/m2-audit` documentation commit). +> - **Supersedes prior T-203/T-204 snapshots:** Unlike `design/m2-completion-audit.md` (T-204), current `master` (`d45014a1`) now includes `T-190` (`send-ilp`), `T-205` (`scripts/research-copilot-mcp.ts` + `"mcp:research-copilot"`), `T-206` (`curate-qm-bars-1m` CLI), and `T-207` (`curate-macro` CLI). Every status below was re-verified from current source files and test runs. +> - **Documentation path drift:** Canonical specs reside under `design/*.md`, 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` (lines 46–54) still reference `docs/*.md`. Cleanup is queued in `m2-ec1-snapshot-cli-and-doc-paths`. +> - **Strict database safety:** Zero connections to QA MongoDB (`27017/stock`) or QA PostgreSQL (`5432/trading_bot`). + +--- + +## 1. Baseline Verification: M1 (`d52aa20`), `T-127` & Option B Rust Architecture + +| Baseline Item | Verified State on `master` | Impact on M2 | +| --- | --- | --- | +| **Accepted M1 (`d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1`)** | Landed and intact: security-master & research SQL schemas (`database/postgres/init/34-security-master.sql`, `35-security-master-exchange-seed.sql`, `36-trial-ledger.sql`, `37-research-findings.sql`), Rust Option B `--from-mongo` runners for all 6 M1 commands (`tools/curate-etl/src/run_mongo.rs:1-100`, `mongo_stream.rs`, `mongo_safety.rs`), and Python `stockbot` M1 SDK (`python/stockbot/{__init__,calculations,data,ledger,signals,vault}.py`). | Solid foundation; M2 builds directly on these schemas, adapters, and `ReadOnlyMongoClient`. | +| **`T-127` (Deferred M1 Equity Eligibility & Vault File Isolation)** | Explicitly accepted as deferred in backlog per settled director decision (`d52aa20`). | **Non-blocking for M2.** Does not block EC-1, EC-2, or EC-3. | +| **Settled Rust ETL / `data-pipeline` Decision (Option B)** | Confirmed in `design/data-pipeline/rust-migration-evaluation.md` (including `2026-11-30` Addendum §§A.1–A.4): keep `apps/stock/data-pipeline` in TypeScript (`42` files, `20,349` LOC) for security master Passes 1–6, TSV export, probes, and BullMQ/Hono; keep bulk curation in Rust `tools/curate-etl` (`mongodb = "=3.10.2"` sync `RawDocumentBuf` cursors). | M2's 6 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`) still lack `--from-mongo` wiring in `tools/curate-etl/src/mongo_stream.rs:53-62` (currently 8 M1 collections only). | +| **Post-T-204 Merges (`T-190`, `T-205`, `T-206`, `T-207`)** | All four verified landed: `T-190` `send-ilp` (`tools/curate-etl/src/{ilp_send,cli,main}.rs`), `T-205` desktop MCP stdio entrypoint (`scripts/research-copilot-mcp.ts`, `package.json:56`, `scripts/test/research-copilot-mcp.test.ts`), `T-206` `curate-qm-bars-1m` (`tools/curate-etl/src/{run_curate_qm_bars_1m,cli,main}.rs`), and `T-207` `curate-macro` (`tools/curate-etl/src/{run_curate_macro,cli,main}.rs`). | Removes the T-204 desktop-launch and `curate-qm-bars-1m` CLI blockers. | + +--- + +## 2. Verification Gate Evidence & Research Governance + +### 2.1 Sandbox Local Fixture Runs (Programmer-Reported on `feat/m2-audit`, Including Loopback TCP — Zero External Network or QA DB Contact) + +| Gate / Suite | Command | Exit | 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,563` passed, `0` failed, `4` ignored across `58` suites (`engine` `150` passed + `curate-etl` unit & integration suites using local fixtures, including loopback TCP in `tools/curate-etl/tests/cli.rs:1787` for `send-ilp`, plus binary tests in `curate_qm_bars_1m.rs` and `curate_macro.rs`, `fundamentals_tests.rs`, `parquet_fundamentals_tests.rs`, and `run_curate_bars_1m_tests.rs`) | +| **Targeted M2 Suites** | `bun test scripts/test/research-copilot-mcp.test.ts scripts/test/security.test.ts libs/research/test/ libs/data/duckdb/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` | **PASS** — `1,050` pass, `0` fail (`80,699` expects, `65` files; includes `7/7` pass in `scripts/test/research-copilot-mcp.test.ts`, real-DuckDB `fundamentalsAsOf` restatement suite, and MCP Vault-fence suite) | +| **Python SDK** | `python3 -m pytest python/tests` | `1` | **SKIPPED (env)** — `/usr/bin/python3: No module named pytest` in sandbox | + +### 2.2 Audited Baseline, Studio Unsandboxed & Host-Only Verification Boundary + +| Verification Layer | Command / Scope | Status | Notes | +| --- | --- | :---: | --- | +| **Audited `master` Baseline Check** | `git rev-parse master` / `git rev-parse dev` | **Verified (`d45014a1`)** | Reviewer verified `master` and `dev` both at `d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52` with accepted M1 (`d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1`) as an ancestor; `feat/m2-audit` review HEAD is tracked separately. | +| **Studio Unsandboxed Runner (Audit Revision)** | `bun run build` and `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | **Authoritative post-handoff** | Prior revision passed Studio build `#1621` and test run `#1622`; Studio re-runs authoritatively on this revision covering workspace build, `audit:secrets`, worktree-git tooling tests (`scripts/test/`), integration tests, and isolated `stock_bot_safety*` PostgreSQL suites unreachable inside the sandbox. | +| **Future Host M2 Closure Revision** | `git rev-parse master` (at M2 closure), `CARGO_BUILD_JOBS=2 bun run check`, `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` | **PENDING (host closure)** | Future closure commit after M2 code tasks merge; required with retained logs in `design/m2-close-evidence.md` before M2 closure. | +| **`quant` (`10.0.0.51`) & Workstation Live Gates** | Read-only QA Mongo M2 field-shape probe, Quant Research-approved `curate-macro` `--series-map`, QuestDB `10.2.0` preflight (`vm.max_map_count`, `nofile`), bulk 3-feed intraday load + read-back reconciliation (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX`), `0x10` TCP ILP v2 commit, observed `NEXM.V`/`NVDA.US` split check, 1y `1m` PGWire latency, and desktop Claude Code + real `marimo` EC-1 receipt | **PENDING (host/`quant`)** | Tracked in `m2-host-quant-verification-and-closure` (with director replan flag in §4–§5). | + +### 2.3 Research Governance & Replay / Financial Invariants Verified + +- **Economic owner & durable inputs:** Quant data curation owns immutable Zstd Parquet partitions (`bars_1d`, `adj_factors`, `corporate_actions`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`, `macro`, `features//v`) and published QuestDB ILP v2 shard files; Quant Research owns the `curate-macro` `--series-map` series and lag-class selections (the approved TSV and its identifier must be retained with macro curation evidence); PostgreSQL owns append-only `trial_ledger`, `vault_evaluations`, `findings`, and `provider_caveats` (`database/postgres/init/36-trial-ledger.sql`, `37-research-findings.sql`, protected by `reject_research_evidence_mutation()`). +- **Holdout Vault & `known_at` boundaries:** Verified by `libs/research/test/mcp-query-data.test.ts` (rejects `scope`/`vault_evaluation_only`, clamps bounds strictly `< vaultCutoffTs`, drops leaky post-cutoff rows) and `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:40`, hardcoding `vaultOperatorAuthorized: false`). **Open FX `1m` availability gap:** `tools/curate-etl/src/run_curate_fx_1m.rs:24-26` preserves bar-start `ts` and `libs/data/questdb/src/schema.ts:33-47` defines `fx_1m` without `known_at`, so filtering on `ts` alone can leak an unclosed bar's close across a cutoff (director confirmation required in §4). +- **Baselines & single-source metrics:** `@stock-bot/calculations` (`144/144` tests passing) remains the sole authority for Sharpe/Sortino/IC/Newey-West/DSR/event-study/recency math; `RET_1D_V1` in `libs/research/src/feature-library.ts:29` documents its zero-return comparison baseline and zero-cost assumption. +- **2D PIT restatement & synthetic split-boundary conservation:** + - Q1 restated after Q2 never overwrites Q2 and updates TTM: verified in Rust (`tools/curate-etl/src/fundamentals_tests.rs:104` `restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2`, `parquet_fundamentals_tests.rs:1107` `restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`). + - `NVDA.US` (`10:1`) and `NEXM.V` (`1:20`) split-unadjustment conservation within `0.5%`: verified on **synthetic** fixtures (`tools/curate-etl/src/run_curate_bars_1m_tests.rs:402` `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes`); observed comparison against retained raw `bars_1d` closes remains open on `quant`. +- **Database safety & execution boundary:** Read-only MongoDB/PostgreSQL guards (`assertEnvironmentSafety()`, `MongoDBClient` `mongoReadOnly: true`, Rust `mongo_safety.rs` + sealed `ReadOnlyMongoClient`) remain intact. **Paper and live execution write access is strictly absent from all M2 MCP/research surfaces and remains out of scope until M5.** + +--- + +## 3. Milestone M2 Deliverables & Exit Criteria Matrix + +### 3.1 Deliverables (`design/MILESTONES.md` lines 87–98) + +| Deliverable | Status | Landed on `master` (Exact Paths, Symbols & Tests) | Missing / Remaining Gaps | +| --- | :---: | --- | --- | +| **M2.1** MCP Server & Notebook Snapshots | **Partial** | - **T-205 landed:** Runnable stdio entrypoint `runResearchCopilotMcp` in `scripts/research-copilot-mcp.ts:77`, `"mcp:research-copilot"` in `package.json:56`, `7/7` tests in `scripts/test/research-copilot-mcp.test.ts`.
- All 6 MCP tools (`search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`) in `libs/research/src/mcp/tools/` + `createResearchCopilotMcpServer` (`libs/research/src/mcp/copilot-server.ts`) + `parseResearchCopilotHostConfig` / `runResearchCopilotStdioHost` (`libs/research/src/mcp/host/stdio-host.ts`).
- Real Postgres executor (`openResearchCopilotExecutor` in `libs/data/postgres/src/research-copilot-executor.ts`) + real DuckDB store (`openResearchCopilotStore` in `libs/data/duckdb/src/research-copilot-store.ts:33`) + read-only `library.yml` card reader (`libs/research/src/mcp/adapters/library-cards.ts`) + `database/postgres/init/37-research-findings.sql`.
- `exportNotebookSnapshot` & Node subprocess adapter (`libs/research/src/notebook-snapshot.ts`, `libs/research/src/notebook-snapshot-node.ts:67`, `libs/research/test/notebook-snapshot*.test.ts`). | 1. `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:37`) and `stdio-host.ts:49-79` open DuckDB-only; optional `RESEARCH_MCP_QUESTDB_*` config + `createRoutedMarketDataStore` composition is missing.
2. `analyze_signal` (`libs/research/src/mcp/tools/analyze-signal.ts:121-123`) supports only `source: 'shorts' \| 'fundamentals'` (no `source: 'feature'` for versioned Feature Library signals).
3. No runnable `scripts/export-notebook-snapshot.ts` / `"notebook:snapshot"` CLI wrapping `@stock-bot/research/notebook-snapshot-node`.
4. No automated E2E stdio test covering `search_symbols` → `query_data` → `analyze_signal` → `event_study` (with `ceo_post`) → `exportNotebookSnapshot` → `file_finding` → `read_knowledge`.
5. No `apps/stock/web-api` SSE wrapper (recommended deferred to M4; see §4). | +| **M2.2** PIT Fundamentals, `ceoPosts` & Lagged `teData` | **Partial** | - File-mode Rust CLIs wired in `tools/curate-etl/src/cli.rs` & `main.rs`: `curate-fundamentals` (`cli.rs:102,1636`, `run_curate_fundamentals.rs`), `curate-posts` (`cli.rs:101,1317`, `run_curate_posts.rs`), and **T-207** `curate-macro` (`cli.rs:103,1689`, `run_curate_macro.rs`; binary tests in `tools/curate-etl/tests/curate_macro.rs:178` `cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage`, `:471` `cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel`, `:709` `cli_rerun_on_same_inputs_is_byte_deterministic`).
- Real-DuckDB `fundamentalsAsOf` (`libs/research/src/market-data-store-duckdb.ts:2287`, `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`).
- 2D PIT restatement tests (`fundamentals_tests.rs:104`, `parquet_fundamentals_tests.rs:1107`). | 1. **`ceoPosts` event-kind & partition mismatch:** `EVENT_KIND_POST = "post"` (`tools/curate-etl/src/parquet_posts.rs:22`) mismatches `'ceo_post'` expected by `market-data-store-duckdb.ts` and `python/stockbot/data.py:21`; `run_curate_posts.rs:133` fails with `EventsDatasetExists` when `/events` exists from `curate-events`; both `market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` glob only `events/year=*/part.parquet` instead of `events/year=*/*.parquet`.
2. `MarketDataStore.macroAsOf` throws `MarketDataStoreNotImplementedError` (`libs/research/src/market-data-store-duckdb.ts:2294-2296`).
3. `CurateFundamentalsArgs` (`tools/curate-etl/src/run_curate_fundamentals.rs:113-118`) accepts only a single `--qm-financials` path (no `--qm-financials-old` merge or `--curate-inputs` resolution).
4. `export-curate-inputs.ts:20-24` does not emit `listing_venues.tsv` (`us_tsx` / `tsxv_cse`).
5. `SourceCollection` (`mongo_stream.rs:53-62`), `RAW_BSON_EXPORT_COLLECTIONS` (`export-raw-bson.ts:11-20`), and `FIELD_SHAPE_PROBE_COLLECTIONS` (`source-field-shapes.ts:8-17`) allowlist only the 8 M1 collections (missing `qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`).
6. `python/stockbot/data.py` lacks `fundamentals_as_of` and `macro_as_of`. | +| **M2.3** QuestDB `10.2.0` Intraday & `send-ilp` | **Partial** | - **T-190 landed:** `send-ilp` multi-socket TCP sender (`tools/curate-etl/src/ilp_send.rs`, `cli.rs:104,2461`, `main.rs:22`, `ilp_send_tests.rs`; binary tests in `tools/curate-etl/tests/cli.rs:1747` `send_ilp_cli_help_missing_flag_success_and_partial_error_routing`, `:1877` `send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage`, `:1939` `send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr`).
- **T-206 landed:** `curate-qm-bars-1m` CLI (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`, `cli.rs:99,2277`, `main.rs:39`; binary tests in `tools/curate-etl/tests/curate_qm_bars_1m.rs:336` `curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants`, `:527` `curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards`, `:622` `curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped`) alongside `curate-bars-1m` (`cli.rs:98,2110`) and `curate-fx-1m` (`cli.rs:100,2381`).
- QuestDB `10.2.0` query layer, ILP v2 writer, and opt-in `M2_INTRADAY_SCHEMAS` / `getM2IntradayDDL()` (`libs/data/questdb/src/schema.ts:13-63,139`, `libs/data/questdb/test/`).
- Vault-fenced QuestDB `bars('1m')` reader (`libs/research/src/market-data-store-questdb.ts`) + `createRoutedMarketDataStore` (`libs/research/src/market-data-store-routed.ts`).
- `docker-compose.quant.yml:30-45` (`nofile: 1048576`, `QDB_RAM_USAGE_LIMIT_BYTES=21474836480`, `mem_limit: 28g`). | 1. `fx({ timeframe: '1m' })` throws `MarketDataStoreNotImplementedError` in TS (`libs/research/src/market-data-store-duckdb.ts:1529-1534`, delegated unchanged by `market-data-store-routed.ts:184-186`) and `NotImplementedError` in Python (`python/stockbot/data.py:258-259`); `market-data-store-questdb.ts` reads `bars_1m` only (no `fx_1m` reader). Moreover, `run_curate_fx_1m.rs:24-26` preserves bar-start `ts` and `fx_1m` (`schema.ts:33-47`) has no `known_at` column, so Vault fencing for both FX adapters requires a confirmed bar-close availability rule (see §4).
2. `getM2IntradayDDL()` (`libs/data/questdb/src/schema.ts:139`) is pure/opt-in with no runnable initializer script/helper wired to apply it.
3. No `--from-mongo` streaming in `mongo_stream.rs` / `run_mongo.rs` (and no allowlist entries in `export-raw-bson.ts` / `source-field-shapes.ts`) for `eodIntraday1M` (`3.40B`) or `qmIntraday` (`173.3M`).
4. Live `quant` preflight (`vm.max_map_count`, `nofile`), `0x10` binary-double TCP ILP acceptance (`ilp_send.rs:15-21`), bulk load & PGWire read-back reconciliation of all three approved feeds (`eodIntraday1M` US 2003–2025, `qmIntraday` CA/US 2024–2025, `CAD.FOREX` `1m` ~5.2M bars, including EOD/QM `(ts, listing_id)` overlap reconciliation), observed `NEXM.V`/`NVDA.US` split check, and 1y `1m` PGWire latency benchmark are unverified. | +| **M2.4** Versioned Feature Library (`D04` / `D11`) | **Partial** | - Declarative DuckDB SQL feature definitions, immutable `registerSignal`, Vault-fenced yearly Zstd Parquet `runFeatureBatch`, and built-in `RET_1D_V1` in `libs/research/src/feature-library.ts` (`libs/research/test/feature-library.test.ts`). | 1. `MarketDataStore.crossSection` throws `MarketDataStoreNotImplementedError` (`libs/research/src/market-data-store-duckdb.ts:2283-2285`), blocking read-back of `features//v/year=*/part.parquet`.
2. `FEATURE_INPUT_DATASETS` (`libs/research/src/feature-library.ts:61-68`) omits `'macro'` and `'corporate_actions'`.
3. Python `stockbot` (`python/stockbot/{__init__,data,signals}.py`) lacks `register_signal(...)`, batch feature materialization, and `cross_section(...)`. | + +### 3.2 Exit Criteria (`design/MILESTONES.md` lines 100–103) + +| Exit Criterion | Status | Verified Evidence & Remaining Work | +| --- | :---: | --- | +| **EC-1:** Desktop Claude Code via MCP executes a fundamental + alt-data signal study and event study end-to-end, exports a `marimo check`-clean static HTML snapshot, and files a finding. | **Partial** | **Landed:** `scripts/research-copilot-mcp.ts` (`mcp:research-copilot`) + all 6 MCP tools + `exportNotebookSnapshot`.
**Missing:** `ceo_post` event compatibility (`m2-ceo-posts-events-compat`), `notebook:snapshot` CLI + automated E2E stdio test (`m2-ec1-snapshot-cli-and-doc-paths`), and desktop Claude Code + real `marimo` session receipt (`m2-host-quant-verification-and-closure`). | +| **EC-2:** Restatement fixture test proves a restated Q1 (`known_at > Q2`) never overwrites Q2 in `fundamentalsAsOf`. | **Done (Offline Rust + Real-DuckDB)** | Proven offline in `tools/curate-etl/src/fundamentals_tests.rs:104`, `tools/curate-etl/src/parquet_fundamentals_tests.rs:1107`, and real-DuckDB `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`. Python `fundamentals_as_of` parity is tracked in `m2-python-sdk-m2-parity`. | +| **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 for one listing loads in `< 250 ms` warm / `< 1 s` cold. | **Partial (Synthetic Done; Live `quant` Missing)** | **Done (synthetic):** `tools/curate-etl/src/run_curate_bars_1m_tests.rs:402` (`split_boundary_nvda_and_nexm_match_raw_bars_1d_closes`).
**Missing (live `quant`):** Host/container `vm.max_map_count`/`nofile` preflight, `getM2IntradayDDL()` execution, QuestDB `10.2.0` `0x10` TCP ILP v2 commit check, bulk 3-feed load & PGWire read-back reconciliation (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX` + EOD/QM `(ts, listing_id)` overlap rule), observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` close check (`<= 0.5%`), and pinned 1-year single-listing PGWire latency benchmark (`< 250 ms` warm / `< 1 s` cold). | + +--- + +## 4. Concrete Blockers, Director Trade-Offs & Backlog Replan Flags + +Confirm these seven items (4 design trade-offs + 3 operational/environment prerequisites) and the **three backlog replan adjustments** below before coding/closing M2: + +### 4.1 Design Trade-Offs Requiring Director Confirmation + +1. **Option B `--from-mongo` for the 6 M2 collections vs. `.bson` staging:** Extend `tools/curate-etl` `SourceCollection` + `run_mongo.rs` with direct read-only MongoDB streaming for `qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, and `qmIntraday`, or stay on `.bson` staging files for M2? + - *Recommended:* Extend Option B `--from-mongo` to all 6 M2 collections (`m2-curate-etl-mongo-and-financials-old`) so `3.40B` `eodIntraday1M` rows never require `~500–832 GiB` of NVMe scratch space, while keeping file mode for offline tests. +2. **MCP stdio-only for M2 vs. `web-api` SSE wrapper:** Close M2 with the landed desktop stdio server (`bun run mcp:research-copilot`), or also add an HTTP/SSE wrapper inside `apps/stock/web-api` now? + - *Recommended:* Keep M2 stdio-only for desktop Claude Code (EC-1) and defer the network-isolated HTTP/SSE MCP endpoint to M4 containerized campaigns. +3. **`fundamentals_pit`-only vs. physical `fundamentals_bitemporal/part.parquet`:** Keep `curate-fundamentals` writing pre-resolved 2D PIT snapshots (`fundamentals_pit/year=YYYY/part.parquet`), or also materialize a separate raw `fundamentals_bitemporal/part.parquet` table in M2? + - *Recommended:* Keep `fundamentals_pit`-only for M2 (`DATA-CONTRACTS.md` §3A and EC-2 both target `fundamentalsAsOf` over `fundamentals_pit`), and materialize `fundamentals_bitemporal` only if a downstream M3/M4 use case requires unflattened multi-period history. +4. **`fx_1m` bar-close availability & Vault fencing rule *(Unresolved — blocks both TS & Python FX adapters)*:** `tools/curate-etl/src/run_curate_fx_1m.rs:24-26` preserves EODHD bar-start `ts` and `libs/data/questdb/src/schema.ts:33-47` defines `fx_1m` without a `known_at` column. Filtering on `ts` alone can return a bar whose start is before `vaultCutoffTs` (or `asOf`) while its close is at or after the cutoff, leaking an unobservable FX close. + - *Recommended:* Enforce bar-close availability in both TypeScript (`m2-store-macro-cross-section-fx1m`) and Python (`m2-python-sdk-m2-parity`) FX adapters (`bar_close = ts + 60s` strictly `< vaultCutoffTs` and `<= asOf`), backed by a boundary fixture proving a bar spanning or ending at `vaultCutoffTs` is excluded — keeping the `fx_1m` schema unchanged. (Alternative: add a `known_at` `TIMESTAMP` column to `fx_1m` DDL + ILP writer set to `ts + 60s`.) + +### 4.2 Operational & Environment Prerequisites + +5. **Live read-only QA MongoDB M2 field-shape probe & `curate-macro` `--series-map` ownership:** Run `probe-source-field-shapes.ts` read-only (`studio_stock_bot_read@stock`) once `m2-data-pipeline-m2-inputs-and-probes` allowlists the 6 M2 collections, to confirm live `ceoPosts` numeric timestamp unit (`Seconds` vs `Millis`), `qmFinancials`/`qmFinancials-old` metric paths, and `teData` labels before production curation. **Quant Research** owns the `teData` series selection and lag-class choices in the caller-supplied `--series-map` TSV; retain the approved mapping TSV and its version/hash identifier alongside the macro curation evidence in `design/m2-close-evidence.md`. +6. **`quant` (`10.0.0.51`) QuestDB `10.2.0` operator access:** Required for sysctl (`vm.max_map_count >= 1048576`) & container `nofile = 1048576` preflight, applying `getM2IntradayDDL()`, verifying `0x10` binary-double TCP ILP v2 commits via PGWire `wal_tables()`, loading and reconciling all three approved intraday feeds (`eodIntraday1M`, `qmIntraday`, `CAD.FOREX`), running the observed `NEXM.V`/`NVDA.US` split check, and timing the 1-year `1m` PGWire latency gate. +7. **Workstation `marimo` + desktop Claude Code setup:** Required on the operator workstation with `bun run mcp:research-copilot`, Studio `library.yml`, real `marimo`, and isolated PostgreSQL to record the EC-1 sign-off receipt. + +### 4.3 Substantive Backlog Replan Flags for Director (Before Merging Follow-Ups) + +The approved 7-key implementation backlog has three gaps discovered during audit review that should be replanned within the existing keys before scheduling: + +- **`m2-store-macro-cross-section-fx1m` & `m2-python-sdk-m2-parity` (FX `1m` availability boundary):** Add the confirmed `fx_1m` bar-close availability rule (item 4 above) and a boundary fixture in both TS and Python tests verifying bar-close observability and Vault exclusion for a minute bar spanning or ending at `vaultCutoffTs`. +- **`m2-ec1-snapshot-cli-and-doc-paths` (missing prerequisite):** Add `m2-ceo-posts-events-compat` to `dependsOn` (currently only `m2-store-macro-cross-section-fx1m`). Without it, the EC-1 integration task can start before `curate-posts` emits `'ceo_post'` and co-publishes alongside `curate-events`; require the E2E stdio test to consume co-published `curate-events` + `curate-posts` fixture output so `event_study` proves it reaches the curated CEO post. +- **`m2-host-quant-verification-and-closure` (bulk 3-feed intraday coverage & reconciliation):** Add acceptance requiring retained bulk load and PGWire read-back evidence in QuestDB for all three approved feeds from `design/MILESTONES.md:96` — `eodIntraday1M` (US equity 2003–2025), `qmIntraday` (CA/US equity 2024–2025), and `CAD.FOREX` `1m` (~5.2M bars) — recording source/date coverage, row counts, skipped/dropped counts, and the explicit reconciliation/precedence rule where EOD and QM share a `(ts, listing_id)` dedup key in `bars_1m`. + +--- + +## 5. Ordered M2 Closure Backlog (7 Tasks) + +Aligned 1-to-1 with the approved implementation backlog keys (with the three director replan flags marked inline): + +| Order | Key | Task | Depends On | Primary Acceptance | +| :---: | --- | --- | --- | --- | +| **1** | `m2-ceo-posts-events-compat` | **M2.2u** — Fix `ceoPosts` event kind (`'ceo_post'`) and co-publish under `/events` | *(none)* | `EVENT_KIND_POST = "ceo_post"`; non-clobbering `events/year=YYYY/part-posts.parquet`; TS (`market-data-store-duckdb.ts`) & Python (`data.py`) glob `events/year=*/*.parquet` verified in real-DuckDB combined filing/earnings/`ceo_post` test. | +| **2** | `m2-store-macro-cross-section-fx1m` | **M2.3s** — Implement `MarketDataStore.macroAsOf`, `crossSection`, QuestDB `fx('1m')`, and copilot `1m` routing | *(none)* | Vault-fenced DuckDB `macroAsOf` & `crossSection` tests; QuestDB `fx_1m` reader + `createRoutedMarketDataStore` `fx('1m')` routing + `getM2IntradayDDL()` initializer; optional `RESEARCH_MCP_QUESTDB_*` in `stdio-host.ts`/`openResearchCopilotStore`; `analyze_signal` `source: 'feature'` + `FEATURE_INPUT_DATASETS` (`'macro'`, `'corporate_actions'`). **[Director replan §4.3: confirm `fx_1m` bar-close availability rule + add cutoff-spanning/ending boundary fixture.]** | +| **3** | `m2-data-pipeline-m2-inputs-and-probes` | **M2.2v** — Export `listing_venues.tsv` and extend field-shape probe & BSON fixture exporter for M2 collections | *(none)* | Atomic `listing_venues.tsv` (`us_tsx` / `tsxv_cse`) in `export-curate-inputs.ts`; all 14 M1+M2 collections allowlisted in `source-field-shapes.ts` & `export-raw-bson.ts` with `mongoReadOnly: true`. | +| **4** | `m2-curate-etl-mongo-and-financials-old` | **M2.3t** — Add `--qm-financials-old` merge and Option B `--from-mongo` streaming for M2 collections in `curate-etl` | `m2-ceo-posts-events-compat`, `m2-data-pipeline-m2-inputs-and-probes` | `curate-fundamentals` `--qm-financials-old` + `--curate-inputs`; sealed read-only `--from-mongo` streaming for all 6 M2 collections with byte-identical offline parity tests and zero new crates. | +| **5** | `m2-python-sdk-m2-parity` | **M2.4b** — Add Python `stockbot` `register_signal`, batch feature runner, and M2 `MarketDataStore` methods | `m2-ceo-posts-events-compat`, `m2-store-macro-cross-section-fx1m` | Vault-fenced `fundamentals_as_of`, `macro_as_of`, `cross_section`, optional QuestDB `1m` `bars`/`fx`, and `register_signal(...)` writing contract Zstd Parquet readable identically by TS and Python. **[Director replan §4.3: enforce confirmed `fx_1m` bar-close availability rule + cutoff-spanning/ending boundary fixture.]** | +| **6** | `m2-ec1-snapshot-cli-and-doc-paths` | **M2.1w** — Add notebook snapshot CLI, MCP E2E study+snapshot+finding test, and fix `docs/` → `design/` path drift | `m2-store-macro-cross-section-fx1m`, **`m2-ceo-posts-events-compat` *(replan §4.3)*** | Fail-closed `scripts/export-notebook-snapshot.ts` (`"notebook:snapshot"`); E2E stdio MCP test (`search_symbols` → `file_finding` + snapshot) consuming **co-published `curate-events` + `curate-posts` fixture output** so `event_study` reaches the curated `ceo_post`; `docs/*.md` → `design/*.md` updated in `AGENTS.md`, `CLAUDE.md`, `README.md`, `studio.config.json`, `tools/curate-etl/README.md`. | +| **7** | `m2-host-quant-verification-and-closure` | **M2.5** — Execute host/`quant` M2 preflight, bulk 3-feed intraday load, observed split-boundary & latency checks, and desktop Claude Code EC-1 sign-off | `m2-curate-etl-mongo-and-financials-old`, `m2-python-sdk-m2-parity`, `m2-ec1-snapshot-cli-and-doc-paths` | Retained host `git rev-parse master`, `CARGO_BUILD_JOBS=2 bun run check` + `test/postgres/` + live read-only M2 probe + Quant Research-approved `curate-macro` `--series-map` TSV/ID + `quant` QuestDB `10.2.0` preflight/`0x10` ILP/observed `NEXM.V` & `NVDA.US` split/latency checks + desktop Claude Code EC-1 receipt in `design/m2-close-evidence.md`, marking M2 closed in `design/MILESTONES.md`. **[Director replan §4.3: require retained bulk load + PGWire read-back reconciliation for EOD equity, QM equity, and `CAD.FOREX` FX — source/date coverage, row counts, skips, and EOD/QM `(ts, listing_id)` overlap precedence rule.]** | diff --git a/libs/data/postgres/src/index.ts b/libs/data/postgres/src/index.ts index eadd1545..de560c90 100644 --- a/libs/data/postgres/src/index.ts +++ b/libs/data/postgres/src/index.ts @@ -1,6 +1,21 @@ export { PostgreSQLClient } from './client'; export { PostgreSQLTransactionManager } from './transactions'; export { runPostgresMigrations, type MigrationTrack } from './migrations'; +export { + RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, + RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, + RESEARCH_COPILOT_PG_POOL_MAX, + RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, + RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, + ResearchCopilotExecutorError, + openResearchCopilotExecutor, + type ManagedResearchCopilotExecutor, + type ResearchCopilotExecutor, + type ResearchCopilotExecutorConfig, + type ResearchCopilotExecutorDeps, + type ResearchCopilotExecutorErrorCode, + type ResearchCopilotExecutorPool, +} from './research-copilot-executor'; export type { ConnectionEvents, PoolMetrics, diff --git a/libs/data/postgres/src/research-copilot-executor.ts b/libs/data/postgres/src/research-copilot-executor.ts new file mode 100644 index 00000000..cd55c3b7 --- /dev/null +++ b/libs/data/postgres/src/research-copilot-executor.ts @@ -0,0 +1,379 @@ +/** + * Real PostgreSQL executor factory for the MCP research copilot stdio host. + * + * Opens a bounded `pg.Pool` (`max: 4`, 5 s connect timeout, 10 s statement + * timeout, 15 s driver query timeout, 2 s lock timeout), verifies connectivity + * with a single `SELECT 1` probe, attaches an idle-client `'error'` listener, + * and returns a managed `{ executor, close }` handle structurally assignable + * to `ManagedPostgresExecutor` in `@stock-bot/research/mcp` without importing + * `@stock-bot/research` at runtime. + * + * All errors thrown by this module are {@link ResearchCopilotExecutorError} + * instances with fixed, sanitized messages and no `cause`, so connection + * strings, credentials, hostnames, and raw `pg` error text never leak. + * PostgreSQL unique-violation SQLSTATE `'23505'` is preserved on sanitized + * query errors for `createPostgresFindingWritePort` idempotent retries. + */ + +import { Pool, type PoolConfig } from 'pg'; + +/** Maximum number of PostgreSQL connections in the copilot executor pool. */ +export const RESEARCH_COPILOT_PG_POOL_MAX = 4; + +/** TCP/startup connection timeout in milliseconds. */ +export const RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS = 5_000; + +/** Server-side PostgreSQL `statement_timeout` in milliseconds. */ +export const RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS = 10_000; + +/** Driver-side `pg` `query_timeout` in milliseconds. */ +export const RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS = 15_000; + +/** Server-side PostgreSQL `lock_timeout` in milliseconds. */ +export const RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS = 2_000; + +/** Typed error codes emitted by {@link ResearchCopilotExecutorError}. */ +export type ResearchCopilotExecutorErrorCode = + | 'INVALID_CONFIG' + | 'OPEN_FAILED' + | 'QUERY_FAILED' + | 'EXECUTOR_CLOSED' + | 'CLOSE_FAILED' + | '23505'; + +const ERROR_MESSAGES: Readonly> = { + INVALID_CONFIG: + 'Invalid PostgreSQL configuration: expected a postgres:// or postgresql:// URL with an explicit host and database.', + OPEN_FAILED: 'Failed to open PostgreSQL executor for research copilot.', + QUERY_FAILED: 'PostgreSQL query failed in research copilot executor.', + EXECUTOR_CLOSED: 'Research copilot PostgreSQL executor is closed.', + CLOSE_FAILED: 'Failed to close PostgreSQL executor for research copilot.', + '23505': 'PostgreSQL unique constraint violation in research copilot executor.', +}; + +const STRIPPED_TIMEOUT_PARAMS: ReadonlySet = new Set([ + 'statement_timeout', + 'lock_timeout', + 'query_timeout', + 'connect_timeout', + 'connectiontimeoutmillis', +]); + +const POSTGRES_URL_PREFIX_RE = /^postgres(?:ql)?:\/\//i; +const PORT_DIGITS_RE = /^\d+$/; +const CONTROL_CHAR_RE = /[\r\n\0]/; + +/** + * Sanitized error thrown by {@link openResearchCopilotExecutor} and the + * managed executor it returns. Never attaches a raw `cause` or embeds DSNs, + * credentials, hostnames, or raw driver messages. + */ +export class ResearchCopilotExecutorError extends Error { + readonly code: ResearchCopilotExecutorErrorCode; + + constructor(code: ResearchCopilotExecutorErrorCode, message: string) { + super(message); + this.name = 'ResearchCopilotExecutorError'; + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Configuration accepted by {@link openResearchCopilotExecutor}. */ +export interface ResearchCopilotExecutorConfig { + readonly postgresUrl: string; +} + +/** Minimal `pg.Pool` surface required by {@link openResearchCopilotExecutor}. */ +export interface ResearchCopilotExecutorPool { + query(text: string, values?: unknown[]): Promise<{ readonly rows: readonly unknown[] }>; + end(): Promise; + on(event: 'error', listener: (error: Error) => void): unknown; +} + +/** Optional dependency injection hooks for {@link openResearchCopilotExecutor}. */ +export interface ResearchCopilotExecutorDeps { + readonly createPool?: (poolConfig: PoolConfig) => ResearchCopilotExecutorPool; +} + +/** Structural query executor compatible with MCP research copilot PostgreSQL adapters. */ +export interface ResearchCopilotExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }>; +} + +/** Managed executor handle structurally assignable to `ManagedPostgresExecutor`. */ +export interface ManagedResearchCopilotExecutor { + readonly executor: ResearchCopilotExecutor; + close(): Promise; +} + +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) || + !POSTGRES_URL_PREFIX_RE.test(rawUrl) + ) { + throw invalidConfigError(); + } + + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch { + throw invalidConfigError(); + } + + if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { + throw invalidConfigError(); + } + + const hostQueryParams = parsed.searchParams.getAll('host'); + if (hostQueryParams.length > 1) { + throw invalidConfigError(); + } + const queryHost = hostQueryParams.length === 1 ? (hostQueryParams[0] as string).trim() : ''; + if (hostQueryParams.length === 1 && queryHost.length === 0) { + throw invalidConfigError(); + } + + const hasAuthorityHost = parsed.hostname.length > 0; + if (hasAuthorityHost) { + let decodedHost: string; + try { + decodedHost = decodeURIComponent(parsed.hostname); + } catch { + throw invalidConfigError(); + } + if (decodedHost.trim().length === 0) { + throw invalidConfigError(); + } + } + + if (!hasAuthorityHost && queryHost.length === 0) { + throw invalidConfigError(); + } + + if (parsed.port.length > 0) { + 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) { + throw invalidConfigError(); + } + const rawDatabase = parsed.pathname.slice(1); + if (rawDatabase.includes('/')) { + throw invalidConfigError(); + } + let decodedDatabase: string; + try { + decodedDatabase = decodeURIComponent(rawDatabase); + } catch { + throw invalidConfigError(); + } + if (decodedDatabase.trim().length === 0) { + throw invalidConfigError(); + } + + try { + if (parsed.username.length > 0) { + decodeURIComponent(parsed.username); + } + if (parsed.password.length > 0) { + decodeURIComponent(parsed.password); + } + } catch { + throw invalidConfigError(); + } + + const existingOptions: string[] = []; + const keysToDelete: string[] = []; + for (const [key, value] of parsed.searchParams.entries()) { + const lower = key.toLowerCase(); + if (lower === 'options') { + const trimmed = value.trim(); + if (trimmed.length > 0) { + existingOptions.push(trimmed); + } + keysToDelete.push(key); + } else if (STRIPPED_TIMEOUT_PARAMS.has(lower)) { + keysToDelete.push(key); + } + } + for (let i = 0; i < keysToDelete.length; i += 1) { + parsed.searchParams.delete(keysToDelete[i] as string); + } + + const envOptions = typeof process.env.PGOPTIONS === 'string' ? process.env.PGOPTIONS.trim() : ''; + const baseOptions = existingOptions.length > 0 ? existingOptions.join(' ') : envOptions; + + const poolConfig: PoolConfig = { + connectionString: parsed.toString(), + max: RESEARCH_COPILOT_PG_POOL_MAX, + connectionTimeoutMillis: RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, + statement_timeout: RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, + query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, + lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, + }; + + if (baseOptions.length > 0) { + poolConfig.options = `${baseOptions} -c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`; + } + + return poolConfig; +} + +function resolveCreatePool( + deps?: ResearchCopilotExecutorDeps +): (poolConfig: PoolConfig) => ResearchCopilotExecutorPool { + if (deps === undefined) { + return poolConfig => new Pool(poolConfig); + } + if (typeof deps !== 'object' || deps === null) { + throw invalidConfigError(); + } + if (deps.createPool === undefined) { + return poolConfig => new Pool(poolConfig); + } + if (typeof deps.createPool !== 'function') { + throw invalidConfigError(); + } + return deps.createPool; +} + +function getPostgresErrorCode(error: unknown): string | undefined { + if (typeof error === 'object' && error !== null) { + const code = (error as { readonly code?: unknown }).code; + if (typeof code === 'string') { + return code; + } + } + return undefined; +} + +async function safeEndPool(pool: ResearchCopilotExecutorPool): Promise { + try { + await pool.end(); + } catch { + // Best-effort cleanup during failed startup; preserve primary OPEN_FAILED error. + } +} + +/** + * Opens a bounded, probed PostgreSQL executor for the MCP research copilot + * stdio host. + */ +export async function openResearchCopilotExecutor( + config: ResearchCopilotExecutorConfig, + deps?: ResearchCopilotExecutorDeps +): Promise { + const poolConfig = parseAndNormalizePoolConfig(config); + const createPool = resolveCreatePool(deps); + + let pool: ResearchCopilotExecutorPool; + try { + pool = createPool(poolConfig); + } catch { + throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED); + } + + if ( + typeof pool !== 'object' || + pool === null || + typeof pool.query !== 'function' || + typeof pool.end !== 'function' || + typeof pool.on !== 'function' + ) { + throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED); + } + + try { + // Keep idle-client disconnects from becoming unhandled EventEmitter errors. + pool.on('error', () => { + // Intentionally absorbed; subsequent queries surface sanitized QUERY_FAILED errors. + }); + await pool.query('SELECT 1'); + } catch { + await safeEndPool(pool); + throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED); + } + + let closed = false; + let closePromise: Promise | null = null; + + const executor: ResearchCopilotExecutor = { + async query>( + text: string, + params?: readonly unknown[] + ): Promise<{ readonly rows: readonly Row[] }> { + if (closed) { + throw new ResearchCopilotExecutorError('EXECUTOR_CLOSED', ERROR_MESSAGES.EXECUTOR_CLOSED); + } + + let rawResult: { readonly rows: readonly unknown[] }; + try { + rawResult = + params === undefined ? await pool.query(text) : await pool.query(text, [...params]); + } catch (error) { + if (getPostgresErrorCode(error) === '23505') { + throw new ResearchCopilotExecutorError('23505', ERROR_MESSAGES['23505']); + } + throw new ResearchCopilotExecutorError('QUERY_FAILED', ERROR_MESSAGES.QUERY_FAILED); + } + + if ( + typeof rawResult !== 'object' || + rawResult === null || + !Array.isArray(rawResult.rows) + ) { + throw new ResearchCopilotExecutorError('QUERY_FAILED', ERROR_MESSAGES.QUERY_FAILED); + } + + return { rows: rawResult.rows as readonly Row[] }; + }, + }; + + const close = (): Promise => { + closed = true; + if (closePromise === null) { + closePromise = Promise.resolve() + .then(() => pool.end()) + .catch(() => { + throw new ResearchCopilotExecutorError('CLOSE_FAILED', ERROR_MESSAGES.CLOSE_FAILED); + }); + } + return closePromise; + }; + + return { executor, close }; +} diff --git a/libs/data/postgres/test/research-copilot-executor-edge.test.ts b/libs/data/postgres/test/research-copilot-executor-edge.test.ts new file mode 100644 index 00000000..f126bd50 --- /dev/null +++ b/libs/data/postgres/test/research-copilot-executor-edge.test.ts @@ -0,0 +1,428 @@ +import { readFileSync } from 'node:fs'; +import { createServer, type AddressInfo, type Socket } from 'node:net'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Client, Pool, type PoolConfig } from 'pg'; +import { + RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, + RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, + RESEARCH_COPILOT_PG_POOL_MAX, + RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, + RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, + ResearchCopilotExecutorError, + type ResearchCopilotExecutorPool, + openResearchCopilotExecutor, +} from '../src/index'; + +const cleanup: Array<() => Promise | void> = []; +afterEach(async () => { + for (const fn of cleanup.splice(0).reverse()) { + await fn(); + } +}); + +describe('openResearchCopilotExecutor edge cases', () => { + test('strips URL timeout overrides while preserving search_path and enforcing executor timeouts', async () => { + const capturedConfigs: PoolConfig[] = []; + const fakePool: ResearchCopilotExecutorPool = { + async query() { + return { rows: [{ '?column?': 1 }] }; + }, + async end() {}, + on() { + return fakePool; + }, + }; + + const hostileUrl = + 'postgres://u:p@127.0.0.1:5432/research_db' + + '?sslmode=disable' + + '&application_name=copilot_edge' + + '&statement_timeout=99999' + + '&LOCK_TIMEOUT=88888' + + '&query_timeout=77777' + + '&connect_timeout=66' + + '&connectionTimeoutMillis=55555' + + '&options=-c%20search_path%3Disolated_schema%20-c%20statement_timeout%3D60000%20-c%20lock_timeout%3D60000'; + + const handle = await openResearchCopilotExecutor( + { postgresUrl: hostileUrl }, + { + createPool(poolConfig) { + capturedConfigs.push(poolConfig); + return fakePool; + }, + } + ); + + expect(capturedConfigs).toHaveLength(1); + const poolConfig = capturedConfigs[0]!; + const normalizedUrl = new URL(poolConfig.connectionString!); + expect(normalizedUrl.searchParams.get('sslmode')).toBe('disable'); + expect(normalizedUrl.searchParams.get('application_name')).toBe('copilot_edge'); + expect(normalizedUrl.searchParams.has('statement_timeout')).toBe(false); + expect(normalizedUrl.searchParams.has('LOCK_TIMEOUT')).toBe(false); + expect(normalizedUrl.searchParams.has('query_timeout')).toBe(false); + expect(normalizedUrl.searchParams.has('connect_timeout')).toBe(false); + expect(normalizedUrl.searchParams.has('connectionTimeoutMillis')).toBe(false); + expect(normalizedUrl.searchParams.has('options')).toBe(false); + + expect(poolConfig.options).toBe( + `-c search_path=isolated_schema -c statement_timeout=60000 -c lock_timeout=60000 ` + + `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` + ); + + // Verify pg's own ConnectionParameters parser resolves the enforced timeouts. + const client = new Client(poolConfig); + const params = ( + client as unknown as { + connectionParameters: { + statement_timeout?: unknown; + lock_timeout?: unknown; + query_timeout?: unknown; + connect_timeout?: unknown; + options?: string; + application_name?: string; + }; + } + ).connectionParameters; + + expect(params.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); + expect(params.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); + expect(params.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); + expect(params.connect_timeout).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS / 1000); + expect(params.application_name).toBe('copilot_edge'); + expect(params.options).toBe(poolConfig.options); + + await handle.close(); + }); + + test('accepts Unix-domain socket host query parameter and resolves domain-socket parameters in pg', async () => { + const capturedConfigs: PoolConfig[] = []; + const fakePool: ResearchCopilotExecutorPool = { + async query() { + return { rows: [{ '?column?': 1 }] }; + }, + async end() {}, + on() { + return fakePool; + }, + }; + + const handle = await openResearchCopilotExecutor( + { + postgresUrl: + 'postgres:///research_db?host=/var/run/postgresql&statement_timeout=99999&lock_timeout=88888', + }, + { + createPool(poolConfig) { + capturedConfigs.push(poolConfig); + return fakePool; + }, + } + ); + + expect(capturedConfigs).toHaveLength(1); + const client = new Client(capturedConfigs[0]); + const params = ( + client as unknown as { + connectionParameters: { + host?: string; + database?: string; + isDomainSocket?: boolean; + statement_timeout?: unknown; + lock_timeout?: unknown; + query_timeout?: unknown; + }; + } + ).connectionParameters; + + expect(params.host).toBe('/var/run/postgresql'); + expect(params.database).toBe('research_db'); + expect(params.isDomainSocket).toBe(true); + expect(params.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); + expect(params.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); + expect(params.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); + + await handle.close(); + }); + + test('rejects URLs missing host or database even when PGHOST and PGDATABASE are set', async () => { + const previousPgHost = process.env.PGHOST; + const previousPgDatabase = process.env.PGDATABASE; + process.env.PGHOST = '127.0.0.1'; + process.env.PGDATABASE = 'fallback_db'; + cleanup.push(() => { + if (previousPgHost === undefined) { + delete process.env.PGHOST; + } else { + process.env.PGHOST = previousPgHost; + } + if (previousPgDatabase === undefined) { + delete process.env.PGDATABASE; + } else { + process.env.PGDATABASE = previousPgDatabase; + } + }); + + let createPoolCalls = 0; + for (const postgresUrl of [ + 'postgres:///research_db', + 'postgres://127.0.0.1:5432/', + 'postgres://127.0.0.1:5432', + ]) { + await expect( + openResearchCopilotExecutor( + { postgresUrl }, + { + createPool() { + createPoolCalls += 1; + return { + async query() { + return { rows: [] }; + }, + async end() {}, + on() { + return undefined; + }, + }; + }, + } + ) + ).rejects.toMatchObject({ + name: 'ResearchCopilotExecutorError', + code: 'INVALID_CONFIG', + }); + } + expect(createPoolCalls).toBe(0); + }); + + test('preserves PGOPTIONS startup precedence while enforcing executor timeouts', async () => { + const previousPgOptions = process.env.PGOPTIONS; + cleanup.push(() => { + if (previousPgOptions === undefined) { + delete process.env.PGOPTIONS; + } else { + process.env.PGOPTIONS = previousPgOptions; + } + }); + + const fakePool: ResearchCopilotExecutorPool = { + async query() { + return { rows: [{ '?column?': 1 }] }; + }, + async end() {}, + on() { + return fakePool; + }, + }; + + // 1. No URL options and no PGOPTIONS -> PoolConfig.options omitted. + delete process.env.PGOPTIONS; + let captured: PoolConfig | undefined; + const h1 = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, + { + createPool(poolConfig) { + captured = poolConfig; + return fakePool; + }, + } + ); + expect(captured?.options).toBeUndefined(); + const c1 = new Client(captured); + const p1 = ( + c1 as unknown as { + connectionParameters: { + options?: string; + statement_timeout?: unknown; + lock_timeout?: unknown; + }; + } + ).connectionParameters; + expect(p1.options).toBeUndefined(); + expect(p1.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); + expect(p1.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); + await h1.close(); + + // 2. PGOPTIONS set with no URL options -> PGOPTIONS preserved + executor timeouts appended. + process.env.PGOPTIONS = '-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888'; + captured = undefined; + const h2 = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, + { + createPool(poolConfig) { + captured = poolConfig; + return fakePool; + }, + } + ); + expect(captured?.options).toBe( + `-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888 ` + + `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` + ); + const c2 = new Client(captured); + const p2 = ( + c2 as unknown as { connectionParameters: { options?: string } } + ).connectionParameters; + expect(p2.options).toBe(captured?.options); + await h2.close(); + + // 3. Both URL options and PGOPTIONS set -> URL options wins over PGOPTIONS, timeouts still appended. + process.env.PGOPTIONS = '-c search_path=env_schema'; + captured = undefined; + const h3 = await openResearchCopilotExecutor( + { + postgresUrl: + 'postgres://127.0.0.1:5432/research_db?options=-c%20search_path%3Durl_schema', + }, + { + createPool(poolConfig) { + captured = poolConfig; + return fakePool; + }, + } + ); + expect(captured?.options).toBe( + `-c search_path=url_schema ` + + `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` + ); + await h3.close(); + }); + + test('absorbs idle-client pool error events without crashing the process', async () => { + const errorListeners: Array<(error: Error) => void> = []; + const fakePool: ResearchCopilotExecutorPool = { + async query(text) { + return { rows: [{ sql: text }] }; + }, + async end() {}, + on(event, listener) { + if (event === 'error') { + errorListeners.push(listener); + } + return fakePool; + }, + }; + + const handle = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, + { createPool: () => fakePool } + ); + + expect(errorListeners).toHaveLength(1); + expect(() => errorListeners[0]!(new Error('idle client disconnected'))).not.toThrow(); + + const res = await handle.executor.query<{ sql: string }>('SELECT 2'); + expect(res.rows).toEqual([{ sql: 'SELECT 2' }]); + await handle.close(); + }); + + test('deduplicates concurrent close() calls and rejects queries started during shutdown', async () => { + let resolveEnd!: () => void; + let endCalls = 0; + let queryCalls = 0; + + const fakePool: ResearchCopilotExecutorPool = { + async query() { + queryCalls += 1; + return { rows: [] }; + }, + end() { + endCalls += 1; + return new Promise(resolve => { + resolveEnd = resolve; + }); + }, + on() { + return fakePool; + }, + }; + + const handle = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, + { createPool: () => fakePool } + ); + expect(queryCalls).toBe(1); + + const closeA = handle.close(); + const closeB = handle.close(); + + // Even while pool.end() is still in flight, new queries must reject immediately. + await expect(handle.executor.query('SELECT 2')).rejects.toMatchObject({ + name: 'ResearchCopilotExecutorError', + code: 'EXECUTOR_CLOSED', + }); + expect(queryCalls).toBe(1); + expect(endCalls).toBe(1); + + resolveEnd(); + await Promise.all([closeA, closeB]); + expect(endCalls).toBe(1); + }); + + test('rejects with sanitized OPEN_FAILED when a real pg.Pool times out against a silent loopback listener', async () => { + const sockets = new Set(); + const server = createServer(socket => { + sockets.add(socket); + socket.on('close', () => sockets.delete(socket)); + // Intentionally accept and never reply so pg hits its connection timeout. + }); + + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => resolve()); + }); + cleanup.push(async () => { + for (const socket of sockets) { + socket.destroy(); + } + await new Promise(resolve => server.close(() => resolve())); + }); + + const { port } = server.address() as AddressInfo; + const secretPass = 'LoopbackSecretPass99'; + const loopbackUrl = `postgres://loopback_user:${secretPass}@127.0.0.1:${port}/research_db`; + + let observedConfig: PoolConfig | undefined; + let caught: unknown; + try { + await openResearchCopilotExecutor( + { postgresUrl: loopbackUrl }, + { + createPool(poolConfig) { + observedConfig = poolConfig; + // Keep the default config assertions intact, but tighten connect timeout for fast local test execution. + return new Pool({ + ...poolConfig, + connectionTimeoutMillis: 150, + }); + }, + } + ); + } catch (err) { + caught = err; + } + + expect(observedConfig?.max).toBe(RESEARCH_COPILOT_PG_POOL_MAX); + expect(observedConfig?.connectionTimeoutMillis).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS); + expect(observedConfig?.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); + expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); + const typed = caught as ResearchCopilotExecutorError; + expect(typed.code).toBe('OPEN_FAILED'); + expect((typed as { cause?: unknown }).cause).toBeUndefined(); + expect(typed.message).not.toContain('loopback_user'); + expect(typed.message).not.toContain(secretPass); + expect(typed.message).not.toContain('127.0.0.1'); + expect(typed.message).not.toContain(String(port)); + }); + + test('has no runtime import of @stock-bot/research', () => { + const sourcePath = fileURLToPath( + new URL('../src/research-copilot-executor.ts', import.meta.url) + ); + const source = readFileSync(sourcePath, 'utf8'); + expect(source).not.toMatch(/from\s+['"]@stock-bot\/research/); + expect(source).not.toMatch(/require\(\s*['"]@stock-bot\/research/); + }); +}); diff --git a/libs/data/postgres/test/research-copilot-executor.test.ts b/libs/data/postgres/test/research-copilot-executor.test.ts new file mode 100644 index 00000000..c014d210 --- /dev/null +++ b/libs/data/postgres/test/research-copilot-executor.test.ts @@ -0,0 +1,423 @@ +import { describe, expect, test } from 'bun:test'; +import type { PoolConfig } from 'pg'; +import { + RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, + RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, + RESEARCH_COPILOT_PG_POOL_MAX, + RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, + RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, + ResearchCopilotExecutorError, + type ResearchCopilotExecutorPool, + openResearchCopilotExecutor, +} from '../src/index'; + +const SECRET_USER = 'copilot_secret_user'; +const SECRET_PASS = 'Sup3rS3cretP@ssw0rd!'; +const SECRET_HOST = 'pg-internal-secret.example.test'; +const VALID_URL = `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`; + +interface FakePoolState { + readonly queries: Array<{ readonly text: string; readonly values?: unknown[] }>; + readonly errorListeners: Array<(error: Error) => void>; + endCalls: number; + readonly pool: ResearchCopilotExecutorPool; +} + +function createFakePool(options?: { + onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>; + onEnd?: () => Promise; +}): FakePoolState { + const queries: Array<{ readonly text: string; readonly values?: unknown[] }> = []; + const errorListeners: Array<(error: Error) => void> = []; + const state: FakePoolState = { + queries, + errorListeners, + endCalls: 0, + pool: { + async query(text: string, values?: unknown[]) { + queries.push(values === undefined ? { text } : { text, values }); + if (options?.onQuery) { + return options.onQuery(text, values); + } + return { rows: [] }; + }, + async end() { + state.endCalls += 1; + if (options?.onEnd) { + return options.onEnd(); + } + }, + on(event: 'error', listener: (error: Error) => void) { + if (event === 'error') { + errorListeners.push(listener); + } + return state.pool; + }, + }, + }; + return state; +} + +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, + SECRET_USER, + SECRET_PASS, + encodeURIComponent(SECRET_PASS), + SECRET_HOST, + 'raw-pg-secret', + ]) { + expect(message).not.toContain(needle); + } +} + +describe('openResearchCopilotExecutor', () => { + test('opens a bounded pg pool, probes once with SELECT 1, and attaches an error listener', async () => { + const previousPgOptions = process.env.PGOPTIONS; + delete process.env.PGOPTIONS; + try { + const capturedConfigs: PoolConfig[] = []; + const fake = createFakePool({ + async onQuery(text) { + if (text === 'SELECT 1') { + return { rows: [{ '?column?': 1 }] }; + } + return { rows: [{ id: 42 }] }; + }, + }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { + createPool(poolConfig) { + capturedConfigs.push(poolConfig); + return fake.pool; + }, + } + ); + + expect(capturedConfigs).toHaveLength(1); + expect(capturedConfigs[0]).toEqual({ + connectionString: VALID_URL, + max: RESEARCH_COPILOT_PG_POOL_MAX, + connectionTimeoutMillis: RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, + statement_timeout: RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, + query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, + lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, + }); + expect(capturedConfigs[0]?.options).toBeUndefined(); + expect(RESEARCH_COPILOT_PG_POOL_MAX).toBe(4); + expect(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS).toBe(5_000); + expect(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS).toBe(10_000); + expect(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS).toBe(15_000); + expect(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS).toBe(2_000); + + expect(fake.errorListeners).toHaveLength(1); + expect(fake.queries).toEqual([{ text: 'SELECT 1' }]); + + const res = await handle.executor.query<{ id: number }>('SELECT $1::int AS id', [42]); + expect(res.rows).toEqual([{ id: 42 }]); + expect(fake.queries).toEqual([ + { text: 'SELECT 1' }, + { text: 'SELECT $1::int AS id', values: [42] }, + ]); + + await handle.close(); + expect(fake.endCalls).toBe(1); + } finally { + if (previousPgOptions === undefined) { + delete process.env.PGOPTIONS; + } else { + process.env.PGOPTIONS = previousPgOptions; + } + } + }); + + test('accepts postgresql:// scheme and Unix-domain socket host query parameters', async () => { + for (const postgresUrl of [ + 'postgresql://127.0.0.1:5432/research_db', + 'postgres:///research_db?host=/var/run/postgresql', + 'postgresql:///research_db?host=/var/run/postgresql', + ]) { + const fake = createFakePool(); + const handle = await openResearchCopilotExecutor( + { postgresUrl }, + { createPool: () => fake.pool } + ); + expect(fake.queries).toEqual([{ text: 'SELECT 1' }]); + await handle.close(); + } + }); + + test('rejects invalid URLs with INVALID_CONFIG before constructing a pool', async () => { + const invalidUrls = [ + '', + ' ', + ` ${VALID_URL} `, + `${VALID_URL}\n`, + '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`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/db/extra`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:0/research_db`, + `postgres://%ZZ:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`, + `postgres://${SECRET_USER}:%ZZ@${SECRET_HOST}:5432/research_db`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%ZZ`, + ]; + + let createPoolCalls = 0; + for (const postgresUrl of invalidUrls) { + let caught: unknown; + try { + await openResearchCopilotExecutor( + { postgresUrl }, + { + createPool() { + createPoolCalls += 1; + return createFakePool().pool; + }, + } + ); + } catch (err) { + caught = err; + } + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG'); + } + expect(createPoolCalls).toBe(0); + }); + + test('rejects malformed config or deps with INVALID_CONFIG', async () => { + await expect( + openResearchCopilotExecutor(null as unknown as { postgresUrl: string }) + ).rejects.toMatchObject({ + name: 'ResearchCopilotExecutorError', + code: 'INVALID_CONFIG', + }); + + await expect( + openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: 'not-a-fn' as unknown as () => ResearchCopilotExecutorPool } + ) + ).rejects.toMatchObject({ + name: 'ResearchCopilotExecutorError', + code: 'INVALID_CONFIG', + }); + }); + + test('ends pool and throws sanitized OPEN_FAILED when startup probe fails', async () => { + const fake = createFakePool({ + async onQuery() { + throw new Error(`password authentication failed for ${SECRET_USER} at ${SECRET_HOST} raw-pg-secret`); + }, + }); + + let caught: unknown; + try { + await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool }); + } catch (err) { + caught = err; + } + + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED'); + expect(fake.endCalls).toBe(1); + }); + + test('still throws OPEN_FAILED when both probe and cleanup end() fail', async () => { + const fake = createFakePool({ + async onQuery() { + throw new Error(`connect ECONNREFUSED ${SECRET_HOST} raw-pg-secret`); + }, + async onEnd() { + throw new Error(`pool end failed ${VALID_URL}`); + }, + }); + + let caught: unknown; + try { + await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool }); + } catch (err) { + caught = err; + } + + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED'); + expect(fake.endCalls).toBe(1); + }); + + test('forwards parameters defensively without mutating caller arrays', async () => { + const fake = createFakePool({ + async onQuery(text, values) { + if (values) { + values.push('mutated-by-driver'); + } + return { rows: [{ text }] }; + }, + }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: () => fake.pool } + ); + + const callerParams = Object.freeze(['alpha', 7]); + const res = await handle.executor.query('SELECT $1, $2', callerParams); + expect(res.rows).toEqual([{ text: 'SELECT $1, $2' }]); + expect(callerParams).toEqual(['alpha', 7]); + + await handle.executor.query('SELECT 2'); + expect(fake.queries[2]).toEqual({ text: 'SELECT 2' }); + expect('values' in fake.queries[2]!).toBe(false); + + await handle.close(); + }); + + 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; + if (callCount === 1) { + return { rows: [{ '?column?': 1 }] }; + } + const pgErr = Object.assign( + 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; + }, + }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: () => fake.pool } + ); + + let caught: unknown; + try { + await handle.executor.query('INSERT INTO findings (id) VALUES ($1)', ['dup-1']); + } catch (err) { + caught = err; + } + + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('23505'); + await handle.close(); + }); + + 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; + if (callCount === 1) { + return { rows: [{ '?column?': 1 }] }; + } + throw Object.assign( + new Error(`relation "missing" does not exist on ${VALID_URL} raw-pg-secret`, { + cause: rawCause, + }), + { code: '42P01', detail: 'driver-detail', extraDiag: 'sensitive-driver-field' } + ); + }, + }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: () => fake.pool } + ); + + let caught: unknown; + try { + await handle.executor.query('SELECT * FROM missing'); + } catch (err) { + caught = err; + } + + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED'); + await handle.close(); + }); + + test('close() is idempotent and subsequent queries fail with EXECUTOR_CLOSED', async () => { + const fake = createFakePool(); + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: () => fake.pool } + ); + + await handle.close(); + await handle.close(); + expect(fake.endCalls).toBe(1); + + let caught: unknown; + try { + await handle.executor.query('SELECT 1'); + } catch (err) { + caught = err; + } + + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED'); + expect(fake.queries).toHaveLength(1); // Only the initial SELECT 1 probe ran. + }); + + test('sanitizes pool.end() failures to CLOSE_FAILED with no cause or secret leakage', async () => { + const fake = createFakePool({ + async onEnd() { + throw new Error(`failed closing pool for ${VALID_URL} raw-pg-secret`); + }, + }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: () => fake.pool } + ); + + let caught: unknown; + try { + await handle.close(); + } catch (err) { + caught = err; + } + + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('CLOSE_FAILED'); + expect(fake.endCalls).toBe(1); + }); +}); diff --git a/libs/data/postgres/test/research-copilot-executor.type-test.ts b/libs/data/postgres/test/research-copilot-executor.type-test.ts new file mode 100644 index 00000000..b022aa18 --- /dev/null +++ b/libs/data/postgres/test/research-copilot-executor.type-test.ts @@ -0,0 +1,50 @@ +import type { Pool } from 'pg'; +import type { + ManagedPostgresExecutor, + PostgresResearchCopilotExecutor, + ResearchCopilotHostConfig, + ResearchCopilotStdioHostDeps, +} from '@stock-bot/research/mcp'; +import { + type ManagedResearchCopilotExecutor, + type ResearchCopilotExecutor, + type ResearchCopilotExecutorConfig, + type ResearchCopilotExecutorDeps, + type ResearchCopilotExecutorError, + type ResearchCopilotExecutorErrorCode, + type ResearchCopilotExecutorPool, + openResearchCopilotExecutor, +} from '../src/index'; + +// The factory must plug directly into ResearchCopilotStdioHostDeps.openExecutor. +openResearchCopilotExecutor satisfies ResearchCopilotStdioHostDeps['openExecutor']; + +// Full host config is structurally assignable to the minimal executor config. +declare const hostConfig: ResearchCopilotHostConfig; +hostConfig satisfies ResearchCopilotExecutorConfig; + +// Returned handle and executor are structurally assignable to the MCP host ports. +declare const managedHandle: ManagedResearchCopilotExecutor; +managedHandle satisfies ManagedPostgresExecutor; + +declare const executor: ResearchCopilotExecutor; +executor satisfies PostgresResearchCopilotExecutor; + +// Real pg.Pool satisfies the injected pool contract. +declare const pgPool: Pool; +pgPool satisfies ResearchCopilotExecutorPool; + +// Optional deps contract accepts createPool returning pg.Pool. +const validDeps: ResearchCopilotExecutorDeps = { + createPool: () => pgPool, +}; +void validDeps; + +// Error code union includes all sanitized lifecycle codes plus SQLSTATE 23505. +declare const errorInstance: ResearchCopilotExecutorError; +const errorCode: ResearchCopilotExecutorErrorCode = errorInstance.code; +void errorCode; + +// Negative checks: missing postgresUrl must fail typechecking. +// @ts-expect-error postgresUrl is required. +void openResearchCopilotExecutor({}); diff --git a/package.json b/package.json index 0e2a41b8..e295375c 100644 --- a/package.json +++ b/package.json @@ -53,6 +53,7 @@ "clean:fresh:force": "./scripts/clean.sh --fresh --force", "backtest": "turbo run backtest", "benchmark:dataset": "bun run scripts/benchmark-dataset.ts", + "mcp:research-copilot": "bun run scripts/research-copilot-mcp.ts", "docker:start": "./scripts/docker.sh start --dev", "docker:stop": "./scripts/docker.sh stop --dev", "docker:restart": "./scripts/docker.sh restart --dev", diff --git a/scripts/research-copilot-mcp.ts b/scripts/research-copilot-mcp.ts new file mode 100644 index 00000000..391d5f00 --- /dev/null +++ b/scripts/research-copilot-mcp.ts @@ -0,0 +1,112 @@ +/** + * Runnable stdio entrypoint for the headless MCP research copilot server. + * + * Parses `RESEARCH_MCP_*` environment variables, composes the Vault-fenced + * PostgreSQL executor, DuckDB market data store, and read-only library card + * reader, and serves newline-delimited JSON-RPC 2.0 over stdio. + * + * Fail-closed: configuration or host errors write a single fixed line to + * stderr and exit with code 1 without exposing DSNs, passwords, or raw error + * objects. Stdout carries only MCP protocol bytes. + */ + +import { randomUUID } from 'node:crypto'; +import { + type LibraryCardReaderHandle, + type ManagedMarketDataStore, + type ManagedPostgresExecutor, + type ResearchCopilotHostConfig, + type ResearchCopilotStdioHostDeps, + type StdioInput, + type StdioOutput, + createLibraryCardReader, + createNodeLibraryCardFs, + parseResearchCopilotHostConfig, + runResearchCopilotStdioHost, +} from '@stock-bot/research/mcp'; + +export const RESEARCH_COPILOT_CONFIG_ERROR_LINE = + 'Research copilot MCP server failed: invalid RESEARCH_MCP_* configuration.\n'; + +export const RESEARCH_COPILOT_HOST_ERROR_LINE = + 'Research copilot MCP server failed while running stdio host.\n'; + +export interface ResearchCopilotStderr { + write(chunk: string): boolean; +} + +export interface ResearchCopilotMcpDeps { + readonly env?: Readonly>; + readonly input?: StdioInput; + readonly output?: StdioOutput; + readonly stderr?: ResearchCopilotStderr; + readonly openExecutor?: ResearchCopilotStdioHostDeps['openExecutor']; + readonly openStore?: ResearchCopilotStdioHostDeps['openStore']; + readonly createLibraryCardReader?: ResearchCopilotStdioHostDeps['createLibraryCardReader']; + readonly newId?: () => string; + readonly now?: () => Date | number; +} + +async function defaultOpenExecutor( + config: ResearchCopilotHostConfig +): Promise { + const { openResearchCopilotExecutor } = await import( + '../libs/data/postgres/src/research-copilot-executor' + ); + return openResearchCopilotExecutor(config); +} + +async function defaultOpenStore( + config: ResearchCopilotHostConfig +): Promise { + const { openResearchCopilotStore } = await import( + '../libs/data/duckdb/src/research-copilot-store' + ); + return openResearchCopilotStore(config); +} + +function defaultCreateLibraryCardReader( + config: ResearchCopilotHostConfig +): LibraryCardReaderHandle { + return createLibraryCardReader({ + root: config.libraryRoot, + fs: createNodeLibraryCardFs(), + }); +} + +export async function runResearchCopilotMcp( + deps: ResearchCopilotMcpDeps = {} +): Promise { + const stderr = deps.stderr ?? process.stderr; + + let config: ResearchCopilotHostConfig; + try { + config = parseResearchCopilotHostConfig(deps.env ?? process.env); + } catch { + stderr.write(RESEARCH_COPILOT_CONFIG_ERROR_LINE); + return 1; + } + + try { + await runResearchCopilotStdioHost({ + config, + openExecutor: deps.openExecutor ?? defaultOpenExecutor, + openStore: deps.openStore ?? defaultOpenStore, + createLibraryCardReader: deps.createLibraryCardReader ?? defaultCreateLibraryCardReader, + newId: deps.newId ?? randomUUID, + now: deps.now ?? Date.now, + stdio: { + input: deps.input ?? process.stdin, + output: deps.output ?? process.stdout, + }, + }); + return 0; + } catch { + stderr.write(RESEARCH_COPILOT_HOST_ERROR_LINE); + return 1; + } +} + +if (import.meta.main) { + process.exitCode = await runResearchCopilotMcp(); +} diff --git a/scripts/test/m2-gap-audit.test.ts b/scripts/test/m2-gap-audit.test.ts new file mode 100644 index 00000000..84742687 --- /dev/null +++ b/scripts/test/m2-gap-audit.test.ts @@ -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*\|/); + }); +}); diff --git a/scripts/test/m2-master-audit.test.ts b/scripts/test/m2-master-audit.test.ts new file mode 100644 index 00000000..9b8f6cca --- /dev/null +++ b/scripts/test/m2-master-audit.test.ts @@ -0,0 +1,208 @@ +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-208 M2 master audit (design/m2-master-audit.md) against citation rot. +// Every repo path it cites must still resolve, every symbol or test it reports as +// landed must still be in the file it names, and the audited baseline must stay +// pinned. The gaps it reports as missing are deliberately not asserted, so closing +// a gap never breaks this test. + +const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); +const audit = readFileSync(join(repoRoot, 'design/m2-master-audit.md'), 'utf8'); +const designIndex = readFileSync(join(repoRoot, 'design/README.md'), 'utf8'); + +// Cited as gaps or future outputs, so they must not be required to exist. +const CITED_AS_ABSENT = new Set([ + 'scripts/export-notebook-snapshot.ts', + 'design/m2-close-evidence.md', + 'docs/', + 'docs/*.md', + 'design/*.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 repoRelative = spans.filter((span) => + /^(apps|libs|tools|python|scripts|design|test|database|docs)\//.test(span) + ); + return [ + ...new Set(repoRelative.map((span) => span.replace(/:[\d,-]+$/, '')).flatMap(expandBraces)), + ] + .filter((p) => !p.includes('*') || CITED_AS_ABSENT.has(p)) + .sort(); +} + +function lineAt(file: string, line: number): string { + return readFileSync(join(repoRoot, file), 'utf8').split('\n')[line - 1] ?? ''; +} + +describe('design/m2-master-audit.md citations', () => { + test('cites only repo paths that exist, except gaps and future evidence files', () => { + 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('paths cited as gaps are still absent, and specs live under design/', () => { + expect(existsSync(join(repoRoot, 'docs'))).toBe(false); + expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true); + }); + + // [file, 1-based line the audit cites, text that line must contain] + const lineCitations: Array<[file: string, line: number, expected: string]> = [ + ['tools/curate-etl/src/parquet_posts.rs', 22, 'EVENT_KIND_POST'], + ['tools/curate-etl/src/run_curate_posts.rs', 133, 'EventsDatasetExists'], + ['tools/curate-etl/src/mongo_stream.rs', 53, 'pub enum SourceCollection'], + ['tools/curate-etl/src/run_curate_fundamentals.rs', 113, 'pub struct CurateFundamentalsArgs'], + ['tools/curate-etl/src/cli.rs', 98, 'CurateBars1m('], + ['tools/curate-etl/src/cli.rs', 99, 'CurateQmBars1m('], + ['tools/curate-etl/src/cli.rs', 100, 'CurateFx1m('], + ['tools/curate-etl/src/cli.rs', 101, 'CuratePosts('], + ['tools/curate-etl/src/cli.rs', 102, 'CurateFundamentals('], + ['tools/curate-etl/src/cli.rs', 103, 'CurateMacro('], + ['tools/curate-etl/src/cli.rs', 104, 'SendIlp('], + ['tools/curate-etl/src/cli.rs', 1317, 'CliAction::CuratePosts'], + ['tools/curate-etl/src/cli.rs', 1636, 'CliAction::CurateFundamentals'], + ['tools/curate-etl/src/cli.rs', 1689, 'CliAction::CurateMacro'], + ['tools/curate-etl/src/cli.rs', 2110, 'CliAction::CurateBars1m'], + ['tools/curate-etl/src/cli.rs', 2277, 'CliAction::CurateQmBars1m'], + ['tools/curate-etl/src/cli.rs', 2381, 'CliAction::CurateFx1m'], + ['tools/curate-etl/src/cli.rs', 2461, 'CliAction::SendIlp'], + ['tools/curate-etl/src/main.rs', 22, 'run_send_ilp'], + ['tools/curate-etl/src/main.rs', 39, 'run_curate_qm_bars_1m'], + [ + 'tools/curate-etl/src/fundamentals_tests.rs', + 104, + 'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2', + ], + [ + 'tools/curate-etl/src/parquet_fundamentals_tests.rs', + 1107, + 'fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm', + ], + [ + 'tools/curate-etl/src/run_curate_bars_1m_tests.rs', + 402, + 'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes', + ], + ['tools/curate-etl/tests/cli.rs', 1747, 'fn send_ilp_cli_help_missing_flag_success_and_partial_error_routing'], + ['tools/curate-etl/tests/cli.rs', 1787, 'TcpListener::bind("127.0.0.1:0")'], + [ + 'tools/curate-etl/tests/cli.rs', + 1877, + 'fn send_ilp_cli_shard_gap_exits_without_partial_report_or_connect_and_bad_prefix_prints_usage', + ], + ['tools/curate-etl/tests/cli.rs', 1939, 'fn send_ilp_cli_ignores_questdb_env_vars_and_requires_explicit_addr'], + [ + 'tools/curate-etl/tests/curate_macro.rs', + 178, + 'fn cli_publishes_runner_equivalent_macro_parquet_with_pit_lag_and_no_forecast_leakage', + ], + [ + 'tools/curate-etl/tests/curate_macro.rs', + 471, + 'fn cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel', + ], + ['tools/curate-etl/tests/curate_macro.rs', 709, 'fn cli_rerun_on_same_inputs_is_byte_deterministic'], + [ + 'tools/curate-etl/tests/curate_qm_bars_1m.rs', + 336, + 'fn curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants', + ], + [ + 'tools/curate-etl/tests/curate_qm_bars_1m.rs', + 527, + 'fn curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards', + ], + [ + 'tools/curate-etl/tests/curate_qm_bars_1m.rs', + 622, + 'fn curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped', + ], + ['tools/curate-etl/src/run_curate_fx_1m.rs', 24, 'bar-start `ts`'], + ['libs/data/questdb/src/schema.ts', 33, 'fx_1m: {'], + ['libs/data/questdb/src/schema.ts', 139, 'export function getM2IntradayDDL'], + ['libs/data/duckdb/src/research-copilot-store.ts', 33, 'export const openResearchCopilotStore'], + ['libs/data/duckdb/src/research-copilot-store.ts', 40, 'vaultOperatorAuthorized: false'], + ['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 251, 'fundamentalsAsOf enforces restatement non-overwrite'], + ['libs/research/src/market-data-store-duckdb.ts', 1448, "'events/year=*/part.parquet'"], + ['libs/research/src/market-data-store-duckdb.ts', 1529, "timeframe === '1m'"], + ['libs/research/src/market-data-store-duckdb.ts', 2283, 'crossSection('], + ['libs/research/src/market-data-store-duckdb.ts', 2287, 'async fundamentalsAsOf('], + ['libs/research/src/market-data-store-duckdb.ts', 2294, 'macroAsOf('], + ['libs/research/src/market-data-store-routed.ts', 185, 'return daily.fx(q)'], + ['libs/research/src/mcp/tools/analyze-signal.ts', 122, 'discriminatedUnion'], + ['libs/research/src/feature-library.ts', 29, 'RET_1D_V1'], + ['libs/research/src/feature-library.ts', 61, 'export const FEATURE_INPUT_DATASETS'], + ['libs/research/src/notebook-snapshot-node.ts', 67, 'export function createNodeNotebookCommandRunner'], + ['scripts/research-copilot-mcp.ts', 77, 'export async function runResearchCopilotMcp'], + ['python/stockbot/data.py', 21, '"ceo_post"'], + ['python/stockbot/data.py', 71, 'events/year=*/part.parquet'], + ['python/stockbot/data.py', 259, 'NotImplementedError'], + ['package.json', 56, '"mcp:research-copilot"'], + ['design/MILESTONES.md', 96, 'eodIntraday1M'], + ['docker-compose.quant.yml', 35, '1048576'], + ]; + + test.each(lineCitations)('%s:%d contains %p as cited', (file, line, expected) => { + expect(audit).toContain(file.split('/').pop()!); + expect(lineAt(file, line)).toContain(expected); + }); + + test('pins the audited master baseline and accepted M1 separately from the review branch', () => { + expect(audit).toContain('d45014a1f6dfc5ba5a73bcc0d6e57e486c2c7c52'); + expect(audit).toContain('d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1'); + expect(audit).toContain('git rev-parse master'); + expect(audit).toMatch(/not `git rev-parse HEAD`/); + }); + + test('maps every M2 deliverable and exit criterion to a Done/Partial/Missing status', () => { + for (const row of ['M2.1', 'M2.2', 'M2.3', 'M2.4', 'EC-1', 'EC-2', 'EC-3']) { + const line = audit.split('\n').find((l) => l.startsWith(`| **${row}`)); + expect(line, row).toBeDefined(); + expect(line!).toMatch(/\|\s*\*\*(Done|Partial|Missing)\b/); + } + }); + + test('keeps host and quant checks pending rather than claiming them passed', () => { + expect(audit).toMatch(/\*\*PENDING \(host closure\)\*\*/); + expect(audit).toMatch(/\*\*PENDING \(host\/`quant`\)\*\*/); + expect(audit).toMatch(/\*\*Partial \(Synthetic Done; Live `quant` Missing\)\*\*/); + }); + + test('lists the seven approved backlog keys in dependency order', () => { + const keys = [ + 'm2-ceo-posts-events-compat', + 'm2-store-macro-cross-section-fx1m', + 'm2-data-pipeline-m2-inputs-and-probes', + 'm2-curate-etl-mongo-and-financials-old', + 'm2-python-sdk-m2-parity', + 'm2-ec1-snapshot-cli-and-doc-paths', + 'm2-host-quant-verification-and-closure', + ]; + const section = audit.slice(audit.indexOf('## 5. Ordered M2 Closure Backlog')); + const rows = section.split('\n').filter((l) => /^\| \*\*\d\*\* \|/.test(l)); + expect(rows.map((r) => /`(m2-[a-z0-9-]+)`/.exec(r)?.[1])).toEqual(keys); + rows.forEach((row, i) => { + for (const dep of [...row.split('|')[4]!.matchAll(/`(m2-[a-z0-9-]+)`/g)].map((m) => m[1]!)) { + expect(keys.indexOf(dep), `${keys[i]} depends on ${dep}`).toBeLessThan(i); + } + }); + }); + + test('proposes no CI workflow and is indexed in design/README.md', () => { + expect(audit).not.toMatch(/\.github\/workflows/); + expect(designIndex).toContain('[m2-master-audit.md](m2-master-audit.md)'); + }); +}); diff --git a/scripts/test/research-copilot-mcp-defaults.test.ts b/scripts/test/research-copilot-mcp-defaults.test.ts new file mode 100644 index 00000000..429f5672 --- /dev/null +++ b/scripts/test/research-copilot-mcp-defaults.test.ts @@ -0,0 +1,332 @@ +import { describe, expect, test } from 'bun:test'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import type { BarBatch, BarQuery, MarketDataStore } from '@stock-bot/research/market-data-store'; +import { MarketDataStoreNotImplementedError } from '@stock-bot/research/market-data-store-duckdb'; +import { + type LibraryCardReaderHandle, + MCP_PROTOCOL_VERSION, + type PostgresResearchCopilotExecutor, + type ReadKnowledgeResultPayload, + RESEARCH_COPILOT_TOOL_NAMES, + type StdioInput, + type StdioOutput, +} from '@stock-bot/research/mcp'; +import { + RESEARCH_COPILOT_HOST_ERROR_LINE, + runResearchCopilotMcp, +} from '../research-copilot-mcp'; + +const FAKE_PASSWORD = 's3cr@t-default-pw#42'; +const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_PASSWORD); +const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z'; +const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0); + +function createMemoryWriter(): { + readonly stream: StdioOutput; + text(): string; +} { + const chunks: string[] = []; + return { + stream: { + write(chunk: string): boolean { + chunks.push(chunk); + return true; + }, + }, + text: () => chunks.join(''), + }; +} + +function createMemoryInput(lines: readonly string[]): StdioInput { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (const line of lines) { + yield `${line}\n`; + } + }, + }; +} + +function createFakeExecutor(): PostgresResearchCopilotExecutor { + return { + async query>(): Promise<{ readonly rows: readonly Row[] }> { + return { rows: [] }; + }, + }; +} + +function createFakeStore(): MarketDataStore { + return { + async *bars(q: BarQuery): AsyncIterable { + yield { + listingId: q.listingIds[0] ?? 0, + timeframe: q.timeframe, + rows: [], + }; + }, + async crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + async fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + async events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + async shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + async macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + async fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + async universe() { + return []; + }, + }; +} + +function createFakeLibraryReader(): LibraryCardReaderHandle { + return { + async listLibraryCards() { + return []; + }, + }; +} + +describe('scripts/research-copilot-mcp.ts default factory wiring', () => { + test('default createLibraryCardReader resolves master createLibraryCardReader + createNodeLibraryCardFs over a temp dir', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'stockbot-mcp-lib-')); + try { + await mkdir(join(tempDir, 'cards', 'quant'), { recursive: true }); + await writeFile( + join(tempDir, 'library.yml'), + 'id: research-lib\nsections:\n quant: Quantitative Methods\n', + 'utf8' + ); + await writeFile( + join(tempDir, 'cards', 'quant', 'dsr-basics.md'), + [ + '---', + 'title: "Deflated Sharpe Ratio"', + 'summary: "Adjusts Sharpe for multiple testing."', + 'matches: ["dsr", "sharpe"]', + '---', + '', + 'Use DSR to account for trial count.', + ].join('\n'), + 'utf8' + ); + + const stdout = createMemoryWriter(); + const stderr = createMemoryWriter(); + const closed: string[] = []; + + const input = createMemoryInput([ + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: 'defaults-test', version: '1.0.0' }, + }, + }), + JSON.stringify({ + jsonrpc: '2.0', + method: 'notifications/initialized', + }), + JSON.stringify({ + jsonrpc: '2.0', + id: 2, + method: 'tools/call', + params: { + name: 'read_knowledge', + arguments: { + source: 'library', + id: 'research-lib:quant/dsr-basics', + }, + }, + }), + ]); + + const exitCode = await runResearchCopilotMcp({ + env: { + RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`, + RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root', + RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, + RESEARCH_MCP_LIBRARY_ROOT: tempDir, + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), + }, + input, + output: stdout.stream, + stderr: stderr.stream, + openExecutor: () => ({ + executor: createFakeExecutor(), + close: () => { + closed.push('executor'); + }, + }), + openStore: () => ({ + store: createFakeStore(), + close: () => { + closed.push('store'); + }, + }), + // Intentionally omit createLibraryCardReader to exercise the default factory. + newId: () => '00000000-0000-4000-8000-000000000002', + now: () => FIXED_NOW_MS, + }); + + expect(exitCode).toBe(0); + expect(stderr.text()).toBe(''); + expect(closed).toEqual(['store', 'executor']); + + const responses = stdout + .text() + .trim() + .split('\n') + .map(line => JSON.parse(line) as Record); + expect(responses).toHaveLength(2); + + const callResp = responses[1] as { + id: number; + result: { + isError?: boolean; + content: Array<{ type: string; text: string }>; + }; + }; + expect(callResp.id).toBe(2); + expect(callResp.result.isError).not.toBe(true); + const payload = JSON.parse(callResp.result.content[0]!.text) as ReadKnowledgeResultPayload; + expect(payload.rowCount).toBe(1); + expect(payload.rows).toHaveLength(1); + const firstRow = payload.rows[0]; + expect(firstRow?.source).toBe('library'); + if (firstRow?.source === 'library') { + expect(firstRow.id).toBe('research-lib:quant/dsr-basics'); + expect(firstRow.title).toBe('Deflated Sharpe Ratio'); + } + } finally { + await rm(tempDir, { recursive: true, force: true }); + } + }); + + test('default openExecutor resolves master openResearchCopilotExecutor and fails closed without opening a DB socket', async () => { + // Passes parseResearchCopilotHostConfig (valid scheme + host), but fails + // openResearchCopilotExecutor synchronously (missing database path) before creating pg.Pool. + const urlWithoutDatabase = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433`; + const stdout = createMemoryWriter(); + const stderr = createMemoryWriter(); + let openStoreCalled = false; + + const exitCode = await runResearchCopilotMcp({ + env: { + RESEARCH_MCP_POSTGRES_URL: urlWithoutDatabase, + RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root', + RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, + RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root', + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), + }, + input: createMemoryInput([]), + output: stdout.stream, + stderr: stderr.stream, + // Intentionally omit openExecutor to exercise lazy import of openResearchCopilotExecutor. + openStore: () => { + openStoreCalled = true; + return { store: createFakeStore(), close: () => undefined }; + }, + createLibraryCardReader: () => createFakeLibraryReader(), + }); + + expect(exitCode).toBe(1); + expect(stdout.text()).toBe(''); + expect(stderr.text()).toBe(RESEARCH_COPILOT_HOST_ERROR_LINE); + expect(stderr.text()).not.toContain(FAKE_PASSWORD); + expect(stderr.text()).not.toContain(FAKE_ENCODED_PASSWORD); + expect(stderr.text()).not.toContain(urlWithoutDatabase); + expect(openStoreCalled).toBe(false); + }); + + test('default openStore resolves master openResearchCopilotStore (in-memory DuckDB) and closes cleanly', async () => { + const tempCuratedRoot = await mkdtemp(join(tmpdir(), 'stockbot-mcp-curated-')); + try { + const stdout = createMemoryWriter(); + const stderr = createMemoryWriter(); + const closed: string[] = []; + + const input = createMemoryInput([ + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: 'defaults-store-test', version: '1.0.0' }, + }, + }), + JSON.stringify({ + jsonrpc: '2.0', + method: 'notifications/initialized', + }), + JSON.stringify({ + jsonrpc: '2.0', + id: 2, + method: 'tools/list', + params: {}, + }), + ]); + + const exitCode = await runResearchCopilotMcp({ + env: { + RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`, + RESEARCH_MCP_CURATED_ROOT: tempCuratedRoot, + RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, + RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root', + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }), + }, + input, + output: stdout.stream, + stderr: stderr.stream, + openExecutor: () => ({ + executor: createFakeExecutor(), + close: () => { + closed.push('executor'); + }, + }), + // Intentionally omit openStore to exercise lazy import of openResearchCopilotStore. + createLibraryCardReader: () => createFakeLibraryReader(), + newId: () => '00000000-0000-4000-8000-000000000003', + now: () => FIXED_NOW_MS, + }); + + expect(exitCode).toBe(0); + expect(stderr.text()).toBe(''); + expect(closed).toEqual(['executor']); + + const responses = stdout + .text() + .trim() + .split('\n') + .map(line => JSON.parse(line) as Record); + expect(responses).toHaveLength(2); + const listResp = responses[1] as { + id: number; + result: { tools: Array<{ name: string }> }; + }; + expect(listResp.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); + } finally { + await rm(tempCuratedRoot, { recursive: true, force: true }); + } + }); +}); diff --git a/scripts/test/research-copilot-mcp.test.ts b/scripts/test/research-copilot-mcp.test.ts new file mode 100644 index 00000000..a92f6f8d --- /dev/null +++ b/scripts/test/research-copilot-mcp.test.ts @@ -0,0 +1,391 @@ +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { BarBatch, BarQuery, MarketDataStore } from '@stock-bot/research/market-data-store'; +import { MarketDataStoreNotImplementedError } from '@stock-bot/research/market-data-store-duckdb'; +import { + type LibraryCardReaderHandle, + MCP_PROTOCOL_VERSION, + type PostgresResearchCopilotExecutor, + RESEARCH_COPILOT_HOST_NAME, + RESEARCH_COPILOT_HOST_VERSION, + RESEARCH_COPILOT_TOOL_NAMES, + type StdioInput, + type StdioOutput, +} from '@stock-bot/research/mcp'; +import { + RESEARCH_COPILOT_CONFIG_ERROR_LINE, + RESEARCH_COPILOT_HOST_ERROR_LINE, + runResearchCopilotMcp, +} from '../research-copilot-mcp'; + +const FAKE_DECODED_PASSWORD = 's3cr@t pass#99!'; +const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD); +const FAKE_POSTGRES_URL = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev?sslmode=disable`; +const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z'; +const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0); + +function buildValidEnv( + overrides: Readonly> = {} +): Record { + return { + PATH: '/usr/local/bin:/usr/bin', + NODE_ENV: 'test', + RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL, + RESEARCH_MCP_POSTGRES_SCHEMA: 'research_ro', + RESEARCH_MCP_CURATED_ROOT: '/tmp/fake-curated-root-secret-path', + RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO, + RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL, + RESEARCH_MCP_LIBRARY_ROOT: '/tmp/fake-library-root-secret-path', + RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ + XNYS: [101], + }), + ...overrides, + }; +} + +function createMemoryWriter(): { + readonly stream: StdioOutput; + readonly chunks: string[]; + text(): string; +} { + const chunks: string[] = []; + return { + stream: { + write(chunk: string): boolean { + chunks.push(chunk); + return true; + }, + }, + chunks, + text: () => chunks.join(''), + }; +} + +function createMemoryInput(lines: readonly string[]): StdioInput { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (const line of lines) { + yield `${line}\n`; + } + }, + }; +} + +function createFakeExecutor(): PostgresResearchCopilotExecutor { + return { + async query>(): Promise<{ readonly rows: readonly Row[] }> { + return { rows: [] }; + }, + }; +} + +function createFakeStore(): MarketDataStore { + return { + async *bars(q: BarQuery): AsyncIterable { + yield { + listingId: q.listingIds[0] ?? 0, + timeframe: q.timeframe, + rows: [], + }; + }, + async crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + async fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + async events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + async shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + async macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + async fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + async universe() { + return []; + }, + }; +} + +function createFakeLibraryReader(): LibraryCardReaderHandle { + return { + async listLibraryCards() { + return []; + }, + }; +} + +function assertSingleFixedLineNoSecrets( + stderrText: string, + expectedLine: string, + env: Readonly> +): void { + expect(stderrText).toBe(expectedLine); + expect(stderrText.endsWith('\n')).toBe(true); + expect(stderrText.slice(0, -1)).not.toContain('\n'); + + const forbidden = [ + FAKE_POSTGRES_URL, + FAKE_ENCODED_PASSWORD, + FAKE_DECODED_PASSWORD, + env.RESEARCH_MCP_POSTGRES_URL, + env.RESEARCH_MCP_CURATED_ROOT, + env.RESEARCH_MCP_LIBRARY_ROOT, + env.RESEARCH_MCP_PRINCIPAL_ID, + ].filter((value): value is string => typeof value === 'string' && value.length > 0); + + for (const secret of forbidden) { + expect(stderrText).not.toContain(secret); + } +} + +describe('scripts/research-copilot-mcp.ts', () => { + test('package.json defines mcp:research-copilot pointing to scripts/research-copilot-mcp.ts', () => { + const repoRoot = fileURLToPath(new URL('../../', import.meta.url)); + const pkg = JSON.parse(readFileSync(join(repoRoot, 'package.json'), 'utf8')) as { + scripts?: Record; + }; + expect(pkg.scripts?.['mcp:research-copilot']).toBe('bun run scripts/research-copilot-mcp.ts'); + }); + + test('missing required RESEARCH_MCP_* env returns exit code 1, one fixed stderr line, and zero stdout bytes', async () => { + const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: undefined }); + const stdout = createMemoryWriter(); + const stderr = createMemoryWriter(); + let openExecutorCalled = false; + let openStoreCalled = false; + + const exitCode = await runResearchCopilotMcp({ + env, + input: createMemoryInput([]), + output: stdout.stream, + stderr: stderr.stream, + openExecutor: () => { + openExecutorCalled = true; + return { executor: createFakeExecutor(), close: () => undefined }; + }, + openStore: () => { + openStoreCalled = true; + return { store: createFakeStore(), close: () => undefined }; + }, + createLibraryCardReader: () => createFakeLibraryReader(), + }); + + expect(exitCode).toBe(1); + expect(stdout.text()).toBe(''); + assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_CONFIG_ERROR_LINE, env); + expect(openExecutorCalled).toBe(false); + expect(openStoreCalled).toBe(false); + }); + + test('invalid RESEARCH_MCP_* env fails closed with one fixed stderr line and zero stdout bytes', async () => { + const env = buildValidEnv({ + RESEARCH_MCP_POSTGRES_URL: `http://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`, + }); + const stdout = createMemoryWriter(); + const stderr = createMemoryWriter(); + + const exitCode = await runResearchCopilotMcp({ + env, + input: createMemoryInput([]), + output: stdout.stream, + stderr: stderr.stream, + openExecutor: () => ({ executor: createFakeExecutor(), close: () => undefined }), + openStore: () => ({ store: createFakeStore(), close: () => undefined }), + createLibraryCardReader: () => createFakeLibraryReader(), + }); + + expect(exitCode).toBe(1); + expect(stdout.text()).toBe(''); + assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_CONFIG_ERROR_LINE, env); + }); + + test('openExecutor failure returns 1 with fixed stderr line leaking no DSN, password, or env values', async () => { + const env = buildValidEnv(); + const stdout = createMemoryWriter(); + const stderr = createMemoryWriter(); + let openStoreCalled = false; + + const exitCode = await runResearchCopilotMcp({ + env, + input: createMemoryInput([]), + output: stdout.stream, + stderr: stderr.stream, + openExecutor: () => { + throw new Error( + `connect failed for ${FAKE_POSTGRES_URL} (pw=${FAKE_DECODED_PASSWORD}) root=${env.RESEARCH_MCP_CURATED_ROOT}` + ); + }, + openStore: () => { + openStoreCalled = true; + return { store: createFakeStore(), close: () => undefined }; + }, + createLibraryCardReader: () => createFakeLibraryReader(), + }); + + expect(exitCode).toBe(1); + expect(stdout.text()).toBe(''); + assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env); + expect(openStoreCalled).toBe(false); + }); + + test('openStore failure closes already-opened executor and returns 1 with fixed stderr line', async () => { + const env = buildValidEnv(); + const stdout = createMemoryWriter(); + const stderr = createMemoryWriter(); + const closed: string[] = []; + + const exitCode = await runResearchCopilotMcp({ + env, + input: createMemoryInput([]), + output: stdout.stream, + stderr: stderr.stream, + openExecutor: () => ({ + executor: createFakeExecutor(), + close: () => { + closed.push('executor'); + }, + }), + openStore: () => { + throw new Error(`DuckDB failed for ${env.RESEARCH_MCP_CURATED_ROOT} ${FAKE_POSTGRES_URL}`); + }, + createLibraryCardReader: () => createFakeLibraryReader(), + }); + + expect(exitCode).toBe(1); + expect(stdout.text()).toBe(''); + assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env); + expect(closed).toEqual(['executor']); + }); + + test('stdio host failure closes store and executor in reverse order and leaks no secrets', async () => { + const env = buildValidEnv(); + const stdout = createMemoryWriter(); + const stderr = createMemoryWriter(); + const closed: string[] = []; + + const failingInput: StdioInput = { + async *[Symbol.asyncIterator](): AsyncIterator { + throw new Error(`stdin boom ${FAKE_POSTGRES_URL} ${FAKE_DECODED_PASSWORD}`); + }, + }; + + const exitCode = await runResearchCopilotMcp({ + env, + input: failingInput, + output: stdout.stream, + stderr: stderr.stream, + openExecutor: () => ({ + executor: createFakeExecutor(), + close: () => { + closed.push('executor'); + }, + }), + openStore: () => ({ + store: createFakeStore(), + close: () => { + closed.push('store'); + }, + }), + createLibraryCardReader: () => createFakeLibraryReader(), + }); + + expect(exitCode).toBe(1); + expect(stdout.text()).toBe(''); + assertSingleFixedLineNoSecrets(stderr.text(), RESEARCH_COPILOT_HOST_ERROR_LINE, env); + expect(closed).toEqual(['store', 'executor']); + }); + + test('MCP initialize + tools/list round trip returns all 6 copilot tools on stdout, exit 0, and closes resources', async () => { + const env = buildValidEnv(); + const stdout = createMemoryWriter(); + const stderr = createMemoryWriter(); + const closed: string[] = []; + + const input = createMemoryInput([ + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: 'test-client', version: '1.0.0' }, + }, + }), + JSON.stringify({ + jsonrpc: '2.0', + method: 'notifications/initialized', + }), + JSON.stringify({ + jsonrpc: '2.0', + id: 2, + method: 'tools/list', + params: {}, + }), + ]); + + const exitCode = await runResearchCopilotMcp({ + env, + input, + output: stdout.stream, + stderr: stderr.stream, + openExecutor: () => ({ + executor: createFakeExecutor(), + close: () => { + closed.push('executor'); + }, + }), + openStore: () => ({ + store: createFakeStore(), + close: () => { + closed.push('store'); + }, + }), + createLibraryCardReader: () => createFakeLibraryReader(), + newId: () => '00000000-0000-4000-8000-000000000001', + now: () => FIXED_NOW_MS, + }); + + expect(exitCode).toBe(0); + expect(stderr.text()).toBe(''); + expect(closed).toEqual(['store', 'executor']); + + const lines = stdout + .text() + .trim() + .split('\n') + .map(line => JSON.parse(line) as Record); + expect(lines).toHaveLength(2); + + const initResp = lines[0] as { + id: number; + result: { + protocolVersion: string; + serverInfo: { name: string; version: string }; + }; + }; + expect(initResp.id).toBe(1); + expect(initResp.result.protocolVersion).toBe(MCP_PROTOCOL_VERSION); + expect(initResp.result.serverInfo).toEqual({ + name: RESEARCH_COPILOT_HOST_NAME, + version: RESEARCH_COPILOT_HOST_VERSION, + }); + + const listResp = lines[1] as { + id: number; + result: { tools: Array<{ name: string }> }; + }; + expect(listResp.id).toBe(2); + expect(listResp.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); + expect(listResp.result.tools).toHaveLength(6); + }); +}); diff --git a/test/postgres/mcp-copilot-executor.test.ts b/test/postgres/mcp-copilot-executor.test.ts new file mode 100644 index 00000000..526f9d78 --- /dev/null +++ b/test/postgres/mcp-copilot-executor.test.ts @@ -0,0 +1,404 @@ +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Client, Pool, type PoolConfig } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { + PostgreSQLClient, + RESEARCH_COPILOT_PG_POOL_MAX, + ResearchCopilotExecutorError, + openResearchCopilotExecutor, + runPostgresMigrations, +} from '@stock-bot/postgres'; +import { + createPostgresFindingWritePort, + createPostgresKnowledgeReaders, + createPostgresTrialRefLookupPort, +} from '../../libs/research/src/mcp/index'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('mcp-copilot-executor-pg-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); + +const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); +const FIXED_TS = '2026-01-15T12:34:56.789Z'; + +const cleanup: Array<() => Promise | void> = []; +afterEach(async () => { + let firstError: unknown; + for (const close of cleanup.splice(0).reverse()) { + try { + await close(); + } catch (err) { + firstError ??= err; + } + } + if (firstError !== undefined) { + throw firstError; + } +}); + +function assertSafetyDatabaseUrl(connectionString: string | undefined): string { + if (!connectionString) { + throw new Error('Dedicated stock_bot_safety database required'); + } + let parsed: URL; + try { + parsed = new URL(connectionString); + } catch { + throw new Error('Dedicated stock_bot_safety database required'); + } + if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { + throw new Error('Dedicated stock_bot_safety database required'); + } + const client = new Client({ connectionString }); + const effectiveDb = ( + client as unknown as { connectionParameters?: { database?: unknown } } + ).connectionParameters?.database; + if ( + typeof effectiveDb !== 'string' || + !effectiveDb.startsWith('stock_bot_safety') || + !parsed.pathname.startsWith('/stock_bot_safety') + ) { + throw new Error('Dedicated stock_bot_safety database required'); + } + return connectionString; +} + +function buildIsolatedPoolConfig(connectionString: string, schema: string): PoolConfig { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const parsed = new URL(safeUrl); + const existingOptions = parsed.searchParams + .getAll('options') + .map(value => value.trim()) + .filter(value => value.length > 0); + parsed.searchParams.delete('options'); + + const options = [ + ...existingOptions, + `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + ].join(' '); + + return { + connectionString: parsed.toString(), + options, + }; +} + +function buildExecutorUrl( + connectionString: string, + schema: string, + applicationName: string, + extraParams?: Readonly> +): string { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const parsed = new URL(safeUrl); + const existingOptions = parsed.searchParams + .getAll('options') + .map(value => value.trim()) + .filter(value => value.length > 0); + parsed.searchParams.delete('options'); + const combinedOptions = [...existingOptions, `-c search_path=${schema}`].join(' '); + parsed.searchParams.set('options', combinedOptions); + parsed.searchParams.set('application_name', applicationName); + if (extraParams) { + for (const [k, v] of Object.entries(extraParams)) { + parsed.searchParams.set(k, v); + } + } + return parsed.toString(); +} + +async function createIsolatedFixture(connectionString: string | undefined = url) { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: safeUrl }); + cleanup.push(() => admin.end()); + await admin.query(`CREATE SCHEMA ${schema}`); + cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined)); + + const setupPool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); + cleanup.push(() => setupPool.end()); + + const { rows: schemaRows } = await setupPool.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + if (schemaRows[0]?.current_schema !== schema) { + throw new Error( + `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` + ); + } + + for (const filename of [ + '06-create-backtest-tables.sql', + '07-fix-execution-time-type.sql', + '08-create-runs-table.sql', + ]) { + await setupPool.query(readFileSync(`${initDir}${filename}`, 'utf8')); + } + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => setupPool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'research' }); + + return { admin, setupPool, schema, safeUrl }; +} + +async function waitForZeroBackends(admin: Pool, applicationName: string): Promise { + const deadline = Date.now() + 2_000; + let count = -1; + while (Date.now() < deadline) { + const { rows } = await admin.query<{ c: number }>( + 'SELECT count(*)::int AS c FROM pg_stat_activity WHERE application_name = $1', + [applicationName] + ); + count = rows[0]?.c ?? -1; + if (count === 0) { + return 0; + } + await new Promise(resolve => setTimeout(resolve, 25)); + } + return count; +} + +describe('PostgreSQL MCP copilot executor safety guard', () => { + test('rejects missing or non-safety database URLs', () => { + expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( + 'Dedicated stock_bot_safety database required' + ); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot') + ).toThrow('Dedicated stock_bot_safety database required'); + expect(() => + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') + ).toThrow('Dedicated stock_bot_safety database required'); + expect( + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') + ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); + }); +}); + +describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () => { + test('enforces effective 10s statement_timeout and 2s lock_timeout even when URL specifies overrides', async () => { + const f = await createIsolatedFixture(); + const appName = `copilot_timeouts_${randomUUID().slice(0, 8)}`; + const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName, { + statement_timeout: '99999', + lock_timeout: '99999', + query_timeout: '99999', + }); + + const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl }); + cleanup.push(() => handle.close()); + + const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>( + 'SHOW statement_timeout' + ); + const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>( + 'SHOW lock_timeout' + ); + + expect(stmtRows[0]?.statement_timeout).toBe('10s'); + expect(lockRows[0]?.lock_timeout).toBe('2s'); + }); + + test('preserves PGOPTIONS search_path when URL omits options while enforcing 10s/2s timeouts', async () => { + const f = await createIsolatedFixture(); + const appName = `copilot_pgoptions_${randomUUID().slice(0, 8)}`; + + // Build a URL with NO options query parameter so pg must honor PGOPTIONS. + const parsed = new URL(f.safeUrl); + parsed.searchParams.delete('options'); + parsed.searchParams.set('application_name', appName); + + const previousPgOptions = process.env.PGOPTIONS; + process.env.PGOPTIONS = `-c search_path=${f.schema} -c statement_timeout=99999 -c lock_timeout=88888`; + cleanup.push(() => { + if (previousPgOptions === undefined) { + delete process.env.PGOPTIONS; + } else { + process.env.PGOPTIONS = previousPgOptions; + } + }); + + const handle = await openResearchCopilotExecutor({ postgresUrl: parsed.toString() }); + cleanup.push(() => handle.close()); + + const { rows: schemaRows } = await handle.executor.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>( + 'SHOW statement_timeout' + ); + const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>( + 'SHOW lock_timeout' + ); + + expect(schemaRows[0]?.current_schema).toBe(f.schema); + expect(stmtRows[0]?.statement_timeout).toBe('10s'); + expect(lockRows[0]?.lock_timeout).toBe('2s'); + + // Verify unqualified findings writes and reads resolve against the PGOPTIONS search_path. + const writePort = createPostgresFindingWritePort({ executor: handle.executor }); + const readers = createPostgresKnowledgeReaders({ executor: handle.executor }); + const created = await writePort.appendFinding( + { + id: 'finding-pgoptions-0001', + kind: 'finding', + title: 'PGOPTIONS search_path finding', + summary: 'Resolved via PGOPTIONS search_path without explicit schema option.', + status: 'pending_review', + createdAt: FIXED_TS, + trialRefs: [], + evidenceRefs: [], + }, + 'idem-pgoptions-0001' + ); + expect(created.status).toBe('created'); + + const listed = await readers.listFindings({ query: 'PGOPTIONS search_path' }); + expect(listed).toHaveLength(1); + expect(listed[0]?.id).toBe('finding-pgoptions-0001'); + }); + + 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); + + const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl }); + cleanup.push(() => handle.close()); + + const writePort = createPostgresFindingWritePort({ + executor: handle.executor, + schema: f.schema, + }); + const readers = createPostgresKnowledgeReaders({ + executor: handle.executor, + schema: f.schema, + }); + + const record = { + id: 'finding-exec-0001', + kind: 'finding' as const, + title: 'Executor integration finding', + summary: 'Verified against migrated schema via openResearchCopilotExecutor.', + status: 'pending_review' as const, + createdAt: FIXED_TS, + trialRefs: ['101'], + evidenceRefs: ['snap:2025-06-29:ic'], + }; + + const first = await writePort.appendFinding(record, 'idem-key-0001'); + expect(first).toEqual({ + status: 'created', + id: 'finding-exec-0001', + createdAt: FIXED_TS, + }); + + // 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', + id: 'finding-exec-0001', + 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'); + expect(listed[0]?.trialRefs).toEqual(['101']); + + // Executor remains usable after 23505 collision. + const { rows } = await handle.executor.query<{ count: number }>( + `SELECT count(*)::int AS count FROM "${f.schema}".findings` + ); + expect(rows[0]?.count).toBe(1); + }); + + test('enforces Vault cutoff when wired into createPostgresTrialRefLookupPort', async () => { + const f = await createIsolatedFixture(); + await f.setupPool.query( + `INSERT INTO trial_ledger ( + trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash, + sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series + ) + OVERRIDING SYSTEM VALUE + VALUES + (1, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-29'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[]), + (2, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-30'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])` + ); + + const appName = `copilot_vault_${randomUUID().slice(0, 8)}`; + const handle = await openResearchCopilotExecutor({ + postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName), + }); + cleanup.push(() => handle.close()); + + const trialLookup = createPostgresTrialRefLookupPort({ + executor: handle.executor, + vaultCutoffTs: VAULT_CUTOFF_TS, + schema: f.schema, + }); + + expect(await trialLookup.hasResearchVisibleTrial('1')).toBe(true); + expect(await trialLookup.hasResearchVisibleTrial('2')).toBe(false); + }); + + test('caps concurrent backend connections at 4 and disconnects all backends on close()', async () => { + const f = await createIsolatedFixture(); + const appName = `copilot_cap_${randomUUID().slice(0, 8)}`; + const handle = await openResearchCopilotExecutor({ + postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName), + }); + cleanup.push(() => handle.close()); + + const results = await Promise.all( + Array.from({ length: RESEARCH_COPILOT_PG_POOL_MAX + 2 }, () => + handle.executor.query<{ pid: number }>( + 'SELECT pg_backend_pid() AS pid FROM pg_sleep(0.15)' + ) + ) + ); + const distinctPids = new Set(results.map(r => r.rows[0]?.pid)); + expect(distinctPids.size).toBeGreaterThanOrEqual(1); + expect(distinctPids.size).toBeLessThanOrEqual(RESEARCH_COPILOT_PG_POOL_MAX); + + await handle.close(); + + const remainingBackends = await waitForZeroBackends(f.admin, appName); + expect(remainingBackends).toBe(0); + + let caught: unknown; + try { + await handle.executor.query('SELECT 1'); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); + expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED'); + }); +}); diff --git a/test/unit/m2-completion-audit-doc.test.ts b/test/unit/m2-completion-audit-doc.test.ts new file mode 100644 index 00000000..66017991 --- /dev/null +++ b/test/unit/m2-completion-audit-doc.test.ts @@ -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\)\*\* \|.*\|.*\|$/); + }); +}); diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 3dd73999..14a59bdd 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1833,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>`) atomically to `/macro/part.parquet` (6-column Zstd contract schema); deferred: CLI command (`curate-macro`), `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>`) atomically to `/macro/part.parquet` (6-column Zstd contract schema); deferred: `macroAsOf` DuckDB reader and live MongoDB access. ## Zero-Copy `teData` BSON Decoder (`M2.2p`) @@ -1856,4 +1856,19 @@ curate-etl send-ilp \ - **Caller-owned series-map TSV (`load_macro_series_map_tsv`):** Requires the exact line-1 header `te_symbolcountrycategorycountry_isoindicatorlag_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 `/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 `curate-macro` CLI / `--from-mongo` wiring are separate follow-ups. +- **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 `/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 `, `--series-map `, and `--out ` 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_symbolcountrycategorycountry_isoindicatorlag_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 `/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 `/macro/part.parquet`; CLI parse errors print `error: ...` followed by `Usage:` to stderr and exit non-zero. diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index c6801d59..aebd72c8 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -188,7 +188,7 @@ pub fn format_usage(name: &str, version: &str) -> String { Curate point-in-time fundamentals from qmFinancials (+ optional qmFinancials-old) + qmFilings BSON or read-only MongoDB + provider_mapping/listing_venues TSVs into fundamentals_pit/year=YYYY/part.parquet (defaults: --financials-key-field {DEFAULT_QM_FINANCIALS_KEY_FIELD}, --period-end-field {DEFAULT_QM_FINANCIALS_PERIOD_END_FIELD}, --report-date-field {DEFAULT_QM_FINANCIALS_REPORT_DATE_FIELD}, --report-period-field {DEFAULT_QM_FINANCIALS_REPORT_PERIOD_FIELD}, --filings-key-field {DEFAULT_FILINGS_KEY_FIELD}, --filings-timefiled-field {DEFAULT_FILINGS_TIMEFILED_FIELD}, --mapping-source {DEFAULT_FUNDAMENTALS_MAPPING_SOURCE})\n\ {name} curate-macro --te-data --series-map --out \n\ {name} curate-macro --from-mongo [--mongo-uri-env | --mongo-uri ] [--batch-size ] [--limit ] --series-map --out \n\ - Curate macroeconomic series from teData BSON or read-only MongoDB + caller-owned series_map TSV into macro/part.parquet\n\ + Curate macroeconomic series from teData BSON or read-only MongoDB + caller-owned series_map TSV into /macro/part.parquet\n\ {name} send-ilp --dir --prefix --addr \n\ Stream published ILP v2 shard files to an explicit QuestDB TCP endpoint (no default address; success means bytes were accepted by local sockets, not rows committed — verify row counts via PGWire; ILP v2 binary doubles over TCP on QuestDB 10.2.0 are unverified until the manual quant load check)\n\ {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ @@ -2314,6 +2314,10 @@ fn parse_curate_bars_1m_args(args: &[&str]) -> Result { } fn parse_curate_qm_bars_1m_args(args: &[&str]) -> Result { + parse_curate_qm_bars_1m_args_inner(args).map_err(|e| sanitize_single_line(&e)) +} + +fn parse_curate_qm_bars_1m_args_inner(args: &[&str]) -> Result { let mut mongo = MongoFlagState::default(); let mut intraday_path: Option = None; let mut curate_inputs: Option = None; @@ -2341,6 +2345,26 @@ fn parse_curate_qm_bars_1m_args(args: &[&str]) -> Result { continue; } + let flag_name = token.split_once('=').map_or(token, |(k, _)| k); + if !matches!( + flag_name, + "--mongo-uri" + | "--mongo-uri-env" + | "--batch-size" + | "--limit" + | "--date-gte" + | "--date-lt" + | "--qm-intraday" + | "--curate-inputs" + | "--provider-mapping" + | "--out" + | "--shards" + | "--known-at-micros" + | "--mapping-source" + ) { + return Err(format!("unknown flag '{flag_name}' for curate-qm-bars-1m")); + } + let (flag, value) = if let Some((k, v)) = token.split_once('=') { i += 1; (k, v) @@ -2577,6 +2601,10 @@ fn parse_curate_fx_1m_args(args: &[&str]) -> Result { } fn parse_curate_macro_args(args: &[&str]) -> Result { + parse_curate_macro_args_inner(args).map_err(|e| sanitize_single_line(&e)) +} + +fn parse_curate_macro_args_inner(args: &[&str]) -> Result { let mut mongo = MongoFlagState::default(); let mut te_data: Option = None; let mut series_map: Option = None; @@ -2600,6 +2628,20 @@ fn parse_curate_macro_args(args: &[&str]) -> Result { continue; } + let flag_name = token.split_once('=').map_or(token, |(flag, _)| flag); + if !matches!( + flag_name, + "--mongo-uri" + | "--mongo-uri-env" + | "--batch-size" + | "--limit" + | "--te-data" + | "--series-map" + | "--out" + ) { + return Err(format!("unknown flag '{flag_name}' for curate-macro")); + } + let (flag, value) = if let Some((k, v)) = token.split_once('=') { i += 1; (k, v) @@ -5146,6 +5188,379 @@ mod tests { )); } + #[test] + fn parse_curate_qm_bars_1m_valid_default_and_explicit_mapping_source() { + let parsed = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--qm-intraday", + "qm_intraday.bson", + "--provider-mapping", + "mapping.tsv", + "--out", + "out_dir", + "--shards", + "4", + "--known-at-micros", + "1735689600000000", + ])) + .expect("valid curate-qm-bars-1m args with default mapping source"); + + assert_eq!( + parsed, + CliAction::CurateQmBars1m(CurateQmBars1mArgs { + intraday_path: PathBuf::from("qm_intraday.bson"), + provider_mapping_path: PathBuf::from("mapping.tsv"), + out_dir: PathBuf::from("out_dir"), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count: 4, + known_at_micros: 1_735_689_600_000_000, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + ); + assert_eq!(DEFAULT_QM_BARS_1M_MAPPING_SOURCE, "qm"); + + let parsed_eq = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--qm-intraday=i2.bson", + "--provider-mapping=m2.tsv", + "--out=o2", + "--shards=2", + "--known-at-micros=9223372036854775807", + "--mapping-source=qm_alt", + ])) + .expect("valid curate-qm-bars-1m args with equals form and explicit mapping source"); + + assert_eq!( + parsed_eq, + CliAction::CurateQmBars1m(CurateQmBars1mArgs { + intraday_path: PathBuf::from("i2.bson"), + provider_mapping_path: PathBuf::from("m2.tsv"), + out_dir: PathBuf::from("o2"), + mapping_source: "qm_alt".to_string(), + shard_count: 2, + known_at_micros: i64::MAX, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }) + ); + } + + #[test] + fn curate_qm_bars_1m_usage_mentions_command_and_all_flags() { + let expected_flags = [ + "--qm-intraday", + "--provider-mapping", + "--out", + "--shards", + "--known-at-micros", + "--mapping-source", + ]; + let usage = format_usage("curate-etl", "0.1.0"); + let usage_stderr = format_usage_stderr("curate-etl"); + let usage_line = usage + .lines() + .find(|line| line.trim_start().starts_with("curate-etl curate-qm-bars-1m ")) + .expect("format_usage missing curate-qm-bars-1m command line"); + let stderr_line = usage_stderr + .lines() + .find(|line| line.trim_start().starts_with("curate-etl curate-qm-bars-1m ")) + .expect("format_usage_stderr missing curate-qm-bars-1m command line"); + for flag in expected_flags { + assert!( + usage_line.contains(flag), + "format_usage curate-qm-bars-1m line missing {flag}: {usage_line}" + ); + assert!( + stderr_line.contains(flag), + "format_usage_stderr curate-qm-bars-1m line missing {flag}: {stderr_line}" + ); + } + assert!( + !usage_line.contains("--qm-splits"), + "format_usage curate-qm-bars-1m line must not list --qm-splits: {usage_line}" + ); + assert!( + !stderr_line.contains("--qm-splits"), + "format_usage_stderr curate-qm-bars-1m line must not list --qm-splits: {stderr_line}" + ); + } + + #[test] + fn parse_curate_qm_bars_1m_rejects_missing_required_flags() { + let required: [(&str, &str); 5] = [ + ("--qm-intraday", "qm_intraday.bson"), + ("--provider-mapping", "mapping.tsv"), + ("--out", "out_dir"), + ("--shards", "2"), + ("--known-at-micros", "1735689600000000"), + ]; + + for omit in 0..required.len() { + let mut argv: Vec<&str> = vec!["curate-qm-bars-1m"]; + for (idx, &(flag, val)) in required.iter().enumerate() { + if idx != omit { + argv.push(flag); + argv.push(val); + } + } + let err = parse_args(&to_args(&argv)).unwrap_err(); + let missing_flag = required[omit].0; + assert!( + err.contains(&format!("missing required flag '{missing_flag}'")), + "expected missing required flag '{missing_flag}', got: {err}" + ); + } + } + + #[test] + fn parse_curate_qm_bars_1m_rejects_duplicates_empty_missing_value_unknown_and_positional() { + let base = [ + "curate-qm-bars-1m", + "--qm-intraday", + "i.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + "--mapping-source", + "qm", + ]; + + // Duplicate flags (path, numeric, and name). + for (flag, extra_val) in [ + ("--qm-intraday", "i2.bson"), + ("--provider-mapping", "m2.tsv"), + ("--out", "o2"), + ("--shards", "3"), + ("--known-at-micros", "2000"), + ("--mapping-source", "qm"), + ] { + let mut argv = base.to_vec(); + argv.push(flag); + argv.push(extra_val); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains(&format!("duplicate flag '{flag}'")), + "expected duplicate error for {flag}, got: {err}" + ); + } + + // Empty values via --flag= and whitespace-only --mapping-source. + for flag in [ + "--qm-intraday", + "--provider-mapping", + "--out", + "--shards", + "--known-at-micros", + "--mapping-source", + ] { + let empty_token = format!("{flag}="); + let err = parse_args(&to_args(&["curate-qm-bars-1m", &empty_token])).unwrap_err(); + assert!( + err.contains(&format!("empty value for flag '{flag}'")), + "expected empty value error for {flag}, got: {err}" + ); + } + let err = + parse_args(&to_args(&["curate-qm-bars-1m", "--mapping-source", " "])).unwrap_err(); + assert!( + err.contains("empty value for flag '--mapping-source'"), + "{err}" + ); + + // Flag at end of input or followed by another flag. + let err = parse_args(&to_args(&["curate-qm-bars-1m", "--qm-intraday"])).unwrap_err(); + assert!( + err.contains("missing value for flag '--qm-intraday'"), + "{err}" + ); + let err = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--shards", + "--out", + "o", + ])) + .unwrap_err(); + assert!(err.contains("missing value for flag '--shards'"), "{err}"); + + // Unknown flags (including curate-bars-1m-only flags --qm-splits and --eod-intraday), + // both with a value and bare (without consuming a value first). + for unknown_flag in ["--nope", "--qm-splits", "--eod-intraday"] { + let mut unknown = base.to_vec(); + unknown.push(unknown_flag); + unknown.push("x"); + let err = parse_args(&to_args(&unknown)).unwrap_err(); + assert!( + err.contains(&format!("unknown flag '{unknown_flag}' for curate-qm-bars-1m")), + "expected unknown flag error for {unknown_flag}, got: {err}" + ); + + let err_bare = parse_args(&to_args(&["curate-qm-bars-1m", unknown_flag])).unwrap_err(); + assert!( + err_bare.contains(&format!("unknown flag '{unknown_flag}' for curate-qm-bars-1m")), + "expected unknown flag error for bare {unknown_flag}, got: {err_bare}" + ); + } + + // Positional argument. + let err = parse_args(&to_args(&["curate-qm-bars-1m", "positional"])).unwrap_err(); + assert!( + err.contains("unexpected positional argument 'positional' for curate-qm-bars-1m"), + "{err}" + ); + + // Multiline error sanitization (CR/LF escaped to single line). + let err = parse_args(&to_args(&["curate-qm-bars-1m", "bad\r\narg"])).unwrap_err(); + assert!( + !err.contains('\r') && !err.contains('\n'), + "error must be single-line: {err:?}" + ); + assert!(err.contains("bad\\r\\narg"), "expected escaped CR/LF: {err}"); + } + + #[test] + fn parse_curate_qm_bars_1m_rejects_invalid_numeric_flags() { + let base_without_shards = [ + "curate-qm-bars-1m", + "--qm-intraday", + "i.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--known-at-micros", + "1000", + ]; + + for bad_shards in [ + "0", + "-1", + "+1", + "abc", + "1.5", + "999999999999999999999999999999999999999", + ] { + let mut argv = base_without_shards.to_vec(); + argv.push("--shards"); + argv.push(bad_shards); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains("invalid --shards"), + "expected invalid --shards for '{bad_shards}', got: {err}" + ); + } + + let base_without_known_at = [ + "curate-qm-bars-1m", + "--qm-intraday", + "i.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + ]; + + for bad_known_at in [ + "0", + "-1", + "-9223372036854775808", + "+1000", + "abc", + "1.5", + "9223372036854775808", + "999999999999999999999999999999", + ] { + let mut argv = base_without_known_at.to_vec(); + argv.push("--known-at-micros"); + argv.push(bad_known_at); + let err = parse_args(&to_args(&argv)).unwrap_err(); + assert!( + err.contains("invalid --known-at-micros"), + "expected invalid --known-at-micros for '{bad_known_at}', got: {err}" + ); + } + } + + #[test] + fn parse_curate_qm_bars_1m_mongo_flags_and_mixing_rules_hide_secrets() { + let secret = "mongodb://user:s3cr3t_pw@localhost:27017/stock"; + + // Mongo options without --from-mongo fail with clear message and no secret leak. + let err = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--qm-intraday", + "i.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + &format!("--mongo-uri={secret}"), + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err.contains("s3cr3t_pw")); + + let err_sep = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--qm-intraday", + "i.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + "--mongo-uri", + secret, + ])) + .unwrap_err(); + assert_eq!(err_sep, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err_sep.contains("s3cr3t_pw")); + + // --with-qm-prices is not a curate-qm-bars-1m flag and must not echo values. + let err_qm = parse_args(&to_args(&[ + "curate-qm-bars-1m", + &format!("--with-qm-prices={secret}"), + ])) + .unwrap_err(); + assert_eq!( + err_qm, + "unknown flag '--with-qm-prices' for curate-qm-bars-1m" + ); + assert!(!err_qm.contains("s3cr3t_pw")); + + // Combining --from-mongo with --qm-intraday fails closed. + let err = parse_args(&to_args(&[ + "curate-qm-bars-1m", + "--from-mongo", + "--qm-intraday", + "i.bson", + "--provider-mapping", + "m.tsv", + "--out", + "o", + "--shards", + "2", + "--known-at-micros", + "1000", + ])) + .unwrap_err(); + assert_eq!(err, "cannot combine '--from-mongo' with '--qm-intraday'"); + } + #[test] fn parse_curate_fx_1m_valid_space_and_equals_forms() { let expected = CliAction::CurateFx1m(CurateFx1mArgs { @@ -6355,6 +6770,234 @@ mod tests { assert!(err.contains("bad\\nline\\rarg"), "{err:?}"); } + #[test] + fn curate_macro_parsing_validation_and_usage() { + let usage = format_usage("curate-etl", "0.1.0"); + let stderr_usage = format_usage_stderr("curate-etl"); + for text in [&usage, &stderr_usage] { + assert!( + text.contains("curate-macro --te-data --series-map --out "), + "{text}" + ); + } + assert!(usage.contains("/macro/part.parquet"), "{usage}"); + assert!(usage.contains("curate-macro --from-mongo"), "{usage}"); + + let expected = CliAction::CurateMacro(CurateMacroArgs { + te_data: PathBuf::from("teData.bson"), + series_map: PathBuf::from("macro_series_map.tsv"), + out_dir: PathBuf::from("macro_out"), + }); + + // Happy path: space-separated flags + assert_eq!( + parse_args(&to_args(&[ + "curate-macro", + "--te-data", + "teData.bson", + "--series-map", + "macro_series_map.tsv", + "--out", + "macro_out", + ])), + Ok(expected.clone()) + ); + + // Reordered flags with mixed `--flag value` and `--flag=value` forms + assert_eq!( + parse_args(&to_args(&[ + "curate-macro", + "--out=macro_out", + "--te-data", + "teData.bson", + "--series-map=macro_series_map.tsv", + ])), + Ok(expected.clone()) + ); + + // All `--flag=value` form in another order + assert_eq!( + parse_args(&to_args(&[ + "curate-macro", + "--series-map=macro_series_map.tsv", + "--out=macro_out", + "--te-data=teData.bson", + ])), + Ok(expected) + ); + + // `--flag=value` with `=` inside path and `--`-prefixed literal dir + assert_eq!( + parse_args(&to_args(&[ + "curate-macro", + "--te-data=/tmp/year=2025/teData.bson", + "--series-map=/tmp/v=1/series-map.tsv", + "--out=--literal-dir", + ])), + Ok(CliAction::CurateMacro(CurateMacroArgs { + te_data: PathBuf::from("/tmp/year=2025/teData.bson"), + series_map: PathBuf::from("/tmp/v=1/series-map.tsv"), + out_dir: PathBuf::from("--literal-dir"), + })) + ); + + // Bare `curate-macro` fails with missing required flag + let err = parse_args(&to_args(&["curate-macro"])).unwrap_err(); + assert_eq!(err, "missing required flag '--te-data'"); + + // Omission of each required flag + let required: [(&str, &str); 3] = [ + ("--te-data", "teData.bson"), + ("--series-map", "macro_series_map.tsv"), + ("--out", "macro_out"), + ]; + for omit in 0..required.len() { + let mut argv = vec!["curate-macro"]; + for (idx, &(flag, val)) in required.iter().enumerate() { + if idx != omit { + argv.push(flag); + argv.push(val); + } + } + let err = parse_args(&to_args(&argv)).unwrap_err(); + let missing_flag = required[omit].0; + assert_eq!(err, format!("missing required flag '{missing_flag}'")); + } + + // Missing value at end or before another flag + for (args, expected_flag) in [ + (&["curate-macro", "--te-data"][..], "--te-data"), + (&["curate-macro", "--series-map"][..], "--series-map"), + (&["curate-macro", "--out"][..], "--out"), + ( + &["curate-macro", "--te-data", "--out", "macro_out"][..], + "--te-data", + ), + ( + &["curate-macro", "--series-map", "--te-data", "teData.bson"][..], + "--series-map", + ), + ] { + let err = parse_args(&to_args(args)).unwrap_err(); + assert_eq!(err, format!("missing value for flag '{expected_flag}'")); + } + + // Empty values in both `--flag=` and `--flag ""` forms + for (args, expected_flag) in [ + (&["curate-macro", "--te-data="][..], "--te-data"), + (&["curate-macro", "--series-map="][..], "--series-map"), + (&["curate-macro", "--out="][..], "--out"), + (&["curate-macro", "--te-data", ""][..], "--te-data"), + (&["curate-macro", "--series-map", ""][..], "--series-map"), + (&["curate-macro", "--out", ""][..], "--out"), + ] { + let err = parse_args(&to_args(args)).unwrap_err(); + assert_eq!(err, format!("empty value for flag '{expected_flag}'")); + } + + // Duplicate flags across forms + for (dup_flag, args) in [ + ( + "--te-data", + &[ + "curate-macro", + "--te-data", + "a.bson", + "--te-data=b.bson", + "--series-map", + "map.tsv", + "--out", + "out", + ][..], + ), + ( + "--series-map", + &[ + "curate-macro", + "--series-map=a.tsv", + "--series-map", + "b.tsv", + "--te-data", + "te.bson", + "--out", + "out", + ][..], + ), + ( + "--out", + &[ + "curate-macro", + "--out", + "out1", + "--out=out2", + "--te-data", + "te.bson", + "--series-map", + "map.tsv", + ][..], + ), + ] { + let err = parse_args(&to_args(args)).unwrap_err(); + assert_eq!(err, format!("duplicate flag '{dup_flag}'")); + } + + // Unknown flags and MongoDB flag-mixing rules (with secret redaction) + let err = parse_args(&to_args(&["curate-macro", "--bogus", "1"])).unwrap_err(); + assert_eq!(err, "unknown flag '--bogus' for curate-macro"); + + let err = parse_args(&to_args(&["curate-macro", "--from-mongo=true"])).unwrap_err(); + assert_eq!(err, "unknown flag '--from-mongo' for curate-macro"); + + let err = parse_args(&to_args(&[ + "curate-macro", + "--from-mongo", + "--te-data", + "te.bson", + "--series-map", + "map.tsv", + "--out", + "o", + ])) + .unwrap_err(); + assert_eq!(err, "cannot combine '--from-mongo' with '--te-data'"); + + let err = parse_args(&to_args(&[ + "curate-macro", + "--te-data", + "te.bson", + "--series-map", + "map.tsv", + "--out", + "o", + "--mongo-uri", + "mongodb://user:s3cr3t@host:27017/stock", + ])) + .unwrap_err(); + assert_eq!(err, "MongoDB streaming flags require '--from-mongo'"); + assert!(!err.contains("s3cr3t")); + + // Unexpected positional arguments rejected (including single-dash token) + for pos in ["extra", "-x"] { + let err = parse_args(&to_args(&["curate-macro", pos])).unwrap_err(); + assert_eq!( + err, + format!("unexpected positional argument '{pos}' for curate-macro") + ); + } + + // CR/LF in arguments are escaped to a single diagnostic line + let err = parse_args(&to_args(&["curate-macro", "bad\nline\rarg"])).unwrap_err(); + assert!(!err.contains('\n') && !err.contains('\r'), "{err:?}"); + assert_eq!( + err, + "unexpected positional argument 'bad\\nline\\rarg' for curate-macro" + ); + + let err = parse_args(&to_args(&["curate-macro", "--bad\nflag\r=1"])).unwrap_err(); + assert!(!err.contains('\n') && !err.contains('\r'), "{err:?}"); + assert_eq!(err, "unknown flag '--bad\\nflag\\r' for curate-macro"); + } + #[test] fn parse_send_ilp_valid_space_and_equals_forms_and_all_allowed_prefixes() { for prefix in ["bars_1m", "bars_1m_qm", "fx_1m"] { diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 6b63b16a..55fdab41 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -236,7 +236,8 @@ fn main() -> ExitCode { ExitCode::SUCCESS } Err(err) => { - eprintln!("error: {err}"); + let msg = err.to_string().replace('\r', "\\r").replace('\n', "\\n"); + eprintln!("error: {msg}"); ExitCode::FAILURE } }, @@ -247,7 +248,8 @@ fn main() -> ExitCode { ExitCode::SUCCESS } Err(err) => { - eprintln!("error: {err}"); + let msg = err.to_string().replace('\r', "\\r").replace('\n', "\\n"); + eprintln!("error: {msg}"); ExitCode::FAILURE } } diff --git a/tools/curate-etl/src/run_mongo_tests.rs b/tools/curate-etl/src/run_mongo_tests.rs index 3754b1a9..fa5c7b73 100644 --- a/tools/curate-etl/src/run_mongo_tests.rs +++ b/tools/curate-etl/src/run_mongo_tests.rs @@ -412,11 +412,13 @@ fn parity_curate_1m_ilp_mongo_cursors_match_file_mode_byte_for_byte() { ) .unwrap(); - // qmSplits: 10:1 split on 2024-06-10 + // qmSplits: 10:1 forward split on 2024-06-10 (QuoteMedia stores splitratio = old / new = 0.1) let mut sp = RawDocumentBuf::new(); sp.append(cstr!("qmSearchCode"), "NVDA:US"); sp.append(cstr!("date"), "2024-06-10"); - sp.append(cstr!("splitratio"), 10.0_f64); + sp.append(cstr!("forfactor"), 1.0_f64); + sp.append(cstr!("tofactor"), 10.0_f64); + sp.append(cstr!("splitratio"), 0.1_f64); let split_docs = vec![sp.into_bytes()]; // eodIntraday1M: equity bar + CAD.FOREX bar @@ -1360,11 +1362,14 @@ fn parity_curate_1m_ilp_filtered_multi_key_cross_chunk_matches_economic_rows_and ) .unwrap(); - // 10:1 split for NVDA (listing 301) on 2024-06-10; AAPL (listing 302) has no split. + // 10:1 forward split for NVDA (listing 301) on 2024-06-10 (QuoteMedia stores + // `splitratio = forfactor / tofactor = old_shares / new_shares = 0.1`); AAPL has no split. let mut sp = RawDocumentBuf::new(); sp.append(cstr!("qmSearchCode"), "NVDA:US"); sp.append(cstr!("date"), "2024-06-10"); - sp.append(cstr!("splitratio"), 10.0_f64); + sp.append(cstr!("forfactor"), 1.0_f64); + sp.append(cstr!("tofactor"), 10.0_f64); + sp.append(cstr!("splitratio"), 0.1_f64); let split_docs = vec![sp.into_bytes()]; let splits_path = tmp.path().join("qmSplits.bson"); fs::write(&splits_path, concat_docs(&split_docs)).unwrap(); diff --git a/tools/curate-etl/tests/curate_macro.rs b/tools/curate-etl/tests/curate_macro.rs new file mode 100644 index 00000000..e990f891 --- /dev/null +++ b/tools/curate-etl/tests/curate_macro.rs @@ -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 = 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: cannot combine '--from-mongo' with '--te-data'", + ), + ( + &[ + "--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 --series-map --out "), + "{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 = 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 --series-map --out "), + "{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` requires `--from-mongo`; mixing it into file mode fails 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: MongoDB streaming flags require '--from-mongo'\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" + ); +} diff --git a/tools/curate-etl/tests/curate_qm_bars_1m.rs b/tools/curate-etl/tests/curate_qm_bars_1m.rs new file mode 100644 index 00000000..4d530a52 --- /dev/null +++ b/tools/curate-etl/tests/curate_qm_bars_1m.rs @@ -0,0 +1,687 @@ +//! End-to-end binary integration tests for `curate-etl curate-qm-bars-1m` (`M2.3r`). + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use bson::raw::{cstr, RawDocumentBuf}; +use bson::DateTime as BsonDateTime; +use curate_etl::bars_1m::BARS_1M_SOURCE_QM; +use curate_etl::ilp::{ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M}; +use curate_etl::{ + et_to_utc_micros, format_curate_qm_bars_1m_report, run_curate_qm_bars_1m, ymd_to_epoch_days, + BsonStreamOptions, CurateQmBars1mArgs, IlpWriterOptions, DEFAULT_QM_BARS_1M_MAPPING_SOURCE, +}; + +static TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct TempDir { + path: PathBuf, +} + +impl TempDir { + fn new(tag: &str) -> Self { + let pid = std::process::id(); + let seq = TEST_DIR_SEQ.fetch_add(1, Ordering::Relaxed); + let path = + std::env::temp_dir().join(format!("curate-etl-it-qm-bars-1m-{tag}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create integration test temp dir"); + Self { path } + } + + fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +fn run_bin(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(args) + .output() + .expect("spawn curate-etl binary") +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn et_ts_millis(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { + let micros = et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp"); + assert_eq!(micros % 1_000, 0); + micros / 1_000 +} + +fn make_qm_intraday_doc( + code: &str, + timestamp_ms: i64, + open: f64, + high: f64, + low: f64, + close: f64, + sharevolume: f64, +) -> RawDocumentBuf { + let mut doc = RawDocumentBuf::new(); + doc.append(cstr!("qmSearchCode"), code); + doc.append(cstr!("timestamp"), BsonDateTime::from_millis(timestamp_ms)); + doc.append(cstr!("open"), open); + doc.append(cstr!("high"), high); + doc.append(cstr!("low"), low); + doc.append(cstr!("close"), close); + doc.append(cstr!("sharevolume"), sharevolume); + doc +} + +#[allow(clippy::too_many_arguments)] +fn make_qm_intraday_doc_with_adjusted( + code: &str, + timestamp_ms: i64, + open: f64, + high: f64, + low: f64, + close: f64, + sharevolume: f64, + adj_scale: f64, +) -> RawDocumentBuf { + let mut doc = make_qm_intraday_doc(code, timestamp_ms, open, high, low, close, sharevolume); + doc.append(cstr!("adjustedopen"), open / adj_scale); + doc.append(cstr!("adjustedhigh"), high / adj_scale); + doc.append(cstr!("adjustedlow"), low / adj_scale); + doc.append(cstr!("adjustedclose"), close / adj_scale); + doc.append(cstr!("avolume"), sharevolume * adj_scale); + doc +} + +fn concat_docs(docs: &[RawDocumentBuf]) -> Vec { + let mut out = Vec::new(); + for doc in docs { + out.extend_from_slice(doc.as_bytes()); + } + out +} + +fn read_dir_files(dir: &Path) -> BTreeMap> { + let mut out = BTreeMap::new(); + for entry in fs::read_dir(dir).expect("read output dir") { + let entry = entry.expect("dir entry"); + let name = entry + .file_name() + .into_string() + .expect("UTF-8 file name in output dir"); + let bytes = fs::read(entry.path()).expect("read output file"); + out.insert(name, bytes); + } + out +} + +fn strip_timing_line(report: &str) -> Vec<&str> { + report + .lines() + .filter(|line| !line.trim_start().starts_with("timing:")) + .collect() +} + +fn shard_and_staging_files(dir: &Path) -> Vec { + if !dir.exists() { + return Vec::new(); + } + read_dir_files(dir).into_keys().collect() +} + +#[derive(Debug)] +struct IlpRow { + table: String, + listing_id: i32, + source: String, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, + known_at: i64, + ts: i64, +} + +/// Minimal ILP v2 `bars_1m` decoder respecting 8-byte binary `DOUBLE` payloads (`==\x10<8 LE>`) +/// so embedded `0x0a` bytes inside doubles never split rows. +fn decode_rows(data: &[u8]) -> Vec { + let mut rows = Vec::new(); + let mut i = 0usize; + while i < data.len() { + let tag_start = i; + while data[i] != b' ' { + i += 1; + } + let tags = std::str::from_utf8(&data[tag_start..i]).expect("valid UTF-8 tags"); + i += 1; + + let mut parts = tags.split(','); + let table = parts.next().expect("table name").to_string(); + let listing_id: i32 = parts + .next() + .expect("listing_id tag") + .strip_prefix("listing_id=") + .expect("listing_id= prefix") + .parse() + .expect("i32 listing_id"); + let _session = parts.next().expect("session tag"); + let source = parts + .next() + .expect("source tag") + .strip_prefix("source=") + .expect("source= prefix") + .to_string(); + assert!(parts.next().is_none(), "unexpected extra ILP tag"); + + let mut read_f64 = |name: &str| -> f64 { + let prefix = format!("{name}=="); + assert!( + data[i..].starts_with(prefix.as_bytes()), + "expected {prefix} at offset {i}" + ); + i += prefix.len(); + assert_eq!( + data[i], ILP_V2_DOUBLE_TYPE, + "expected binary DOUBLE type tag for {name}" + ); + i += 1; + let v = f64::from_le_bytes(data[i..i + 8].try_into().unwrap()); + i += 8; + if data[i] == b',' { + i += 1; + } + v + }; + let open = read_f64("open"); + let high = read_f64("high"); + let low = read_f64("low"); + let close = read_f64("close"); + let volume = read_f64("volume"); + assert!(data[i..].starts_with(b"known_at="), "expected known_at="); + i += b"known_at=".len(); + let ks = i; + while data[i] != b' ' { + i += 1; + } + let known_at: i64 = std::str::from_utf8(&data[ks..i]) + .unwrap() + .strip_suffix('t') + .unwrap() + .parse() + .unwrap(); + i += 1; + let ts_start = i; + while data[i] != b'\n' { + i += 1; + } + let ts: i64 = std::str::from_utf8(&data[ts_start..i]) + .unwrap() + .strip_suffix('t') + .unwrap() + .parse() + .unwrap(); + i += 1; + rows.push(IlpRow { + table, + listing_id, + source, + open, + high, + low, + close, + volume, + known_at, + ts, + }); + } + rows +} + +struct Fixture { + intraday: PathBuf, + mapping: PathBuf, +} + +/// Synthetic `qmIntraday` fixture: +/// - `NVDA` pre-split bar with distinct `adjusted*`/`avolume` fields (ignored) and embedded `0x0a` +/// float byte in `close`. +/// - `NEXM:CA` bar with `-0.0` `sharevolume` (normalized to `+0.0`). +fn write_qm_fixture(dir: &Path, mapping_source: &str) -> (Fixture, f64) { + let close_with_lf_byte = f64::from_le_bytes([0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59, 0x40]); + assert!(close_with_lf_byte.to_le_bytes().contains(&b'\n')); + + let intraday = dir.join("qmIntraday.bson"); + fs::write( + &intraday, + concat_docs(&[ + make_qm_intraday_doc_with_adjusted( + "NVDA", + et_ts_millis(2024, 6, 7, 15, 59), + 100.0, + 101.0, + 99.5, + close_with_lf_byte, + 412_390.0, + 10.0, + ), + make_qm_intraday_doc_with_adjusted( + "NVDA", + et_ts_millis(2024, 6, 10, 15, 59), + 121.50, + 122.00, + 121.20, + 121.79, + 350_000.0, + 1.0, + ), + make_qm_intraday_doc_with_adjusted( + "NEXM:CA", + et_ts_millis(2025, 6, 18, 15, 59), + 1.21, + 1.22, + 1.20, + 1.215, + -0.0, + 0.05, + ), + ]), + ) + .expect("write qmIntraday.bson"); + + let mapping = dir.join("provider_mapping.tsv"); + fs::write( + &mapping, + format!( + "{mapping_source}\tNVDA\t2000-01-01\t\t1001\n\ + {mapping_source}\tNEXM:CA\t2000-01-01\t\t1002\n" + ), + ) + .expect("write provider_mapping.tsv"); + + (Fixture { intraday, mapping }, close_with_lf_byte) +} + +fn bin_args<'a>( + fx: &'a Fixture, + out: &'a Path, + known_at: &'a str, + extra: &[&'a str], +) -> Vec<&'a str> { + let mut argv = vec![ + "curate-qm-bars-1m", + "--qm-intraday", + fx.intraday.to_str().unwrap(), + "--provider-mapping", + fx.mapping.to_str().unwrap(), + "--out", + out.to_str().unwrap(), + "--shards", + "2", + "--known-at-micros", + known_at, + ]; + argv.extend_from_slice(extra); + argv +} + +#[test] +fn curate_qm_bars_1m_binary_matches_direct_runner_bytes_report_and_invariants() { + let tmp = TempDir::new("parity"); + let (fx, close_with_lf_byte) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE); + + let known_at_micros: i64 = 1_750_000_000_123_456; + let shard_count: usize = 2; + + let bin_out = tmp.path().join("out-bin"); + let bin_out_repeat = tmp.path().join("out-bin-repeat"); + let direct_out = tmp.path().join("out-direct"); + + let output = run_bin(&bin_args(&fx, &bin_out, "1750000000123456", &[])); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success(), + "expected exit 0, got {:?}; stderr:\n{stderr}\nstdout:\n{stdout}", + output.status.code() + ); + assert!( + stderr.is_empty(), + "expected empty stderr on success, got:\n{stderr}" + ); + + let direct_args = CurateQmBars1mArgs { + intraday_path: fx.intraday.clone(), + provider_mapping_path: fx.mapping.clone(), + out_dir: direct_out.clone(), + mapping_source: DEFAULT_QM_BARS_1M_MAPPING_SOURCE.to_string(), + shard_count, + known_at_micros, + stream_options: BsonStreamOptions::default(), + ilp_options: IlpWriterOptions::default(), + }; + let direct_report = run_curate_qm_bars_1m(&direct_args).expect("direct run_curate_qm_bars_1m"); + assert_eq!(direct_report.rows_written, 3, "expected 3 emitted rows"); + assert_eq!( + direct_report.intraday_decode.rejected_total(), + 0, + "expected zero rejected BSON documents" + ); + + let direct_formatted = format_curate_qm_bars_1m_report(&direct_report); + assert_eq!( + strip_timing_line(&stdout), + strip_timing_line(&direct_formatted), + "binary stdout report must match direct runner report excluding timing line" + ); + assert!( + stdout + .lines() + .any(|line| line.trim_start().starts_with("timing: elapsed_secs=")), + "expected timing line in stdout:\n{stdout}" + ); + + let bin_files = read_dir_files(&bin_out); + let direct_files = read_dir_files(&direct_out); + let expected_names = vec![ + "bars_1m_qm.shard-00.ilp".to_string(), + "bars_1m_qm.shard-01.ilp".to_string(), + ]; + assert_eq!( + bin_files.keys().cloned().collect::>(), + expected_names, + "unexpected files in binary output dir" + ); + assert_eq!( + bin_files, direct_files, + "binary shard files must be byte-identical to direct runner output" + ); + + // Determinism across repeat runs. + let repeat = run_bin(&bin_args(&fx, &bin_out_repeat, "1750000000123456", &[])); + assert!(repeat.status.success()); + assert_eq!( + bin_files, + read_dir_files(&bin_out_repeat), + "repeat runs must be byte-identical" + ); + assert_eq!( + strip_timing_line(&stdout), + strip_timing_line(&String::from_utf8_lossy(&repeat.stdout)), + ); + + // Decode all ILP rows across shards and verify row count + financial invariants. + let mut rows: Vec = bin_files + .values() + .flat_map(|bytes| decode_rows(bytes)) + .collect(); + assert_eq!( + rows.len(), + direct_report.rows_written, + "decoded ILP row count must equal reported rows_written" + ); + rows.sort_by_key(|r| (r.listing_id, r.ts)); + + for row in &rows { + assert_eq!(row.table, TABLE_BARS_1M); + assert_eq!(row.source, BARS_1M_SOURCE_QM); + assert_eq!(row.known_at, known_at_micros); + } + + // NVDA pre-split row: raw OHLCV bit-identical (adjusted* fields ignored), embedded 0x0a intact. + let nvda_pre = &rows[0]; + assert_eq!(nvda_pre.listing_id, 1001); + assert_eq!(nvda_pre.ts, et_ts_millis(2024, 6, 7, 15, 59) * 1_000); + assert_eq!(nvda_pre.open.to_bits(), 100.0_f64.to_bits()); + assert_eq!(nvda_pre.high.to_bits(), 101.0_f64.to_bits()); + assert_eq!(nvda_pre.low.to_bits(), 99.5_f64.to_bits()); + assert_eq!(nvda_pre.close.to_bits(), close_with_lf_byte.to_bits()); + assert_eq!(nvda_pre.volume.to_bits(), 412_390.0_f64.to_bits()); + + // NVDA post-split row (adj_scale 1.0): raw OHLCV bit-identical, no un-adjustment applied. + let nvda_post = &rows[1]; + assert_eq!(nvda_post.listing_id, 1001); + assert_eq!(nvda_post.ts, et_ts_millis(2024, 6, 10, 15, 59) * 1_000); + assert_eq!(nvda_post.open.to_bits(), 121.50_f64.to_bits()); + assert_eq!(nvda_post.high.to_bits(), 122.00_f64.to_bits()); + assert_eq!(nvda_post.low.to_bits(), 121.20_f64.to_bits()); + assert_eq!(nvda_post.close.to_bits(), 121.79_f64.to_bits()); + assert_eq!(nvda_post.volume.to_bits(), 350_000.0_f64.to_bits()); + + // NEXM:CA row: raw OHLC bit-identical, -0.0 sharevolume normalized to +0.0. + let nexm = &rows[2]; + assert_eq!(nexm.listing_id, 1002); + assert_eq!(nexm.ts, et_ts_millis(2025, 6, 18, 15, 59) * 1_000); + assert_eq!(nexm.open.to_bits(), 1.21_f64.to_bits()); + assert_eq!(nexm.high.to_bits(), 1.22_f64.to_bits()); + assert_eq!(nexm.low.to_bits(), 1.20_f64.to_bits()); + assert_eq!(nexm.close.to_bits(), 1.215_f64.to_bits()); + assert_eq!(nexm.volume.to_bits(), 0.0_f64.to_bits()); +} + +#[test] +fn curate_qm_bars_1m_binary_missing_input_exits_nonzero_single_line_stderr_and_clean_out() { + let tmp = TempDir::new("missing-input"); + let (fx, _) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE); + let missing_intraday = tmp.path().join("does-not-exist.bson"); + let missing_mapping = tmp.path().join("does-not-exist.tsv"); + + for (tag, intraday_path, mapping_path) in [ + ("intraday", &missing_intraday, &fx.mapping), + ("mapping", &fx.intraday, &missing_mapping), + ] { + let out_dir = tmp.path().join(format!("out-empty-{tag}")); + fs::create_dir_all(&out_dir).expect("create empty out dir"); + + let output = run_bin(&[ + "curate-qm-bars-1m", + "--qm-intraday", + intraday_path.to_str().unwrap(), + "--provider-mapping", + mapping_path.to_str().unwrap(), + "--out", + out_dir.to_str().unwrap(), + "--shards", + "2", + "--known-at-micros", + "1750000000000000", + ]); + + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + !output.status.success(), + "expected non-zero exit when {tag} file is missing" + ); + assert!( + stdout.is_empty(), + "expected no success report on stdout for missing {tag}, got:\n{stdout}" + ); + let lines: Vec<&str> = stderr.lines().collect(); + assert_eq!( + lines.len(), + 1, + "expected strictly single-line stderr (no usage block) for missing {tag}, got:\n{stderr}" + ); + assert!( + lines[0].starts_with("error:"), + "expected 'error:' prefix on stderr for missing {tag}, got: {}", + lines[0] + ); + assert!( + shard_and_staging_files(&out_dir).is_empty(), + "expected no shard or staging files in output dir for missing {tag}, found: {:?}", + shard_and_staging_files(&out_dir) + ); + } +} + +#[test] +fn curate_qm_bars_1m_binary_refuses_overwrite_and_coexists_with_eod_bars_1m_shards() { + let tmp = TempDir::new("overwrite-coexist"); + let (fx, _) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE); + let out = tmp.path().join("out"); + fs::create_dir_all(&out).expect("create out dir"); + + // Pre-populate an EOD bars_1m shard in the same directory; QM run must not collide with it. + let eod_sentinel = b"sentinel-eod-bars-1m-shard\n".to_vec(); + fs::write(out.join("bars_1m.shard-00.ilp"), &eod_sentinel).expect("write eod sentinel"); + + let first = run_bin(&bin_args(&fx, &out, "1750000000000000", &[])); + assert!( + first.status.success(), + "QM run should coexist with bars_1m.shard-00.ilp; stderr:\n{}", + String::from_utf8_lossy(&first.stderr) + ); + let before = read_dir_files(&out); + assert_eq!( + before.get("bars_1m.shard-00.ilp"), + Some(&eod_sentinel), + "co-located EOD shard must remain untouched" + ); + assert!(before.contains_key("bars_1m_qm.shard-00.ilp")); + assert!(before.contains_key("bars_1m_qm.shard-01.ilp")); + + // Second run with different known_at must refuse to overwrite existing bars_1m_qm shards. + let second = run_bin(&bin_args(&fx, &out, "1760000000000000", &[])); + assert!( + !second.status.success(), + "second run into populated --out must fail" + ); + assert!(second.stdout.is_empty(), "no success report expected"); + let stderr = String::from_utf8_lossy(&second.stderr); + assert_eq!(stderr.lines().count(), 1, "single-line stderr expected: {stderr}"); + assert!(stderr.starts_with("error:"), "stderr: {stderr}"); + assert_eq!( + read_dir_files(&out), + before, + "existing shards must be untouched and no staging files left" + ); +} + +#[test] +fn curate_qm_bars_1m_binary_supports_custom_mapping_source() { + let tmp = TempDir::new("custom-source"); + let (fx, _) = write_qm_fixture(tmp.path(), "qm_alt"); + let out = tmp.path().join("out"); + + let output = run_bin(&bin_args( + &fx, + &out, + "1750000000000000", + &["--mapping-source=qm_alt"], + )); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "stderr:\n{stderr}"); + assert!(stderr.is_empty()); + + let rows: Vec = read_dir_files(&out) + .values() + .flat_map(|bytes| decode_rows(bytes)) + .collect(); + assert_eq!(rows.len(), 3, "custom --mapping-source should map all 3 rows"); +} + +#[test] +fn curate_qm_bars_1m_binary_parse_error_prints_usage_hides_secret_and_writes_nothing() { + let tmp = TempDir::new("parse-error"); + let (fx, _) = write_qm_fixture(tmp.path(), DEFAULT_QM_BARS_1M_MAPPING_SOURCE); + let out = tmp.path().join("out"); + + let secret = "--mongo-uri=mongodb://user:s3cr3t_pw@localhost:27017/stock"; + let output = run_bin(&bin_args(&fx, &out, "1750000000000000", &[secret])); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("MongoDB streaming flags require '--from-mongo'"), + "stderr: {stderr}" + ); + assert!( + stderr.contains("curate-qm-bars-1m --qm-intraday"), + "usage expected: {stderr}" + ); + assert!(!stderr.contains("s3cr3t_pw"), "secret leaked: {stderr}"); + assert!(!out.exists(), "parse failure must not create --out"); + + // Missing --known-at-micros: no clock fallback, nothing written. + let mut argv = bin_args(&fx, &out, "1", &[]); + argv.truncate(argv.len() - 2); + let output = run_bin(&argv); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr) + .contains("missing required flag '--known-at-micros'")); + assert!(!out.exists()); +} + +#[test] +fn curate_qm_bars_1m_binary_applies_date_effective_mapping_and_reports_dropped_unmapped() { + let tmp = TempDir::new("pit-mapping"); + // "REUSE" maps to listing 101 through 2024-06-10 and to listing 202 from 2024-06-11; + // "GHOST" has no mapping row and must be dropped (never assigned a listing). + let mapping = tmp.path().join("provider_mapping.tsv"); + fs::write( + &mapping, + "qm\tREUSE\t2024-06-01\t2024-06-10\t101\n\ + qm\tREUSE\t2024-06-11\t\t202\n", + ) + .expect("write provider_mapping.tsv"); + let intraday = tmp.path().join("qmIntraday.bson"); + let ts_old = et_ts_millis(2024, 6, 10, 10, 30); + let ts_new = et_ts_millis(2024, 6, 11, 10, 30); + fs::write( + &intraday, + concat_docs(&[ + make_qm_intraday_doc("REUSE", ts_old, 50.0, 51.0, 49.0, 50.5, 1_000.0), + make_qm_intraday_doc("REUSE", ts_new, 60.0, 61.0, 59.0, 60.5, 2_000.0), + make_qm_intraday_doc("GHOST", ts_new, 1.0, 1.0, 1.0, 1.0, 10.0), + ]), + ) + .expect("write qmIntraday.bson"); + let fx = Fixture { intraday, mapping }; + let out = tmp.path().join("out"); + + let output = run_bin(&bin_args(&fx, &out, "1718236800000000", &[])); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "stderr:\n{stderr}"); + assert!(stderr.is_empty(), "stderr:\n{stderr}"); + assert!( + stdout.contains("dropped_unmapped=1"), + "expected one unmapped row reported:\n{stdout}" + ); + assert!(stdout.contains("rows_written=2"), "stdout:\n{stdout}"); + + let mut rows: Vec = read_dir_files(&out) + .values() + .flat_map(|bytes| decode_rows(bytes)) + .collect(); + rows.sort_by_key(|r| r.ts); + assert_eq!(rows.len(), 2); + assert_eq!((rows[0].listing_id, rows[0].ts), (101, ts_old * 1_000)); + assert_eq!((rows[1].listing_id, rows[1].ts), (202, ts_new * 1_000)); + assert_eq!(rows[1].open.to_bits(), 60.0_f64.to_bits()); + assert!(rows.iter().all(|r| r.known_at == 1_718_236_800_000_000)); + + // Reported per-shard counts must sum to the rows actually written in the shard files. + let per_shard_line = stdout + .lines() + .find(|l| l.contains("per_shard_rows=")) + .expect("per_shard_rows in report"); + let per_shard_sum: usize = per_shard_line + .split("per_shard_rows=") + .nth(1) + .unwrap() + .trim() + .split(',') + .map(|kv| kv.split_once('=').unwrap().1.parse::().unwrap()) + .sum(); + assert_eq!(per_shard_sum, rows.len()); +} diff --git a/tsconfig.check.json b/tsconfig.check.json index d67c308a..74f157e6 100644 --- a/tsconfig.check.json +++ b/tsconfig.check.json @@ -32,7 +32,8 @@ "apps/stock/**/src/**/*.tsx", "tools/**/src/**/*.ts", "apps/stock/orchestrator/examples/canonical-regime-research.ts", - "libs/core/services/test/contracts.type-test.ts" + "libs/core/services/test/contracts.type-test.ts", + "libs/data/postgres/test/research-copilot-executor.type-test.ts" ], "exclude": ["node_modules", "**/dist/**", "**/*.test.ts", "**/*.spec.ts"] }