T-207: merge dev
This commit is contained in:
commit
9c5138a329
14 changed files with 2784 additions and 175 deletions
|
|
@ -14,6 +14,7 @@ Start here. Every document below has a single responsibility; historical sprint
|
|||
| **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)** | Canonical metric definitions, `trial_ledger` schema, effective-trials DSR ($\hat{N}$), CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, lifecycle gates, and Dual Live Drift + IB/TSX execution rules | Before touching `libs/calculations`, `libs/research`, validation workflows, or paper/live execution |
|
||||
| **[servers.md](servers.md)** | Host roles (`quant` `12900K` research/data server, `9900K` isolated IB live/paper host, `TrueNAS` cold storage, dev workstation) and port/storage layout | Infrastructure, deployment, and worker sizing |
|
||||
| **[data-pipeline/rust-migration-evaluation.md](data-pipeline/rust-migration-evaluation.md)** | Evidence-based evaluation of keeping `apps/stock/data-pipeline` in TypeScript vs. moving bulk MongoDB streaming or the full pipeline into Rust (`tools/curate-etl`) | Before `M2` adds PIT fundamentals, `ceoPosts`, or `bars_1m` QuestDB ingestion |
|
||||
| **[m2-completion-audit.md](m2-completion-audit.md)** | Read-only Milestone `M2` completion audit, gate results & pending host checks, candidate Auto Mode parking causes, director decisions, and `M3` readiness mapping (`T-204`) | Before closing `M2`, queuing remaining `M2` tasks, or starting `M3` |
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
122
design/m2-completion-audit.md
Normal file
122
design/m2-completion-audit.md
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
# Milestone M2 Completion Audit & M3 Readiness Report (T-204)
|
||||
|
||||
**Verdict:** **HOLD M3 — M2 is ~70% complete on the audited `feat/audit-m2-completion-status-m3` checkout (branched from `master`; exact `master` commit SHA pending host-side `git` verification), with 7 concrete wiring/contract gaps remaining before M2 closure.**
|
||||
|
||||
All sandbox-runnable TypeScript, ESLint, contract, and Rust native gates passed in the programmer's sandboxed run on the review checkout (`0` errors, `0` warnings), and Studio's unsandboxed review-branch runs (`#1597` build and `#1598` test suite) passed. Core M2 building blocks — `send-ilp` (`T-190`), the 6-tool MCP copilot server, file-mode PIT fundamentals/`ceoPosts`/`teData` curaters, QuestDB `10.2.0` schemas, and the TypeScript Feature Library — are landed and tested. However, desktop Claude Code cannot launch the MCP server end-to-end (`T-196` entrypoint is absent from the checkout), `ceoPosts` writes `"post"` instead of `"ceo_post"`, `MarketDataStore` rejects `crossSection`/`macroAsOf`/`fx('1m')`, `curate-qm-bars-1m` has no CLI subcommand, Python `stockbot` lacks `register_signal` and M2 store methods, and the live `quant` QuestDB `10.2.0` preflight, observed split-boundary check, and latency gates remain unverified.
|
||||
|
||||
> **Scope & Provenance Notes**
|
||||
> - **Audit-only:** Zero production code, build config, or CI changes (project CI is off).
|
||||
> - **Audited checkout & `master` relationship:** Audited in the task worktree on branch `feat/audit-m2-completion-status-m3` (branched from `master` for `T-204`). Because worktree `.git` metadata lives outside the agent sandbox, the exact `master` commit SHA and `studio/auto-*` branch history could not be read here and remain **PENDING** host-side verification. Every deliverable below was verified directly from source files, exports, CLI parsers, and test execution in this checkout.
|
||||
> - **Documentation path drift:** Milestone and contract docs moved from `docs/` to `design/`, while `AGENTS.md` (lines 43–48), `CLAUDE.md` (lines 3, 7–11), `README.md` (lines 7, 9, 11–13, 142, 264, 435), and `studio.config.json` still reference `docs/*.md`.
|
||||
> - **Prior M1 deferral:** Per settled director decision (`d52aa20`), M1 equity eligibility classification and cutoff-separated Parquet benchmarking stay deferred in the backlog and do not block M2.
|
||||
|
||||
---
|
||||
|
||||
## 1. Verification Gate Results & Pending Host Checks
|
||||
|
||||
### 1.1 Programmer Sandbox Runs (Review Worktree `feat/audit-m2-completion-status-m3`)
|
||||
|
||||
Executed inside the agent sandbox (network disabled; zero contact with QA MongoDB `27017/stock` or QA PostgreSQL `5432/trading_bot`; counts below are attributed to the programmer's sandbox execution without retained log files on disk):
|
||||
|
||||
| Gate / Suite | Command | Exit | Programmer-Observed Outcome & Counts |
|
||||
| --- | --- | :---: | --- |
|
||||
| Typecheck | `bun run typecheck` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.check.json --noEmit`) |
|
||||
| Contracts | `bun run test:contracts` | `0` | **PASS** — `0` errors (`tsc --project tsconfig.contracts.json --noEmit`) |
|
||||
| Lint | `bun run lint:check` | `0` | **PASS** — `0` errors, `0` warnings (`--max-warnings 0`) |
|
||||
| Utils | `bun run test:utils` | `0` | **PASS** — `32` pass, `0` fail (`59` expects, `3` files) |
|
||||
| Calculations | `bun run test:calculations` | `0` | **PASS** — `144` pass, `0` fail (`76,602` expects, `12` files) |
|
||||
| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PASS** — `1,548` passed, `0` failed, `4` ignored across `57` suites (`engine` + `curate-etl`, incl. `tcp_sends_separate_shards_and_half_closes`, `restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2`, and the synthetic `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` fixture) |
|
||||
| M2 Research, DuckDB, QuestDB & Scripts | `bun test libs/research/ libs/data/duckdb/ libs/data/questdb/ scripts/test/security.test.ts scripts/test/workspace.test.ts` | `0` | **PASS** — `1,032` pass, `0` fail (`80,869` expects, `63` files; includes real-DuckDB `fundamentalsAsOf` restatement fixture and MCP Vault-fence suite) |
|
||||
| Postgres Copilot Executor & Unit Suites | `bun test libs/data/postgres/test/research-copilot-executor.test.ts libs/data/postgres/test/research-copilot-executor-edge.test.ts test/unit/` | `0` | **PASS** — `640` pass, `0` fail (`734,988` expects, `44` files) |
|
||||
| Python SDK (`python/tests/`) | `python3 -m pytest` | N/A | **SKIPPED (env)** — `pytest` / `python/.venv` not installed in the sandbox |
|
||||
|
||||
### 1.2 Studio Unsandboxed Runs & Remaining Host Verification
|
||||
|
||||
| Verification | Scope / Command | Status | Notes |
|
||||
| --- | --- | :---: | --- |
|
||||
| **Studio Build `#1597`** | `bun run build` on review branch `feat/audit-m2-completion-status-m3` | **PASS** | Reported green by Studio on the review branch. |
|
||||
| **Studio Test Run `#1598`** | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` on review branch `feat/audit-m2-completion-status-m3` | **PASS** | Reported green by Studio on the review branch (covers Bun test suites including isolated `stock_bot_safety*` PostgreSQL tests, plus Rust workspace `--lib` tests). |
|
||||
| **Full Host Check & `master` Provenance** | Record `master` SHA, inspect `studio/auto-*` branches, and run `CARGO_BUILD_JOBS=2 bun run check` (incl. `audit:secrets`, `test:tooling`, `test:integration`, `lint:check`) + `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` with retained logs | **PENDING** | Not covered by Studio runs `#1597`/`#1598`; must be executed on the host against the confirmed `master` revision before M2 closure (see `design/m2-gap-audit.md:118-122`). |
|
||||
|
||||
**Research & Financial Invariants Verified Across Passing Suites**
|
||||
- **Economic ownership & durable inputs:** Quant data curation owns immutable Zstd Parquet partitions (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`, `macro`) and QuestDB ILP v2 shards; PostgreSQL owns append-only `trial_ledger`, `findings`, and `provider_caveats` (`database/postgres/init/37-research-findings.sql:81-99`).
|
||||
- **Holdout Vault fence:** `createQueryDataTool` (`libs/research/src/mcp/tools/query-data.ts`) and `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:40`) hardcode `vaultOperatorAuthorized: false`, reject `scope`/`vault_evaluation_only` keys, clamp bounds strictly below `vaultCutoffTs`, and drop post-cutoff rows (`libs/research/test/mcp-query-data.test.ts`).
|
||||
- **PIT & synthetic split conservation:** Both Rust (`tools/curate-etl/src/fundamentals_tests.rs:104`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251,601-626`) prove `known_at <= asOf` and Q1-after-Q2 restatement non-overwrite. **Synthetic** Rust fixtures (`tools/curate-etl/src/bars_1m_tests.rs:107,220` and `tools/curate-etl/src/run_curate_bars_1m_tests.rs:377-402`) prove `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split arithmetic and ex-date boundary handling within `0.5%`, while observed-data comparison against retained raw `bars_1d` closes remains open (`run_curate_bars_1m_tests.rs:396-400`).
|
||||
- **Database & execution safety:** Read-only MongoDB/Postgres adapters verified; zero paper/live execution write access in research/MCP surfaces.
|
||||
|
||||
---
|
||||
|
||||
## 2. M2 Deliverables & Exit Criteria Matrix
|
||||
|
||||
### 2.1 Deliverables (`design/MILESTONES.md` lines 87–98)
|
||||
|
||||
| Area | Status | Landed in Checkout (Exact Evidence) | Concrete Gaps Remaining |
|
||||
| --- | :---: | --- | --- |
|
||||
| **M2.1** Research Copilot MCP & Notebook Snapshots | **PARTIAL** | All 6 tools wired in `createResearchCopilotMcpServer` (`libs/research/src/mcp/copilot-server.ts:13-20,48`); stdio host (`libs/research/src/mcp/host/stdio-host.ts`); Postgres adapters (`libs/research/src/mcp/adapters/postgres-copilot.ts`, `postgres-trial-ref.ts`, `library-cards.ts`, `exchange-calendars.ts`, `bar-session-dates.ts`); `openResearchCopilotExecutor` (`libs/data/postgres/src/research-copilot-executor.ts`); `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:33`); SQL schema (`database/postgres/init/37-research-findings.sql`); `exportNotebookSnapshot` (`libs/research/src/notebook-snapshot.ts:594`, `notebook-snapshot-node.ts:67`). | **(1)** `T-196` desktop entrypoint `scripts/research-copilot-mcp.ts` and `"mcp:research-copilot"` in `package.json` are missing; `apps/stock/web-api/src/` has no optional SSE wrapper. **(2)** `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts:37`) opens daily DuckDB only instead of composing `createRoutedMarketDataStore` + `createQuestDbIntradayBarsReader` for `1m` queries. **(3)** `analyze_signal` (`libs/research/src/mcp/tools/analyze-signal.ts:121-123`) restricts `signal.source` to `'shorts' \| 'fundamentals'` (no `ceoPosts`, `macro`, or materialized `features`). **(4)** `exportNotebookSnapshot` has no CLI or MCP entrypoint and no end-to-end MCP study + `marimo check`-clean HTML + `file_finding` verification test. |
|
||||
| **M2.2** PIT Fundamentals, `ceoPosts` & Lagged `teData` | **PARTIAL** | File-mode CLIs `curate-fundamentals`, `curate-posts`, and `curate-macro` wired in `tools/curate-etl/src/cli.rs:99-101,1295,1573,1684` and `main.rs:228,238,250`; Rust Q1-after-Q2 restatement test (`tools/curate-etl/src/fundamentals_tests.rs:104`); real-DuckDB TS `fundamentalsAsOf` implementation & restatement test (`libs/research/src/market-data-store-duckdb.ts:2287`, `libs/data/duckdb/test/duckdb-market-data-store.test.ts:251`). | **(1)** `EVENT_KIND_POST = "post"` (`tools/curate-etl/src/parquet_posts.rs:22`) mismatches `'ceo_post'` required by `libs/research/src/market-data-store-duckdb.ts:108`, `libs/research/src/event-panel.ts:63`, and `python/stockbot/data.py:21`, and `run_curate_posts` fails closed (`EventsDatasetExists`, `tools/curate-etl/src/run_curate_posts.rs:133,389`) if `<out>/events` already exists from `curate-events`; both TS (`market-data-store-duckdb.ts:1448`) and Python (`python/stockbot/data.py:71`) only glob `events/year=*/part.parquet`. **(2)** `createDuckDbMarketDataStore().macroAsOf` (`libs/research/src/market-data-store-duckdb.ts:2294-2296`) throws `MarketDataStoreNotImplementedError`, blocking read-back of `macro/part.parquet` (note: per `design/DATA-CONTRACTS.md:26`, `teData` holds final-revised values only and must remain restricted to coarse lagged regime filters, not historical release signals without vintage data). **(3)** `SourceCollection` (`tools/curate-etl/src/mongo_stream.rs:53-62`) allowlists only the 8 M1 collections — no `--from-mongo` streaming for `qmFinancials`, `qmFinancials-old`, `ceoPosts`, or `teData`, and `curate-fundamentals` lacks `--qm-financials-old` merging. **(4)** Python `stockbot.data.MarketDataStore` (`python/stockbot/data.py`) lacks `fundamentals_as_of` and `macro_as_of`. |
|
||||
| **M2.3** QuestDB `10.2.0` Intraday & `send-ilp` (`T-190`) | **PARTIAL** | `T-190` `send-ilp` CLI landed (`tools/curate-etl/src/cli.rs:102,2290`, `main.rs:260`, `ilp_send.rs`, `ilp_send_tests.rs` loopback `TcpListener` tests); `curate-bars-1m` and `curate-fx-1m` CLIs wired (`cli.rs:97-98`, `main.rs:208,218`); `M2_INTRADAY_SCHEMAS` (`libs/data/questdb/src/schema.ts:13-63`) with `PARTITION BY MONTH`, `WAL`, `SYMBOL CAPACITY 65536 NOCACHE`, `DEDUP UPSERT KEYS`; `docker-compose.quant.yml:35-39,52-53` (`nofile: 1048576`, `QDB_RAM_USAGE_LIMIT_BYTES=21474836480`); synthetic `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split fixtures (`bars_1m_tests.rs:107,220`, `run_curate_bars_1m_tests.rs:377-402`). | **(1)** `run_curate_qm_bars_1m` (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`, `T-185`) is not wired into `cli.rs`/`main.rs` (no `curate-qm-bars-1m` subcommand). **(2)** `MarketDataStore.fx({ timeframe: '1m' })` throws `MarketDataStoreNotImplementedError` in TS (`libs/research/src/market-data-store-duckdb.ts:1529-1530`, delegated unchanged by `createRoutedMarketDataStore` at `libs/research/src/market-data-store-routed.ts:184-186`) and `NotImplementedError` in Python (`python/stockbot/data.py:259`). **(3)** No `--from-mongo` streaming for `eodIntraday1M` (`3.40B` docs) or `qmIntraday` (`173.3M` docs). **(4)** Live `quant` preflight (`vm.max_map_count >= 1048576`, effective container `nofile = 1048576`, WAL DDL), binary-double (`0x10`) TCP ILP v2 acceptance (`tools/curate-etl/src/ilp_send.rs:15-21`), observed `NEXM.V`/`NVDA.US` comparison against retained raw `bars_1d`, and pinned PGWire 1-year `1m` read benchmark (`< 250 ms` warm / `< 1 s` cold) are all unverified. |
|
||||
| **M2.4** Versioned Feature Library (`D04` / `D11`) | **PARTIAL** | TS `registerSignal`, `runFeatureBatch`, and Zstd Parquet writer landed (`libs/research/src/feature-library.ts`); built-in `RET_1D_V1` (`feature-library.ts:2166`). | **(1)** `createDuckDbMarketDataStore().crossSection` (`libs/research/src/market-data-store-duckdb.ts:2283-2285`) throws `MarketDataStoreNotImplementedError`, blocking read-back of materialized `features/<name>/v<version>/` Parquet. **(2)** `FEATURE_INPUT_DATASETS` (`libs/research/src/feature-library.ts:61-68`) omits `'macro'` (coarse regime filters only per `DATA-CONTRACTS.md:26`) and `'corporate_actions'`, and registers only `'RET_1D_V1'`. **(3)** Python `stockbot` (`python/stockbot/__init__.py`, `data.py`, `signals.py`) lacks `cross_section` and `register_signal` (`D04`/`D11`). |
|
||||
|
||||
### 2.2 Exit Criteria (`design/MILESTONES.md` lines 100–103)
|
||||
|
||||
| Exit Criterion | Status | Evidence & Remaining Blocker |
|
||||
| --- | :---: | --- |
|
||||
| **EC-1:** Desktop Claude Code via MCP runs a fundamental + alt-data signal study and event study end-to-end, exports a `marimo check`-clean static HTML snapshot, and files a finding. | **OPEN** | All 6 MCP tools and `exportNotebookSnapshot` exist as libraries, but `scripts/research-copilot-mcp.ts` / `"mcp:research-copilot"` (`T-196`) is missing, `ceoPosts` cannot be read via `event_study` (`"post"` vs `"ceo_post"`), and no end-to-end MCP → HTML snapshot → `file_finding` verification exists. |
|
||||
| **EC-2:** Restatement fixture test proves a restated Q1 (`known_at > Q2`) never overwrites Q2 in `fundamentalsAsOf`. | **SATISFIED (Offline Fixture)** | Proven in both Rust (`tools/curate-etl/src/fundamentals_tests.rs:104`) and real-DuckDB TypeScript (`libs/data/duckdb/test/duckdb-market-data-store.test.ts:251,601-626`), both passing in sandbox and Studio test run `#1598`. |
|
||||
| **EC-3:** Split-boundary test on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirms `bars_1m` session closes match raw `bars_1d` closes within `0.5%`, and 1y of `1m` bars loads in `< 250 ms` warm / `< 1 s` cold. | **OPEN (Synthetic Only)** | **Synthetic** Rust fixtures (`tools/curate-etl/src/bars_1m_tests.rs:107,220`, `run_curate_bars_1m_tests.rs:377-402`) pass for split arithmetic only and explicitly leave observed comparison against retained raw `bars_1d` open (`run_curate_bars_1m_tests.rs:396-400`). Still open on `quant`: (1) effective `vm.max_map_count >= 1048576` & container `nofile = 1048576` preflight before bulk load; (2) live QuestDB `10.2.0` binary-double (`0x10`) TCP ILP v2 acceptance; (3) observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` close check (`<= 0.5%`); and (4) pinned 1-year single-listing PGWire benchmark (`QuestDBClient.query` → `createQuestDbIntradayBarsReader`) recording listing ID, date range, cache conditions, and expected vs. actual row counts against `< 250 ms` warm / `< 1 s` cold. |
|
||||
|
||||
---
|
||||
|
||||
## 3. Candidate Causes: Why M2 Auto Mode May Have Parked 3 Consecutive Tasks
|
||||
|
||||
No parked task receipts or Auto Mode run logs are available inside the sandbox, so **none of the four items below can be attributed to a specific parked task yet**. Separating what is directly observed in the checkout from what remains inferred pending host history/log inspection:
|
||||
|
||||
1. **Missing `T-196` desktop MCP entrypoint *(observed in checkout; branch-reset cause inferred/unverified)*:** `scripts/research-copilot-mcp.ts` and `"mcp:research-copilot"` in `package.json` are absent from the checkout, whereas `T-190` (`send-ilp`) and `curate-macro` are present. Any Auto Mode task expecting a runnable desktop MCP entrypoint would hit an immediate blocker. Whether `T-196` was dropped during a `studio/auto-*` branch reset remains **unverified** until host-side branch history is inspected (`design/m2-gap-audit.md:119`).
|
||||
2. **`docs/*` → `design/*` path drift *(observed in checkout; park attribution unverified)*:** `AGENTS.md` (L43–48), `CLAUDE.md` (L3, L7–11), `README.md` (L7, L9, L11–13, L142, L264, L435), `studio.config.json`, and older task prompts still point to `docs/*.md`, which can cause agents to fail path checks against the renamed `design/` directory.
|
||||
3. **Sandbox boundary friction for `.git`, PostgreSQL, and `quant` *(observed environment constraint; park attribution unverified)*:** Running `bun run check`, `audit:secrets`, worktree-git tests (`scripts/test/`), `PIPELINE_TEST_DATABASE_URL` (`127.0.0.1:5432`) suites, or live `quant` QuestDB checks inside the agent sandbox fails by design; tasks without explicit host/sandbox separation can park on those expected errors.
|
||||
4. **Unqueued Option B `--from-mongo` extension for M2 collections *(observed in checkout; park attribution unverified)*:** The `2026-11-30` addendum in `design/data-pipeline/rust-migration-evaluation.md` (lines 253–294) locked Option B (`tools/curate-etl --from-mongo`) for M1 and scoped M2's 6 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`) to M2, but `SourceCollection` (`tools/curate-etl/src/mongo_stream.rs:53-62`) still allowlists only the 8 M1 collections.
|
||||
|
||||
---
|
||||
|
||||
## 4. Concrete Blockers Needing Director Decisions
|
||||
|
||||
1. **Option B `--from-mongo` for M2 collections vs. `.bson` staging:** Should we extend `tools/curate-etl` `SourceCollection` with `--from-mongo` streaming for the 6 M2 collections (`qmFinancials`, `qmFinancials-old`, `ceoPosts`, `teData`, `eodIntraday1M`, `qmIntraday`), or close M2 in file-mode `.bson` staging?
|
||||
- *Recommended:* Extend `--from-mongo` to the 6 M2 collections (reusing the M1 `ReadOnlyMongoClient` + `ChunkedMongoRawDocumentSource` pattern) so `3.40B` `eodIntraday1M` docs never require `~500–832 GiB` of intermediate `.bson` scratch files.
|
||||
2. **Canonical `ceoPosts` event `kind` & `<out>/events` co-publishing:** Should `tools/curate-etl/src/parquet_posts.rs` switch `EVENT_KIND_POST` from `"post"` to `"ceo_post"` and co-publish alongside `curate-events` under `<out>/events/year=YYYY/` (either by writing `part-posts.parquet` **and updating both readers** — `libs/research/src/market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` — from `events/year=*/part.parquet` to `events/year=*/*.parquet`, or by merging posts into yearly `part.parquet`), or keep posts in a separate curated root?
|
||||
- *Recommended:* Change `EVENT_KIND_POST` to `"ceo_post"`, write `events/year=YYYY/part-posts.parquet`, **and update both TS (`market-data-store-duckdb.ts:1448`) and Python (`python/stockbot/data.py:71`) readers to glob `events/year=*/*.parquet`** (verified by a combined read-back fixture with filings, earnings, and an edited CEO post in the same curated root) so `curate-events` and `curate-posts` remain independently re-runnable without hiding posts from either reader.
|
||||
3. **Live `quant` QuestDB `10.2.0` preflight, observed split check & latency gate for M2 closure:** Should M2 closure require an operator-run `quant` QuestDB `10.2.0` verification covering host/container limits (`vm.max_map_count`, `nofile`), binary-double (`0x10`) TCP ILP v2 acceptance, observed `NEXM.V` + `NVDA.US` `bars_1m` vs. retained raw `bars_1d` closes (`<= 0.5%`), and a pinned 1-year single-listing PGWire latency benchmark (`< 250 ms` warm / `< 1 s` cold), or accept synthetic-fixture closure and defer all live `quant` checks to an ops follow-up (matching the M1 `d52aa20` precedent)?
|
||||
- *Recommended:* Require a small-slice (`NEXM.V` + `NVDA.US`, 1 year) operator verification on `quant` covering all four checks above before closing M2, while deferring full `3.40B`-row backfill to an ops runbook.
|
||||
|
||||
---
|
||||
|
||||
## 5. M3 Readiness Mapping & Recommended Task Order
|
||||
|
||||
**Verdict: Do not start M3 yet.** M2 must close first, and M3's core engine, screener, and validation deliverables are unstarted on this checkout.
|
||||
|
||||
### 5.1 M3 Deliverables & Exit Criteria Readiness Map (`design/MILESTONES.md` lines 111–128)
|
||||
|
||||
| M3 Item | Status | Target Files & Current Checkout Evidence |
|
||||
| --- | :---: | --- |
|
||||
| **Tier 1 Columnar Screener** (`MILESTONES.md:112-113`) | **NOT STARTED** | Append-only `trial_ledger` SQL exists (`database/postgres/init/36-trial-ledger.sql`), and `libs/calculations/src/index.ts` exports `deflatedSharpeRatio`, `effectiveIndependentTrials`, `analyzeSignalPanel`, `eventStudy`, `evaluateRecencyGate`. No Polars/DuckDB portfolio sweep, $M_{T \times N}$ writer, or CSCV `PBO` ($S = 16$) yet. |
|
||||
| **Tier 2 Rust `financial/` Multi-Asset Upgrades** (`MILESTONES.md:114-119`) | **NOT STARTED** | `apps/stock/engine/Cargo.toml` has no `parquet`/`arrow-rs` crates yet; `apps/stock/orchestrator/src/backtest/{native-worker,candidate-sandbox}.ts` still use the single-series JSON/IPC path. Task 1 (retire `backtest_datasets` JSONB/IPC/N-API bar path), atomic timestamp-slice marks (`F06`), simultaneous `Target` sell-netting, feature side-channel, and `USD`/`CAD` Margin + corporate actions/delisting in `apps/stock/engine/src/financial/*` are all unstarted. |
|
||||
| **Validation Suite & Engine Consolidation** (`MILESTONES.md:120-123`) | **PARTIAL (SQL only)** | `vault_evaluations` table with `<= 10/year` cap & append-only triggers exists (`database/postgres/init/36-trial-ledger.sql:44-138`), and `apps/stock/analytics` / `SimulationExecution` are already absent from the repo. Purged Walk-Forward/CPCV, stability surface, ADV capacity, US/CA factor exposure, human Vault Holdout Gate workflow, and retirement of legacy `f64` `BacktestEngine` (`apps/stock/engine/src/backtest/engine.rs:17`, `apps/stock/engine/src/api/backtest.rs:13`) remain **NOT STARTED**. |
|
||||
| **M3 EC-1:** Rust unit + differential accounting fixtures (`MILESTONES.md:126`) | **OPEN** | Atomic hedged mark neutrality, 100%-invested `Sell A + Buy B` target rotation, split + dividend 8-decimal conservation, USD/CAD margin interest, TSX board-lot sizing, and `SIVB` delisting liquidation fixtures are not yet implemented. |
|
||||
| **M3 EC-2:** 20y US+CA daily backtest (`~5,000+` listings) in `< 30 s` on `quant` (`MILESTONES.md:127`) | **OPEN** | Blocked on Tier 2 Parquet/Arrow-rs path + multi-asset engine upgrades. |
|
||||
| **M3 EC-3:** Real M2 signal via `register_signal` end-to-end (`MILESTONES.md:128`) | **OPEN** | Blocked on M2 Python `register_signal` + `crossSection` read-back and M3 Tier 1/Tier 2/CPCV/Vault gate. |
|
||||
|
||||
### 5.2 Ordered Task List to Finish M2 (8 Tasks)
|
||||
|
||||
1. **Restore `T-196` desktop MCP entrypoint & wire routed intraday store:** Add `scripts/research-copilot-mcp.ts` + `"mcp:research-copilot"` in `package.json`, and update `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`) to compose `createRoutedMarketDataStore` + `createQuestDbIntradayBarsReader` when QuestDB config is present.
|
||||
2. **Fix `ceoPosts` `kind = 'ceo_post'`, `<out>/events` co-publishing & reader globs:** Change `EVENT_KIND_POST` in `tools/curate-etl/src/parquet_posts.rs` to `"ceo_post"`, co-publish `ceoPosts` under `<out>/events/year=YYYY/` (either writing `part-posts.parquet` and updating both `libs/research/src/market-data-store-duckdb.ts:1448` and `python/stockbot/data.py:71` to glob `events/year=*/*.parquet`, or merging into yearly `part.parquet`), and add a combined read-back fixture containing filings, earnings, and an edited CEO post in the same curated root.
|
||||
3. **Implement `MarketDataStore.macroAsOf`, `crossSection`, and `fx('1m')`:** Implement DuckDB read-back for `macro/part.parquet` (`macroAsOf`, enforcing/documenting the `design/DATA-CONTRACTS.md:26` coarse lagged regime-filter-only limit since `teData` lacks release vintages) and versioned `features/<name>/v<version>/` (`crossSection`) in `libs/research/src/market-data-store-duckdb.ts`, and route `fx({ timeframe: '1m' })` to QuestDB `fx_1m` in `libs/research/src/market-data-store-routed.ts`.
|
||||
4. **Wire `curate-qm-bars-1m` CLI & expand Feature Library inputs:** Expose `curate-qm-bars-1m` in `tools/curate-etl/src/{cli,main}.rs`, add `'macro'` (restricted to lagged regime filters per `DATA-CONTRACTS.md:26` until vintage data exists) and `'corporate_actions'` to `FEATURE_INPUT_DATASETS` in `libs/research/src/feature-library.ts`, and extend MCP `analyze_signal` to support materialized `features` (and `ceoPosts` / regime-only `macro` as needed).
|
||||
5. **Add Python `stockbot` M2 parity & `register_signal` (`D04`/`D11`):** Expose `fundamentals_as_of`, `macro_as_of` (regime-only), `cross_section`, `fx(..., timeframe='1m')`, and `register_signal(...)` in `python/stockbot/` with offline `pytest` coverage.
|
||||
6. **Extend `curate-etl --from-mongo` to the 6 M2 collections (subject to Director Decision 1):** Add `qmFinancials`, `qmFinancials-old` (with `--qm-financials-old` merge), `ceoPosts`, `teData`, `eodIntraday1M`, and `qmIntraday` to `SourceCollection` in `tools/curate-etl/src/mongo_stream.rs`.
|
||||
7. **Add M2 Exit Criterion 1 end-to-end verification & doc path cleanup:** Add a CLI/MCP wrapper + end-to-end test covering MCP study → `marimo check`-clean HTML snapshot (`exportNotebookSnapshot`) → `file_finding`, and update stale `docs/` links in `AGENTS.md`, `CLAUDE.md`, `README.md`, and `studio.config.json` to `design/`.
|
||||
8. **Operator `quant` QuestDB `10.2.0` preflight, observed split check & latency benchmark (Exit Criterion 3):** Before bulk load, verify on `quant` effective `vm.max_map_count >= 1048576`, container `ulimits.nofile = 1048576`, memory limits, and `getM2IntradayDDL()` WAL tables; run `send-ilp` on a small `NEXM.V` + `NVDA.US` 1-year slice to verify `0x10` binary-double acceptance and `wal_tables()` health via PGWire; compare observed `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) `bars_1m` session closes against retained raw `bars_1d` closes (`<= 0.5%`); and run a pinned 1-year single-listing `1m` benchmark through `QuestDBClient.query` → `createQuestDbIntradayBarsReader` (re-verifying via `createRoutedMarketDataStore` once wired) recording listing ID, date range, cache conditions, and expected vs. actual row counts against `< 250 ms` warm / `< 1 s` cold.
|
||||
|
||||
### 5.3 Initial M3 Prerequisite Sequence (Once M2 Closes)
|
||||
|
||||
1. **Retire JSON-over-Postgres/IPC/N-API bar path (M3 Task 1):** Add `parquet`/`arrow-rs` to `apps/stock/engine/Cargo.toml`, store `(hash, manifest, parquet_paths)` in `backtest_datasets`, and lift single-series TS gates in `native-worker.ts`.
|
||||
2. **Tier 1 Columnar Screener & CSCV PBO (`S = 16`):** Implement CSCV `PBO` and Purged Walk-Forward/CPCV in `libs/calculations`, plus vectorized Polars/DuckDB portfolio sweeps logging $M_{T \times N}$ matrices to `trial_ledger`.
|
||||
3. **Tier 2 Rust `financial/` multi-asset upgrades & legacy retirement:** Implement atomic timestamp-slice marks (`F06`), simultaneous `Target` sell-netting, feature side-channel, `USD`/`CAD` Margin + corporate-action/delisting accounting (with all 6 M3 EC-1 fixtures), human Vault Holdout Gate workflow, and retirement of legacy `f64` `BacktestEngine`.
|
||||
133
design/m2-gap-audit.md
Normal file
133
design/m2-gap-audit.md
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
# Milestone M2 Gap Audit Report (T-203)
|
||||
|
||||
**Verdict:** **OPEN — M2 is not ready for closure.** Core M2 libraries (`curate-macro`, `send-ilp`, MCP server/adapters with Vault-fenced `query_data`, `fundamentalsAsOf`, QuestDB `10.2.0` primitives, and TS Feature Library) are present in the checked-out worktree and are programmer-reported green in the provisioned sandbox, but six concrete code/wiring gaps remain (including the missing desktop MCP entry point, unwired equity `1m` QuestDB consumer routing, and a `ceo_post` vs `post` event-kind mismatch). Traceable gate verification (with confirmed checkout SHA and retained logs) and all host-only `master` / `quant` / desktop closure gates remain **PENDING**.
|
||||
|
||||
> **Scope & Provenance Notes:**
|
||||
> - Milestone and contract documents live under `design/` (`design/MILESTONES.md`, `design/DATA-CONTRACTS.md`, `design/PLATFORM-PLAN.md`), not `docs/`.
|
||||
> - **Revision status:** Worktree `.git` metadata lives outside the sandbox boundary, so the exact base `master` SHA and `studio/auto-*` branches could not be inspected inside the sandbox. All local checks below ran against the checked-out worktree on branch `feat/m2-gap-audit` (`/home/boki/.studio/worktrees/stock-bot/slot-1`); authoritative `master` verification remains **PENDING** until the host confirms the `master` SHA.
|
||||
> - Per settled director decision, **T-127** (M1 equity eligibility / Vault file isolation) stays deferred in the backlog and does not block M2.
|
||||
> - Project CI is off; no CI workflows were planned, added, or modified.
|
||||
|
||||
---
|
||||
|
||||
## 1. Verification History & Worktree Gate Results
|
||||
|
||||
### 1.1 Earlier Planning-Phase Setup Failures (Recorded in Approved Plan)
|
||||
|
||||
During the initial read-only planning pass (unprovisioned environment before worktree dependencies and writable Cargo target were available), all four requested local gates and supplemental tests failed during setup:
|
||||
|
||||
| Gate / Suite | Command | Exit Code | Planning-Phase Outcome |
|
||||
| --- | --- | --- | --- |
|
||||
| Typecheck | `bun run typecheck` | `2` | **FAIL** — `TS2688` missing `bun-types` |
|
||||
| Contracts | `bun run test:contracts` | `2` | **FAIL** — `TS2688` missing `bun-types` |
|
||||
| Lint | `bun run lint:check` | `127` | **FAIL** — `eslint: command not found` |
|
||||
| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `101` | **FAIL** — `Read-only file system (os error 30)` creating Cargo target path |
|
||||
| Supplemental M2 `bun test` | copilot server, stdio, snapshot exporter, DuckDB store, ILP writer | `1` | **FAIL** — missing `zod` and `@stock-bot/logger` during import setup |
|
||||
|
||||
### 1.2 Programmer-Reported Worktree Sandbox Runs (Verification Pending)
|
||||
|
||||
Executed interactively in the provisioned worktree `/home/boki/.studio/worktrees/stock-bot/slot-1` (branch `feat/m2-gap-audit`, Linux sandbox, network disabled).
|
||||
|
||||
- **Tested checkout revision:** **Unavailable in sandbox** (worktree `.git` metadata lives outside the sandbox boundary).
|
||||
- **Retained command log / run reference:** **None** (ephemeral sandbox terminal output only).
|
||||
- **Verification status:** **PENDING.** Because neither a confirmed checkout SHA nor retained command logs/run IDs are available for these four gates and supplemental suites, the rows below are **programmer-reported** only and do not constitute verified passes on `master` or the audited revision.
|
||||
|
||||
| Gate / Suite | Command | Exit Code | Status (Programmer-Reported) |
|
||||
| --- | --- | --- | --- |
|
||||
| Typecheck | `bun run typecheck` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors reported |
|
||||
| Contracts | `bun run test:contracts` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors reported |
|
||||
| Lint | `bun run lint:check` | `0` | **PROGRAMMER-REPORTED (pending)** — 0 errors, 0 warnings reported |
|
||||
| Native Rust | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PROGRAMMER-REPORTED (pending)** — `1,548` passed, `0` failed, `4` ignored across `57` suites |
|
||||
| MCP `query_data` Vault Fence | `bun test libs/research/test/mcp-query-data.test.ts` | `0` | **PROGRAMMER-REPORTED (pending)** — `13` pass, `0` fail |
|
||||
| Real-DuckDB M2 Fixtures | `bun test libs/data/duckdb/test/` | `0` | **PROGRAMMER-REPORTED (pending)** — `25` pass, `0` fail across `4` files; includes Exit 2 restatement fixture & `openResearchCopilotStore` |
|
||||
| Research + QuestDB + Copilot Executor | `bun test libs/research/test/ libs/data/questdb/test/ libs/data/postgres/test/research-copilot-executor.test.ts libs/data/postgres/test/research-copilot-executor-edge.test.ts` | `0` | **PROGRAMMER-REPORTED (pending)** — `999` pass, `0` fail across `59` files |
|
||||
| Exit 3 Split-Boundary Fixture | `CARGO_BUILD_JOBS=2 cargo test -p curate-etl --offline split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` | `0` | **PROGRAMMER-REPORTED (pending)** — `1` passed, `0` failed |
|
||||
| Utils | `bun run test:utils` | `0` | **PROGRAMMER-REPORTED (pending)** — `32` pass, `0` fail across `3` files |
|
||||
| Calculations | `bun run test:calculations` | `0` | **PROGRAMMER-REPORTED (pending)** — `144` pass, `0` fail across `12` files |
|
||||
|
||||
- **Prior Studio unsandboxed runs (review branch `feat/m2-gap-audit`):** Studio `build` (`#1589`, `#1591`) and `test` (`#1590`, `#1592`) passed on the review branch. These runs cover separate Studio `build` and `test` commands on the review branch—not the four individual requested gates (`typecheck`, `test:contracts`, `lint:check`, `test:native`)—and do not confirm the audited `master` revision.
|
||||
- **Verification status:** **PENDING** host confirmation of the exact `master` SHA, retained logs for `CARGO_BUILD_JOBS=2 bun run check`, and the separate `test/postgres/` run (see Section 4.1).
|
||||
|
||||
---
|
||||
|
||||
## 2. Verified on `master` *(Source Inspection; Traceable Runtime Verification & Host `master` SHA Pending)*
|
||||
|
||||
- **PRESENT · MCP Copilot Libraries, Vault-Fenced `query_data` & Snapshot Exporter.**
|
||||
- `libs/research/src/mcp/copilot-server.ts` exposes all six M2 tools (`search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`).
|
||||
- `createQueryDataTool` (`libs/research/src/mcp/tools/query-data.ts`) enforces strict Vault fencing: its Zod schema omits `scope` and `vault_evaluation_only` (`.strict()` rejects them with zero store calls), calls `fenceVaultQueryBounds` before any `store.universe` or `store.bars` call (clamping `to`/`asOf` strictly below `vaultCutoffTs` and rejecting ranges starting at/after `vaultCutoffTs` with `VaultHoldoutFenceError`), always passes `scope: 'vault_fenced'`, and applies defense-in-depth row filtering dropping any row where `row.ts >= vaultCutoffTs || row.knownAt >= vaultCutoffTs` (lines 203–210).
|
||||
- Boundary cases in `libs/research/test/mcp-query-data.test.ts` — rejecting `scope`/`vault_evaluation_only`/unknown keys (L303), rejecting ranges starting at/after `vaultCutoffTs` with `VaultHoldoutFenceError` (L342), clamping straddling `to`/`asOf` below cutoff (L359), dropping leaky post-cutoff `ts`/`knownAt` rows (L386), clamping universe date via `min(to, asOf)` (L508), and DuckDB microsecond-bound + `adj_factors` snapshot checks (L576) — are **programmer-reported passing** in the worktree (`13` pass, `0` fail; traceable verification & host `master` SHA pending).
|
||||
- `libs/research/src/mcp/adapters/postgres-copilot.ts` (`createPostgresResearchCopilotServer`) wires the read-only Studio library reader, PostgreSQL findings/caveats, trial lookup, and exchange calendars.
|
||||
- `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`, T-184) and `openResearchCopilotExecutor` (`libs/data/postgres/src/research-copilot-executor.ts`, T-189/T-200) are exported and programmer-reported passing in worktree unit tests (verification pending).
|
||||
- `exportNotebookSnapshot` (`libs/research/src/notebook-snapshot.ts`) and its Node/Bun adapters (`libs/research/src/notebook-snapshot-node.ts`) implement the `marimo check` → static HTML export sequence.
|
||||
- **PRESENT · `tools/curate-etl` CLI Subcommands.**
|
||||
- `tools/curate-etl/src/cli.rs` and `tools/curate-etl/src/main.rs` wire `curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, `curate-fx-1d`, `curate-shorts`, `curate-events`, `curate-bars-1m`, `curate-fx-1m`, `curate-posts`, `curate-fundamentals`, `curate-macro`, and `send-ilp`.
|
||||
- `curate-macro` (T-194/T-202) connects `run_curate_macro` to `curate_and_write_macro`; `send-ilp` (T-190) connects `run_send_ilp` to shard discovery and one TCP connection per shard. Both are programmer-reported passing in offline native tests in the worktree (verification pending).
|
||||
- **PRESENT · Exit 2 (PIT Restatement) & Exit 3 (Split-Boundary) Fixtures.**
|
||||
- `tools/curate-etl/src/fundamentals.rs` builds deduplicated 2D PIT snapshots and 4-quarter TTM with venue lag provenance.
|
||||
- `libs/data/duckdb/test/duckdb-market-data-store.test.ts` contains the real-DuckDB `fundamentalsAsOf` restatement fixture proving a restated Q1 (`known_at > Q2`) never overwrites Q2 (programmer-reported passing in worktree; verification pending).
|
||||
- `tools/curate-etl/src/run_curate_bars_1m_tests.rs` contains `split_boundary_nvda_and_nexm_match_raw_bars_1d_closes` with the `0.5%` threshold and negative controls (programmer-reported passing in worktree; verification pending).
|
||||
- **PRESENT · QuestDB `10.2.0` Primitives & TS Feature Library.**
|
||||
- `docker-compose.yml`, `docker-compose.dev.yml`, and `docker-compose.prod.yml` pin `questdb/questdb:10.2.0`.
|
||||
- `libs/data/questdb/src/{schema,client,query-builder,ilp-v2-writer}.ts` provide monthly WAL DDL (`M2_INTRADAY_SCHEMAS`, `getM2IntradayDDL`), parameterized PGWire (`QuestDBClient.query`), `LATEST ON`, and the ILP v2 binary batch writer.
|
||||
- `libs/research/src/feature-library.ts` implements `registerSignal`, `runFeatureBatch`, and Zstd Parquet writing for versioned DuckDB SQL features.
|
||||
|
||||
---
|
||||
|
||||
## 3. Remaining M2 Code Gaps
|
||||
|
||||
1. **FAIL · Desktop MCP Entry Point & Exit 1 Wiring**
|
||||
- T-196 target `scripts/research-copilot-mcp.ts` and root `package.json` script `mcp:research-copilot` are absent.
|
||||
- `runResearchCopilotStdioHost` (`libs/research/src/mcp/host/stdio-host.ts`) still requires caller-injected store/executor factories rather than a runnable default entrypoint.
|
||||
- `apps/stock/web-api/src/` has no MCP/SSE route.
|
||||
- Impact: Desktop Claude Code cannot yet launch the copilot end-to-end to satisfy M2 Exit Criterion 1.
|
||||
|
||||
2. **FAIL · `ceoPosts` Event-Kind & Output-Root Interoperability**
|
||||
- `tools/curate-etl/src/parquet_posts.rs` emits `EVENT_KIND_POST = "post"`, whereas `libs/research/src/market-data-store.ts` (`EventKind`), `libs/research/src/market-data-store-duckdb.ts` (`EVENT_KINDS`), `libs/research/src/mcp/tools/event-study.ts`, and `python/stockbot/data.py` (`EventKind`) all expect `"ceo_post"`.
|
||||
- `tools/curate-etl/src/run_curate_posts.rs` writes `<out_dir>/events/year=YYYY/part.parquet` and fails closed (`RunCuratePostsError::EventsDatasetExists`) if `<out_dir>/events` already has `year=*` partitions from `curate-events`, while the copilot store takes a single curated root.
|
||||
- Impact: Published `ceoPosts` cannot be queried alongside filings and earnings through the DuckDB store or MCP `event_study` as shipped.
|
||||
|
||||
3. **PARTIAL · Fundamentals & Macro Contract Gaps**
|
||||
- `build_fundamentals_rows` (`tools/curate-etl/src/fundamentals.rs`) links filings using listing/fiscal-class plus report-date or filing-window heuristics because sampled filings lack statement period, whereas `design/DATA-CONTRACTS.md` specifies a direct period-end join.
|
||||
- `run_curate_fundamentals` (`tools/curate-etl/src/run_curate_fundamentals.rs`) takes one caller-prepared financials BSON dump and requires `listing_venues.tsv`, which `exportCurateInputs` (`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts`) does not emit. No physical `fundamentals_bitemporal` writer or `eodFinancialsOLD` backfill path exists.
|
||||
- `createDuckDbMarketDataStore().macroAsOf` (`libs/research/src/market-data-store-duckdb.ts:2294`) still rejects with `MarketDataStoreNotImplementedError`, so curated `teData` Parquet (`macro/part.parquet`) has no DuckDB reader.
|
||||
|
||||
4. **PARTIAL · Intraday Operating Path**
|
||||
- `run_curate_qm_bars_1m` (`tools/curate-etl/src/run_curate_qm_bars_1m.rs`) is implemented as a library function but has no binary subcommand dispatch in `tools/curate-etl/src/{cli,main}.rs`.
|
||||
- `curate-bars-1m` and `curate-fx-1m` operate in file-mode BSON only (no `--from-mongo` streaming).
|
||||
- `tools/curate-etl/src/bars_1m.rs` applies fixed Eastern session tags (venue/date overrides exist in close validation, not curation), and loaders stamp caller-supplied `--known-at-micros` whose historical availability semantics must be defined before as-of studies.
|
||||
|
||||
5. **FAIL / PARTIAL · QuestDB Startup Wiring & Intraday Read Path (Equity `1m` + FX `1m`)**
|
||||
- **Unwired equity `1m` consumer path:** No application entry point constructs `createRoutedMarketDataStore` (`libs/research/src/market-data-store-routed.ts`) with `createQuestDbIntradayBarsReader` (`libs/research/src/market-data-store-questdb.ts`). The documented copilot factory `openResearchCopilotStore` (`libs/data/duckdb/src/research-copilot-store.ts`) opens DuckDB alone (`openDuckDbMarketDataStore`), which rejects `timeframe: '1m'` queries with `MarketDataStoreNotImplementedError` before reaching QuestDB.
|
||||
- **Unwired FX `1m` route:** Even when `createRoutedMarketDataStore` is constructed, `fx()` delegates to the daily store rather than QuestDB `fx_1m`.
|
||||
- **Startup DDL & legacy writer:** `getM2IntradayDDL` (`libs/data/questdb/src/schema.ts:139`) is opt-in with no checked-in startup caller applying it, and `QuestDBClient` (`libs/data/questdb/src/client.ts:232`) still instantiates legacy `QuestDBInfluxWriter` (`libs/data/questdb/src/influx-writer.ts`).
|
||||
- **Schema wording drift:** `M2_INTRADAY_SCHEMAS.fx_1m` matches `design/DATA-CONTRACTS.md` (`DEDUP UPSERT KEYS(ts, pair)`), while `design/MILESTONES.md:96` wording can be read as `(ts, listing_id)` for both `bars_1m` and `fx_1m`.
|
||||
|
||||
6. **PARTIAL · Feature Library & Documentation Drift**
|
||||
- `python/stockbot/__init__.py` and `python/stockbot/signals.py` do not expose `register_signal(...)` (only TS `libs/research/src/feature-library.ts` has `registerSignal`).
|
||||
- `createDuckDbMarketDataStore().crossSection` (`libs/research/src/market-data-store-duckdb.ts:2283`) still rejects with `MarketDataStoreNotImplementedError`.
|
||||
- `tools/curate-etl/README.md` still describes landed `curate-fundamentals` and `curate-macro` CLI wiring as deferred/follow-up in older stage sections (e.g., lines 1697, 1744, 1752, 1836, 1859).
|
||||
- `AGENTS.md` and `studio.config.json` still reference `docs/` paths instead of `design/`.
|
||||
- `design/MILESTONES.md:97` labels the Feature Library `D04` reopened, whereas `design/PLATFORM-PLAN.md` assigns the `register_signal` promotion bridge to `D11`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Manual Host-Only Closure Gates
|
||||
|
||||
These checks cannot run inside the sandbox and must be executed on the host / `quant` before closing M2:
|
||||
|
||||
1. **Host Git Revision, Unmerged Branches, Full Check Gate & PostgreSQL Safety Suite**
|
||||
- Record the exact audited `master` SHA and inspect `studio/auto-*` branches for any unmerged M2 commits (in particular T-196 desktop MCP wiring).
|
||||
- Run `CARGO_BUILD_JOBS=2 bun run check` outside the sandbox on the confirmed `master` revision (covers `audit:secrets`, `build`, `typecheck`, `test:contracts`, `test:tooling`, `test:utils`, `test:calculations`, `test:integration`, `test:native`, and `lint:check`) and retain the command output/log alongside the `master` SHA.
|
||||
- Because `scripts/check.ts` (`bun run check`) does **not** invoke `test:postgres` or discover `test/postgres/`, run the fixture-backed PostgreSQL safety suite separately using `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/` (against isolated `stock_bot_safety*`) and record its result and log alongside `bun run check`.
|
||||
- Never mutate QA MongoDB (`localhost:27017/stock`) or QA PostgreSQL (`localhost:5432/trading_bot`).
|
||||
|
||||
2. **Desktop Claude Code End-to-End Verification (Exit 1)**
|
||||
- After runnable MCP entry-point wiring lands, connect desktop Claude Code against the read-only Studio library (`~/repos/studio/catalog/quant/library/library.yml`) and isolated PostgreSQL.
|
||||
- Exercise all six MCP tools: run a PIT fundamentals + alt-data signal study and an event study, verify actual `marimo check`-clean static HTML export, and retrieve the filed finding with its trial and artifact references.
|
||||
|
||||
3. **Live `quant` QuestDB `10.2.0` Preflight, Load & Latency Verification (Exit 3)**
|
||||
- **Host & schema precheck:** Verify on `quant`: QuestDB `10.2.0` image, `vm.max_map_count >= 1048576`, container `ulimits.nofile = 1048576`, memory limits, and pre-created `PARTITION BY MONTH` WAL tables with documented dedup keys (`(ts, listing_id)` for `bars_1m`, `(ts, pair)` for `fx_1m`).
|
||||
- **Small live preflight per shard type (before bulk load):** Because `tools/curate-etl/src/cli.rs:175` documents that ILP v2 binary double encoding over TCP on QuestDB `10.2.0` is still unverified live, send one small sample shard for each shard type (`bars_1m`, `bars_1m_qm`, `fx_1m`) via `send-ilp` first. Confirm committed row counts, decoded OHLCV/FX numeric values and timestamps, and healthy WAL state (`wal_tables()`) through PGWire before starting the bulk load.
|
||||
- **Full bulk load & reconciliation:** Run `send-ilp` for `bars_1m`, `bars_1m_qm`, and `fx_1m`; reconcile source counts vs. QuestDB PGWire row counts and WAL state (TCP `send-ilp` success confirms socket delivery only, not committed rows), and verify overlapping EOD/QM bar dedup and repeat-load idempotency.
|
||||
- **Split-boundary verification:** Compare `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) split-boundary `bars_1m` session closes against independently sourced raw `bars_1d` closes (`<= 0.5%`).
|
||||
- **Read latency benchmark & explicit scope:** Benchmark a pinned 1-year single-listing `1m` read (`adjustment: 'raw'`) at **`< 250 ms` warm / `< 1 s` cold** using the real PGWire-backed reader path: `QuestDBClient.query(sql, params)` (`libs/data/questdb/src/client.ts`) injected as `QuestDbQueryExecutor` into `createQuestDbIntradayBarsReader` (`libs/research/src/market-data-store-questdb.ts`), optionally composed via `createRoutedMarketDataStore({ daily, intraday })`. Record listing ID, date range, row count, elapsed times, and cache conditions. **Scope note:** Until equity `1m` routing is wired into `openResearchCopilotStore` and the desktop MCP entrypoint (Section 3, item 5), this benchmark measures the **standalone PGWire-backed reader path**, not a running copilot application; re-verify through the running application once consumer wiring lands.
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
379
libs/data/postgres/src/research-copilot-executor.ts
Normal file
379
libs/data/postgres/src/research-copilot-executor.ts
Normal file
|
|
@ -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<Record<ResearchCopilotExecutorErrorCode, string>> = {
|
||||
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<string> = 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<void>;
|
||||
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<Row = Record<string, unknown>>(
|
||||
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<void>;
|
||||
}
|
||||
|
||||
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<void> {
|
||||
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<ManagedResearchCopilotExecutor> {
|
||||
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<void> | null = null;
|
||||
|
||||
const executor: ResearchCopilotExecutor = {
|
||||
async query<Row = Record<string, unknown>>(
|
||||
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<void> => {
|
||||
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 };
|
||||
}
|
||||
428
libs/data/postgres/test/research-copilot-executor-edge.test.ts
Normal file
428
libs/data/postgres/test/research-copilot-executor-edge.test.ts
Normal file
|
|
@ -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> | 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<void>(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<Socket>();
|
||||
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<void>((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<void>(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/);
|
||||
});
|
||||
});
|
||||
423
libs/data/postgres/test/research-copilot-executor.test.ts
Normal file
423
libs/data/postgres/test/research-copilot-executor.test.ts
Normal file
|
|
@ -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<void>;
|
||||
}): 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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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({});
|
||||
101
scripts/test/m2-gap-audit.test.ts
Normal file
101
scripts/test/m2-gap-audit.test.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
|
||||
// Guards the T-203 M2 gap audit (design/m2-gap-audit.md) against citation rot:
|
||||
// every repo path it cites must resolve, and every symbol it reports as
|
||||
// "present" must still live in the file it names. Gaps the audit reports as
|
||||
// missing are deliberately NOT asserted, so landing a fix never breaks this test.
|
||||
|
||||
const repoRoot = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const auditPath = join(repoRoot, 'design/m2-gap-audit.md');
|
||||
const audit = readFileSync(auditPath, 'utf8');
|
||||
|
||||
// Paths the audit cites as absent (the gap itself) or as the wrong location.
|
||||
const CITED_AS_ABSENT = new Set(['scripts/research-copilot-mcp.ts', 'docs/']);
|
||||
|
||||
function expandBraces(path: string): string[] {
|
||||
const match = /^(.*)\{([^}]+)\}(.*)$/.exec(path);
|
||||
if (!match) return [path];
|
||||
const [, prefix, options, suffix] = match;
|
||||
return options!.split(',').flatMap((option) => expandBraces(`${prefix}${option}${suffix}`));
|
||||
}
|
||||
|
||||
function citedRepoPaths(markdown: string): string[] {
|
||||
const spans = [...markdown.matchAll(/`([^`\s]+)`/g)].map((m) => m[1]!);
|
||||
const pathLike = spans.filter(
|
||||
(span) =>
|
||||
/^(apps|libs|tools|python|scripts|design|test|docs)\//.test(span) ||
|
||||
/^[A-Za-z0-9_.-]+\.(md|json|yml)$/.test(span)
|
||||
);
|
||||
return [...new Set(pathLike.map((span) => span.replace(/:\d+$/, '')).flatMap(expandBraces))].sort();
|
||||
}
|
||||
|
||||
describe('design/m2-gap-audit.md citations', () => {
|
||||
test('cites only repo paths that exist, except those it reports as absent', () => {
|
||||
const cited = citedRepoPaths(audit);
|
||||
expect(cited.length).toBeGreaterThan(30);
|
||||
|
||||
const missing = cited.filter((p) => !CITED_AS_ABSENT.has(p) && !existsSync(join(repoRoot, p)));
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
|
||||
test('every path listed as absent is actually absent in the audited checkout or is the docs/ relocation note', () => {
|
||||
// docs/ is cited because milestone docs moved to design/; it must stay absent for that note to hold.
|
||||
expect(existsSync(join(repoRoot, 'docs'))).toBe(false);
|
||||
expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true);
|
||||
});
|
||||
|
||||
// Symbols the audit reports as PRESENT, keyed by the file it attributes them to.
|
||||
const presentSymbols: Array<[file: string, symbol: string | RegExp]> = [
|
||||
['libs/research/src/mcp/tools/query-data.ts', 'createQueryDataTool'],
|
||||
['libs/research/src/mcp/tools/query-data.ts', 'fenceVaultQueryBounds'],
|
||||
['libs/research/src/mcp/tools/query-data.ts', "'vault_fenced'"],
|
||||
['libs/research/src/mcp/adapters/postgres-copilot.ts', 'createPostgresResearchCopilotServer'],
|
||||
['libs/data/duckdb/src/research-copilot-store.ts', 'openResearchCopilotStore'],
|
||||
['libs/data/postgres/src/research-copilot-executor.ts', 'openResearchCopilotExecutor'],
|
||||
['libs/research/src/notebook-snapshot.ts', 'exportNotebookSnapshot'],
|
||||
['libs/research/src/mcp/host/stdio-host.ts', 'runResearchCopilotStdioHost'],
|
||||
['libs/research/src/feature-library.ts', 'registerSignal'],
|
||||
['libs/research/src/feature-library.ts', 'runFeatureBatch'],
|
||||
['libs/data/questdb/src/schema.ts', 'M2_INTRADAY_SCHEMAS'],
|
||||
['libs/data/questdb/src/schema.ts', 'getM2IntradayDDL'],
|
||||
['libs/research/src/market-data-store-routed.ts', 'createRoutedMarketDataStore'],
|
||||
['libs/research/src/market-data-store-questdb.ts', 'createQuestDbIntradayBarsReader'],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateMacro('],
|
||||
['tools/curate-etl/src/cli.rs', 'SendIlp('],
|
||||
['tools/curate-etl/src/cli.rs', 'CuratePosts('],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateFundamentals('],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateBars1m('],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateFx1m('],
|
||||
['tools/curate-etl/src/run_curate_bars_1m_tests.rs', 'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes'],
|
||||
['tools/curate-etl/src/run_curate_posts.rs', 'EventsDatasetExists'],
|
||||
['tools/curate-etl/src/run_curate_qm_bars_1m.rs', /pub fn run_curate_qm_bars_1m\b/],
|
||||
['tools/curate-etl/src/fundamentals.rs', 'build_fundamentals_rows'],
|
||||
];
|
||||
|
||||
test.each(presentSymbols)('%s defines %p as the audit reports', (file, symbol) => {
|
||||
const source = readFileSync(join(repoRoot, file), 'utf8');
|
||||
if (typeof symbol === 'string') expect(source).toContain(symbol);
|
||||
else expect(source).toMatch(symbol);
|
||||
});
|
||||
|
||||
test('pins QuestDB 10.2.0 in every compose file the audit cites', () => {
|
||||
for (const file of ['docker-compose.yml', 'docker-compose.dev.yml', 'docker-compose.prod.yml']) {
|
||||
expect(readFileSync(join(repoRoot, file), 'utf8')).toContain('questdb/questdb:10.2.0');
|
||||
}
|
||||
});
|
||||
|
||||
test('lists the three closure-checklist sections the task requires', () => {
|
||||
expect(audit).toMatch(/^## 2\. Verified on `master`/m);
|
||||
expect(audit).toMatch(/^## 3\. Remaining M2 Code Gaps/m);
|
||||
expect(audit).toMatch(/^## 4\. Manual Host-Only Closure Gates/m);
|
||||
});
|
||||
|
||||
test('keeps master verification pending rather than claiming unverified passes', () => {
|
||||
expect(audit).toContain('**OPEN');
|
||||
expect(audit).toMatch(/PENDING/);
|
||||
expect(audit).not.toMatch(/\|\s*\*\*PASS\*\*\s*\|/);
|
||||
});
|
||||
});
|
||||
404
test/postgres/mcp-copilot-executor.test.ts
Normal file
404
test/postgres/mcp-copilot-executor.test.ts
Normal file
|
|
@ -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> | 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<Record<string, string>>
|
||||
): 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<number> {
|
||||
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');
|
||||
});
|
||||
});
|
||||
175
test/unit/m2-completion-audit-doc.test.ts
Normal file
175
test/unit/m2-completion-audit-doc.test.ts
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
|
||||
// Guards the T-204 M2 completion audit (design/m2-completion-audit.md) against
|
||||
// citation rot: every repo path it cites must resolve, every symbol it reports as
|
||||
// landed must still live in the file it names, and the report must keep host-only
|
||||
// verification marked pending. Gaps the audit reports as missing are deliberately
|
||||
// NOT asserted, so landing an M2 fix never breaks this test.
|
||||
|
||||
const repoRoot = fileURLToPath(new URL('../../', import.meta.url));
|
||||
const audit = readFileSync(join(repoRoot, 'design/m2-completion-audit.md'), 'utf8');
|
||||
const designIndex = readFileSync(join(repoRoot, 'design/README.md'), 'utf8');
|
||||
|
||||
// Cited as the gap itself (absent today), as already-retired code, as a sandbox env
|
||||
// note, or as the stale pre-rename docs/ location.
|
||||
const CITED_AS_ABSENT = new Set([
|
||||
'scripts/research-copilot-mcp.ts',
|
||||
'apps/stock/analytics',
|
||||
'python/.venv',
|
||||
'docs',
|
||||
'docs/',
|
||||
'docs/*.md',
|
||||
]);
|
||||
|
||||
function expandBraces(path: string): string[] {
|
||||
const match = /^(.*)\{([^}]+)\}(.*)$/.exec(path);
|
||||
if (!match) {return [path];}
|
||||
const [, prefix, options, suffix] = match;
|
||||
return options!.split(',').flatMap((option) => expandBraces(`${prefix}${option}${suffix}`));
|
||||
}
|
||||
|
||||
function citedRepoPaths(markdown: string): string[] {
|
||||
const spans = [...markdown.matchAll(/`([^`\s]+)`/g)].map((m) => m[1]!);
|
||||
const pathLike = spans.filter(
|
||||
(span) =>
|
||||
/^(apps|libs|tools|python|scripts|design|test|database|docs)\//.test(span) ||
|
||||
/^[A-Za-z0-9_.-]+\.(md|json|yml)$/.test(span)
|
||||
);
|
||||
return [
|
||||
...new Set(
|
||||
pathLike
|
||||
// Strip `:line`, `:a-b`, and `:a-b,c` suffixes and trailing globs.
|
||||
.map((span) => span.replace(/:[\d,-]+$/, '').replace(/\/\*$/, ''))
|
||||
.flatMap(expandBraces)
|
||||
),
|
||||
].sort();
|
||||
}
|
||||
|
||||
describe('design/m2-completion-audit.md citations', () => {
|
||||
test('cites only repo paths that exist, except those it reports as absent', () => {
|
||||
const cited = citedRepoPaths(audit);
|
||||
expect(cited.length).toBeGreaterThan(40);
|
||||
|
||||
const missing = cited.filter((p) => !CITED_AS_ABSENT.has(p) && !existsSync(join(repoRoot, p)));
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
|
||||
test('docs/ stays absent so the documentation path-drift note holds', () => {
|
||||
expect(existsSync(join(repoRoot, 'docs'))).toBe(false);
|
||||
expect(existsSync(join(repoRoot, 'design/MILESTONES.md'))).toBe(true);
|
||||
});
|
||||
|
||||
// Symbols the audit reports as LANDED, keyed by the file it attributes them to.
|
||||
const landedSymbols: Array<[file: string, symbol: string | RegExp]> = [
|
||||
['libs/research/src/mcp/copilot-server.ts', 'createResearchCopilotMcpServer'],
|
||||
['libs/research/src/mcp/host/stdio-host.ts', 'runResearchCopilotStdioHost'],
|
||||
['libs/data/postgres/src/research-copilot-executor.ts', 'openResearchCopilotExecutor'],
|
||||
['libs/data/duckdb/src/research-copilot-store.ts', 'openResearchCopilotStore'],
|
||||
['libs/data/duckdb/src/research-copilot-store.ts', 'vaultOperatorAuthorized: false'],
|
||||
['libs/research/src/mcp/tools/query-data.ts', 'createQueryDataTool'],
|
||||
['libs/research/src/notebook-snapshot.ts', 'exportNotebookSnapshot'],
|
||||
['libs/research/src/notebook-snapshot-node.ts', 'exportNotebookSnapshot'],
|
||||
['libs/research/src/market-data-store-duckdb.ts', 'fundamentalsAsOf'],
|
||||
['libs/research/src/market-data-store-routed.ts', 'createRoutedMarketDataStore'],
|
||||
['libs/research/src/market-data-store-questdb.ts', 'createQuestDbIntradayBarsReader'],
|
||||
['libs/research/src/feature-library.ts', 'registerSignal'],
|
||||
['libs/research/src/feature-library.ts', 'runFeatureBatch'],
|
||||
['libs/research/src/feature-library.ts', 'export const RET_1D_V1'],
|
||||
['libs/research/src/feature-library.ts', 'export const FEATURE_INPUT_DATASETS'],
|
||||
['libs/data/questdb/src/schema.ts', 'M2_INTRADAY_SCHEMAS'],
|
||||
['libs/data/questdb/src/schema.ts', 'getM2IntradayDDL'],
|
||||
// The schema is declarative; DDL keywords are rendered from these fields.
|
||||
['libs/data/questdb/src/schema.ts', "capacity: 65536, cache: false"],
|
||||
['libs/data/questdb/src/schema.ts', "partitionBy: 'MONTH'"],
|
||||
['libs/data/questdb/src/schema.ts', 'dedupUpsertKeys'],
|
||||
['tools/curate-etl/src/cli.rs', 'SendIlp('],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateFundamentals('],
|
||||
['tools/curate-etl/src/cli.rs', 'CuratePosts('],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateMacro('],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateBars1m('],
|
||||
['tools/curate-etl/src/cli.rs', 'CurateFx1m('],
|
||||
['tools/curate-etl/src/main.rs', 'run_send_ilp('],
|
||||
['tools/curate-etl/src/mongo_stream.rs', 'pub enum SourceCollection'],
|
||||
['tools/curate-etl/src/run_curate_posts.rs', 'EventsDatasetExists'],
|
||||
['tools/curate-etl/src/run_curate_qm_bars_1m.rs', /pub fn run_curate_qm_bars_1m\b/],
|
||||
['tools/curate-etl/src/ilp_send_tests.rs', 'fn tcp_sends_separate_shards_and_half_closes'],
|
||||
[
|
||||
'tools/curate-etl/src/fundamentals_tests.rs',
|
||||
'fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2',
|
||||
],
|
||||
[
|
||||
'tools/curate-etl/src/run_curate_bars_1m_tests.rs',
|
||||
'fn split_boundary_nvda_and_nexm_match_raw_bars_1d_closes',
|
||||
],
|
||||
['libs/data/duckdb/test/duckdb-market-data-store.test.ts', 'restatement non-overwrite'],
|
||||
['docker-compose.quant.yml', 'hard: 1048576'],
|
||||
['docker-compose.quant.yml', 'QDB_RAM_USAGE_LIMIT_BYTES=21474836480'],
|
||||
['database/postgres/init/37-research-findings.sql', 'provider_caveats'],
|
||||
['database/postgres/init/36-trial-ledger.sql', 'vault_evaluations'],
|
||||
];
|
||||
|
||||
test.each(landedSymbols)('%s contains %p as the audit reports', (file, symbol) => {
|
||||
const source = readFileSync(join(repoRoot, file), 'utf8');
|
||||
if (typeof symbol === 'string') {expect(source).toContain(symbol);}
|
||||
else {expect(source).toMatch(symbol);}
|
||||
});
|
||||
|
||||
test('every MCP tool the audit counts is registered in the copilot server', () => {
|
||||
const server = readFileSync(join(repoRoot, 'libs/research/src/mcp/copilot-server.ts'), 'utf8');
|
||||
const tools = ['search_symbols', 'query_data', 'analyze_signal', 'event_study', 'file_finding', 'read_knowledge'];
|
||||
for (const tool of tools) {expect(server).toContain(`'${tool}'`);}
|
||||
expect(audit).toContain('6 MCP tools');
|
||||
});
|
||||
|
||||
test('the synthetic split fixture still documents the observed-data comparison as open', () => {
|
||||
// The audit's EC-3 "synthetic only" status rests on this scope note.
|
||||
const fixture = readFileSync(join(repoRoot, 'tools/curate-etl/src/run_curate_bars_1m_tests.rs'), 'utf8');
|
||||
expect(fixture).toMatch(/Does NOT prove .* against retained `bars_1d` data/);
|
||||
expect(audit).toMatch(/OPEN \(Synthetic Only\)/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('design/m2-completion-audit.md structure and honesty', () => {
|
||||
test('holds M3 and covers every section the task requires', () => {
|
||||
expect(audit).toMatch(/HOLD M3/);
|
||||
expect(audit).toMatch(/^## 1\. Verification Gate Results/m);
|
||||
expect(audit).toMatch(/^## 2\. M2 Deliverables & Exit Criteria Matrix/m);
|
||||
expect(audit).toMatch(/^## 3\. Candidate Causes/m);
|
||||
expect(audit).toMatch(/^## 4\. Concrete Blockers Needing Director Decisions/m);
|
||||
expect(audit).toMatch(/^## 5\. M3 Readiness Mapping/m);
|
||||
});
|
||||
|
||||
test('covers all four M2 deliverables and all three M2 exit criteria', () => {
|
||||
for (const area of ['M2.1', 'M2.2', 'M2.3', 'M2.4']) {expect(audit).toContain(`**${area}**`);}
|
||||
for (const ec of ['EC-1', 'EC-2', 'EC-3']) {expect(audit).toContain(`**${ec}:**`);}
|
||||
for (const ec of ['M3 EC-1', 'M3 EC-2', 'M3 EC-3']) {expect(audit).toContain(`**${ec}:**`);}
|
||||
});
|
||||
|
||||
test('keeps host-only verification pending and parking causes unattributed', () => {
|
||||
expect(audit).toMatch(/\|\s*\*\*PENDING\*\*\s*\|/);
|
||||
expect(audit).toContain('none of the four items below can be attributed to a specific parked task');
|
||||
expect(audit).not.toMatch(/EC-3[^|]*\|\s*\*\*SATISFIED/);
|
||||
});
|
||||
|
||||
test('asks the director three decisions, each with a recommendation', () => {
|
||||
const decisions = audit.split(/^## 4\./m)[1]!.split(/^## 5\./m)[0]!;
|
||||
expect(decisions.match(/^\d\. \*\*/gm)?.length).toBe(3);
|
||||
expect(decisions.match(/\*Recommended:\*/g)?.length).toBe(3);
|
||||
});
|
||||
|
||||
test('carries the teData regime-filter-only limit into macro follow-ups', () => {
|
||||
expect(audit).toContain('design/DATA-CONTRACTS.md:26');
|
||||
expect(readFileSync(join(repoRoot, 'design/DATA-CONTRACTS.md'), 'utf8').split('\n')[25]).toContain(
|
||||
'final-revised values only'
|
||||
);
|
||||
});
|
||||
|
||||
test('is indexed exactly once in design/README.md', () => {
|
||||
const rows = designIndex.split('\n').filter((line) => line.includes('(m2-completion-audit.md)'));
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatch(/^\| \*\*\[m2-completion-audit\.md\]\(m2-completion-audit\.md\)\*\* \|.*\|.*\|$/);
|
||||
});
|
||||
});
|
||||
|
|
@ -169,8 +169,8 @@ pub fn format_usage(name: &str, version: &str) -> String {
|
|||
Curate ceoPosts from BSON + provider_mapping TSV into <out>/events/year=YYYY/part.parquet using a dedicated --out directory (--timestamp-unit has no default; defaults: --key-field {DEFAULT_POSTS_KEY_FIELD}, --spiel-id-field {DEFAULT_POSTS_SPIEL_ID_FIELD}, --timestamp-field {DEFAULT_POSTS_TIMESTAMP_FIELD}, --edited-field {DEFAULT_POSTS_EDITED_FIELD}, --bot-field {DEFAULT_POSTS_BOT_FIELD}, --user-id-field {DEFAULT_POSTS_USER_ID_FIELD}, --text-field {DEFAULT_POSTS_TEXT_FIELD}, --mapping-source {DEFAULT_POSTS_MAPPING_SOURCE})\n\
|
||||
{name} curate-fundamentals --qm-financials <path> --qm-filings <path> --provider-mapping <path> --listing-venues <path> --out <dir> --currency-field <name> --filings-form-type-field <name> --k <N> (--fiscal-period <quarterly|annual> | [--quarterly-tokens <a,b,..>] [--annual-tokens <a,b,..>]) [--financials-key-field <name>] [--period-end-field <name>] [--report-date-field <name>] [--report-period-field <name>] [--revenue-field <path>] [--net-income-field <path>] [--operating-cash-flow-field <path>] [--total-assets-field <path>] [--total-equity-field <path>] [--shares-outstanding-field <path>] [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--mapping-source <name>]\n\
|
||||
Curate point-in-time fundamentals from qmFinancials + qmFilings BSON + provider_mapping/listing_venues TSVs into fundamentals_pit/year=YYYY/part.parquet (file mode only; 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 <teData.bson> --series-map <series-map.tsv> --out <dir>\n\
|
||||
Curate lagged macro regime series from teData BSON + caller-supplied 6-column series-map TSV into macro/part.parquet (file mode only; no default mappings or lag classes)\n\
|
||||
{name} curate-macro --te-data <path> --series-map <path> --out <dir>\n\
|
||||
Curate macro regime series from a teData BSON dump + series-map TSV into <out>/macro/part.parquet (file mode only)\n\
|
||||
{name} send-ilp --dir <dir> --prefix <bars_1m|bars_1m_qm|fx_1m> --addr <host:port>\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\
|
||||
|
|
@ -225,7 +225,7 @@ pub fn format_usage_stderr(name: &str) -> String {
|
|||
{name} curate-fx-1m --eod-intraday <path> --out <dir> --shards <N>\n\
|
||||
{name} curate-posts --ceo-posts <path> --provider-mapping <path> --out <dir> --timestamp-unit <seconds|millis> [--key-field <name>] [--spiel-id-field <name>] [--timestamp-field <name>] [--edited-field <name>] [--bot-field <name>] [--user-id-field <name>] [--text-field <name>] [--mapping-source <name>]\n\
|
||||
{name} curate-fundamentals --qm-financials <path> --qm-filings <path> --provider-mapping <path> --listing-venues <path> --out <dir> --currency-field <name> --filings-form-type-field <name> --k <N> (--fiscal-period <quarterly|annual> | [--quarterly-tokens <a,b,..>] [--annual-tokens <a,b,..>]) [--financials-key-field <name>] [--period-end-field <name>] [--report-date-field <name>] [--report-period-field <name>] [--revenue-field <path>] [--net-income-field <path>] [--operating-cash-flow-field <path>] [--total-assets-field <path>] [--total-equity-field <path>] [--shares-outstanding-field <path>] [--filings-key-field <name>] [--filings-timefiled-field <name>] [--filings-filing-id-field <name>] [--filings-url-field <name>] [--mapping-source <name>]\n\
|
||||
{name} curate-macro --te-data <teData.bson> --series-map <series-map.tsv> --out <dir>\n\
|
||||
{name} curate-macro --te-data <path> --series-map <path> --out <dir>\n\
|
||||
{name} send-ilp --dir <dir> --prefix <bars_1m|bars_1m_qm|fx_1m> --addr <host:port>\n\
|
||||
{name} bench-split [rows]\n\
|
||||
{name} bench-adj [events]\n\
|
||||
|
|
@ -5750,6 +5750,224 @@ 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 <path> --series-map <path> --out <dir>"),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
assert!(usage.contains("<out>/macro/part.parquet"), "{usage}");
|
||||
assert!(usage.contains("file mode only"), "{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 including --mongo-uri and --from-mongo (rejected before consuming a value)
|
||||
for (args, expected_flag) in [
|
||||
(&["curate-macro", "--bogus", "1"][..], "--bogus"),
|
||||
(&["curate-macro", "--from-mongo"][..], "--from-mongo"),
|
||||
(
|
||||
&["curate-macro", "--from-mongo", "--out", "o"][..],
|
||||
"--from-mongo",
|
||||
),
|
||||
(&["curate-macro", "--from-mongo=true"][..], "--from-mongo"),
|
||||
(
|
||||
&["curate-macro", "--mongo-uri", "mongodb://host"][..],
|
||||
"--mongo-uri",
|
||||
),
|
||||
(
|
||||
&["curate-macro", "--mongo-uri-env=MONGODB_READ_URI"][..],
|
||||
"--mongo-uri-env",
|
||||
),
|
||||
] {
|
||||
let err = parse_args(&to_args(args)).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
format!("unknown flag '{expected_flag}' for curate-macro")
|
||||
);
|
||||
}
|
||||
|
||||
// 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"] {
|
||||
|
|
@ -6035,172 +6253,4 @@ mod tests {
|
|||
.expect("space dir with equals and IPv6 equals addr");
|
||||
assert_eq!(parsed_space, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curate_macro_parsing_validation_and_usage() {
|
||||
let usage_sig = "curate-macro --te-data <teData.bson> --series-map <series-map.tsv> --out <dir>";
|
||||
let usage = format_usage("curate-etl", "0.1.0");
|
||||
assert!(usage.contains(usage_sig), "{usage}");
|
||||
let usage_stderr = format_usage_stderr("curate-etl");
|
||||
assert!(usage_stderr.contains(usage_sig), "{usage_stderr}");
|
||||
|
||||
// Happy path: separated form
|
||||
let parsed = parse_args(&to_args(&[
|
||||
"curate-macro",
|
||||
"--te-data",
|
||||
"/tmp/teData.bson",
|
||||
"--series-map",
|
||||
"/tmp/series-map.tsv",
|
||||
"--out",
|
||||
"/tmp/curated",
|
||||
]))
|
||||
.expect("separated curate-macro args");
|
||||
assert_eq!(
|
||||
parsed,
|
||||
CliAction::CurateMacro(CurateMacroArgs {
|
||||
te_data: PathBuf::from("/tmp/teData.bson"),
|
||||
series_map: PathBuf::from("/tmp/series-map.tsv"),
|
||||
out_dir: PathBuf::from("/tmp/curated"),
|
||||
})
|
||||
);
|
||||
|
||||
// Happy path: `--flag=value` (including `=` inside path and `--`-prefixed literal dir)
|
||||
let parsed_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",
|
||||
]))
|
||||
.expect("equals curate-macro args");
|
||||
assert_eq!(
|
||||
parsed_eq,
|
||||
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"),
|
||||
})
|
||||
);
|
||||
|
||||
// Happy path: reordered mixed flags
|
||||
let parsed_reordered = parse_args(&to_args(&[
|
||||
"curate-macro",
|
||||
"--out",
|
||||
"out_dir",
|
||||
"--series-map=map.tsv",
|
||||
"--te-data",
|
||||
"te.bson",
|
||||
]))
|
||||
.expect("reordered curate-macro args");
|
||||
assert_eq!(
|
||||
parsed_reordered,
|
||||
CliAction::CurateMacro(CurateMacroArgs {
|
||||
te_data: PathBuf::from("te.bson"),
|
||||
series_map: PathBuf::from("map.tsv"),
|
||||
out_dir: PathBuf::from("out_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'");
|
||||
|
||||
// Omitting each required flag
|
||||
let required: [(&str, &str); 3] = [
|
||||
("--te-data", "teData.bson"),
|
||||
("--series-map", "series-map.tsv"),
|
||||
("--out", "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();
|
||||
assert_eq!(err, format!("missing required flag '{}'", required[omit].0));
|
||||
}
|
||||
|
||||
// Duplicate flags
|
||||
let base = [
|
||||
"curate-macro",
|
||||
"--te-data",
|
||||
"teData.bson",
|
||||
"--series-map",
|
||||
"series-map.tsv",
|
||||
"--out",
|
||||
"out",
|
||||
];
|
||||
for (flag, extra) in [
|
||||
("--te-data", "--te-data=other.bson"),
|
||||
("--series-map", "--series-map=other.tsv"),
|
||||
("--out", "--out=other_out"),
|
||||
] {
|
||||
let mut argv = base.to_vec();
|
||||
argv.push(extra);
|
||||
let err = parse_args(&to_args(&argv)).unwrap_err();
|
||||
assert_eq!(err, format!("duplicate flag '{flag}'"));
|
||||
}
|
||||
|
||||
// Empty values in both `--flag ""` and `--flag=` forms
|
||||
for flag in ["--te-data", "--series-map", "--out"] {
|
||||
let err_space = parse_args(&to_args(&["curate-macro", flag, ""])).unwrap_err();
|
||||
assert_eq!(err_space, format!("empty value for flag '{flag}'"));
|
||||
|
||||
let eq_token = format!("{flag}=");
|
||||
let err_eq = parse_args(&to_args(&["curate-macro", &eq_token])).unwrap_err();
|
||||
assert_eq!(err_eq, format!("empty value for flag '{flag}'"));
|
||||
}
|
||||
|
||||
// Missing values at EOF and before another `--flag`
|
||||
for flag in ["--te-data", "--series-map", "--out"] {
|
||||
let err_eof = parse_args(&to_args(&["curate-macro", flag])).unwrap_err();
|
||||
assert_eq!(err_eof, format!("missing value for flag '{flag}'"));
|
||||
}
|
||||
let err_before_flag = parse_args(&to_args(&[
|
||||
"curate-macro",
|
||||
"--te-data",
|
||||
"--out",
|
||||
"out",
|
||||
]))
|
||||
.unwrap_err();
|
||||
assert_eq!(err_before_flag, "missing value for flag '--te-data'");
|
||||
|
||||
// Unknown flags including --from-mongo and --mongo-uri* (checked before consuming value)
|
||||
for (argv, expected_flag) in [
|
||||
(&["curate-macro", "--bogus", "1"][..], "--bogus"),
|
||||
(&["curate-macro", "--from-mongo"][..], "--from-mongo"),
|
||||
(&["curate-macro", "--from-mongo=true"][..], "--from-mongo"),
|
||||
(
|
||||
&["curate-macro", "--from-mongo", "--out", "o"][..],
|
||||
"--from-mongo",
|
||||
),
|
||||
(
|
||||
&["curate-macro", "--mongo-uri", "mongodb://host"][..],
|
||||
"--mongo-uri",
|
||||
),
|
||||
(
|
||||
&["curate-macro", "--mongo-uri-env=MONGODB_READ_URI"][..],
|
||||
"--mongo-uri-env",
|
||||
),
|
||||
] {
|
||||
let err = parse_args(&to_args(argv)).unwrap_err();
|
||||
assert_eq!(err, format!("unknown flag '{expected_flag}' for curate-macro"));
|
||||
}
|
||||
|
||||
// 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")
|
||||
);
|
||||
}
|
||||
|
||||
// Multiline tokens are sanitized 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!(err.contains("bad\\nline\\rarg"), "{err:?}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -146,6 +146,27 @@ fn write_macro_fixture(dir: &Path) -> (PathBuf, PathBuf) {
|
|||
(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)
|
||||
|
|
@ -435,9 +456,7 @@ fn cli_invalid_flags_print_error_and_usage_without_touching_out() {
|
|||
assert_eq!(lines.next(), Some(*expected_error), "{stderr}");
|
||||
assert_eq!(lines.next(), Some("Usage:"), "{stderr}");
|
||||
assert!(
|
||||
stderr.contains(
|
||||
"curate-macro --te-data <teData.bson> --series-map <series-map.tsv> --out <dir>"
|
||||
),
|
||||
stderr.contains("curate-macro --te-data <path> --series-map <path> --out <dir>"),
|
||||
"{stderr}"
|
||||
);
|
||||
}
|
||||
|
|
@ -447,3 +466,311 @@ fn cli_invalid_flags_print_error_and_usage_without_touching_out() {
|
|||
"out_from_mongo must not be created"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_publishes_runner_equivalent_macro_parquet_and_excludes_forecast_sentinel() {
|
||||
let dir = TempDir::new("e2e-policy-rate");
|
||||
let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0);
|
||||
|
||||
let baseline_out = dir.0.join("baseline_out");
|
||||
let baseline_report = run_curate_macro(&CurateMacroArgs {
|
||||
te_data: te_data_path.clone(),
|
||||
series_map: series_map_path.clone(),
|
||||
out_dir: baseline_out.clone(),
|
||||
})
|
||||
.expect("run library baseline");
|
||||
let expected_stdout = format!("{}\n", format_curate_macro_report(&baseline_report));
|
||||
|
||||
let cli_out = dir.0.join("cli_out");
|
||||
let result = cli()
|
||||
.current_dir(&dir.0)
|
||||
.args([
|
||||
"--te-data",
|
||||
"teData.bson",
|
||||
"--series-map=macro_series_map.tsv",
|
||||
"--out",
|
||||
"cli_out",
|
||||
])
|
||||
.output()
|
||||
.expect("run curate-macro");
|
||||
|
||||
assert!(result.status.success(), "{result:?}");
|
||||
assert!(
|
||||
result.stderr.is_empty(),
|
||||
"unexpected stderr: {}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
let stdout = String::from_utf8(result.stdout).expect("utf-8 stdout");
|
||||
assert_eq!(stdout, expected_stdout);
|
||||
|
||||
let cli_parquet = cli_out.join("macro/part.parquet");
|
||||
let baseline_parquet = baseline_out.join("macro/part.parquet");
|
||||
assert!(cli_parquet.is_file(), "expected {}", cli_parquet.display());
|
||||
assert_eq!(
|
||||
fs::read(&cli_parquet).expect("read cli parquet"),
|
||||
fs::read(&baseline_parquet).expect("read baseline parquet"),
|
||||
"CLI Parquet output must match library runner bytes"
|
||||
);
|
||||
|
||||
let reader = SerializedFileReader::new(File::open(&cli_parquet).expect("open parquet"))
|
||||
.expect("open parquet reader");
|
||||
let rows: Vec<Row> = reader
|
||||
.get_row_iter(None)
|
||||
.expect("row iter")
|
||||
.map(|row| row.expect("decode row"))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
rows.len(),
|
||||
1,
|
||||
"expected exactly one mapped policy-rate row and no forecast sentinel row"
|
||||
);
|
||||
|
||||
let expected_period_date = ymd_to_epoch_days(2024, 3, 20).expect("valid date");
|
||||
let expected_known_at = i64::from(expected_period_date + POLICY_RATE_LAG_DAYS) * MICROS_PER_DAY;
|
||||
assert_eq!(POLICY_RATE_LAG_DAYS, 1);
|
||||
|
||||
let row = &rows[0];
|
||||
assert_eq!(col(row, "country_iso"), &Field::Str("US".to_string()));
|
||||
assert_eq!(
|
||||
col(row, "indicator"),
|
||||
&Field::Str("fed_funds_rate".to_string())
|
||||
);
|
||||
assert_eq!(col(row, "period_date"), &Field::Date(expected_period_date));
|
||||
assert_eq!(
|
||||
col(row, "known_at"),
|
||||
&Field::TimestampMicros(expected_known_at)
|
||||
);
|
||||
assert_eq!(
|
||||
col(row, "known_at_source"),
|
||||
&Field::Str("publication_lag_estimate".to_string())
|
||||
);
|
||||
assert_eq!(col(row, "value"), &Field::Double(5.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_missing_te_data_exits_nonzero_with_single_line_escaped_error_and_no_parquet() {
|
||||
let dir = TempDir::new("missing-te-data");
|
||||
let (_, series_map_path) = write_policy_rate_fixture(&dir.0);
|
||||
|
||||
let missing_path = dir.0.join("missing\nte_data\r.bson");
|
||||
let cli_out = dir.0.join("cli_out");
|
||||
|
||||
let result = cli()
|
||||
.arg("--te-data")
|
||||
.arg(&missing_path)
|
||||
.arg("--series-map")
|
||||
.arg(&series_map_path)
|
||||
.arg("--out")
|
||||
.arg(&cli_out)
|
||||
.output()
|
||||
.expect("run curate-macro");
|
||||
|
||||
assert_eq!(result.status.code(), Some(1), "{result:?}");
|
||||
assert!(
|
||||
result.stdout.is_empty(),
|
||||
"unexpected stdout: {}",
|
||||
String::from_utf8_lossy(&result.stdout)
|
||||
);
|
||||
|
||||
let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr");
|
||||
assert_eq!(
|
||||
stderr.lines().count(),
|
||||
1,
|
||||
"expected 1 stderr line: {stderr:?}"
|
||||
);
|
||||
assert!(!stderr.contains('\r'), "stderr must escape CR: {stderr:?}");
|
||||
assert!(stderr.starts_with("error: "), "{stderr:?}");
|
||||
assert!(stderr.contains("te-data"), "{stderr:?}");
|
||||
assert!(
|
||||
stderr.contains("missing\\nte_data\\r.bson"),
|
||||
"expected escaped path in stderr: {stderr:?}"
|
||||
);
|
||||
assert!(!stderr.contains("Usage:"), "{stderr:?}");
|
||||
assert!(
|
||||
!cli_out.join("macro/part.parquet").exists(),
|
||||
"macro/part.parquet must not be written on failure"
|
||||
);
|
||||
assert!(!cli_out.exists(), "out dir must not be created on failure");
|
||||
}
|
||||
|
||||
// ---- QA edge cases (T-202) ----
|
||||
|
||||
fn run_cli_paths(te_data: &Path, series_map: &Path, out: &Path) -> std::process::Output {
|
||||
cli()
|
||||
.arg("--te-data")
|
||||
.arg(te_data)
|
||||
.arg("--series-map")
|
||||
.arg(series_map)
|
||||
.arg("--out")
|
||||
.arg(out)
|
||||
.output()
|
||||
.expect("run curate-macro")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_help_lists_curate_macro_and_parse_errors_print_usage_without_writing() {
|
||||
let help = Command::new(env!("CARGO_BIN_EXE_curate-etl"))
|
||||
.arg("--help")
|
||||
.output()
|
||||
.expect("run --help");
|
||||
assert!(help.status.success(), "{help:?}");
|
||||
let help_text = String::from_utf8(help.stdout).expect("utf-8 help");
|
||||
assert!(
|
||||
help_text.contains("curate-macro --te-data <path> --series-map <path> --out <dir>"),
|
||||
"{help_text}"
|
||||
);
|
||||
|
||||
let dir = TempDir::new("parse-error");
|
||||
let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0);
|
||||
let cli_out = dir.0.join("cli_out");
|
||||
|
||||
// `--mongo-uri` is not a file-mode flag; it must be rejected before any run.
|
||||
let result = cli()
|
||||
.arg("--te-data")
|
||||
.arg(&te_data_path)
|
||||
.arg("--series-map")
|
||||
.arg(&series_map_path)
|
||||
.arg("--out")
|
||||
.arg(&cli_out)
|
||||
.args(["--mongo-uri", "mongodb://user:secret@host:27017/stock"])
|
||||
.output()
|
||||
.expect("run curate-macro");
|
||||
|
||||
assert_eq!(result.status.code(), Some(1), "{result:?}");
|
||||
assert!(result.stdout.is_empty(), "{result:?}");
|
||||
let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr");
|
||||
assert!(
|
||||
stderr.starts_with("error: unknown flag '--mongo-uri' for curate-macro\n"),
|
||||
"{stderr:?}"
|
||||
);
|
||||
assert!(stderr.contains("Usage:"), "{stderr:?}");
|
||||
assert!(
|
||||
!stderr.contains("secret"),
|
||||
"rejected flag value must not be echoed: {stderr:?}"
|
||||
);
|
||||
assert!(
|
||||
!cli_out.exists(),
|
||||
"out dir must not be created on parse error"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_runtime_failures_keep_existing_parquet_byte_identical() {
|
||||
let dir = TempDir::new("preserve");
|
||||
let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0);
|
||||
let out = dir.0.join("out");
|
||||
|
||||
let first = run_cli_paths(&te_data_path, &series_map_path, &out);
|
||||
assert!(first.status.success(), "{first:?}");
|
||||
let parquet = out.join("macro/part.parquet");
|
||||
let original = fs::read(&parquet).expect("read published parquet");
|
||||
|
||||
let bad_header = dir.0.join("bad_header.tsv");
|
||||
fs::write(&bad_header, "not\ta\theader\n").expect("write bad tsv");
|
||||
let corrupt_bson = dir.0.join("corrupt.bson");
|
||||
// Declares a 64-byte document but provides only 8 bytes.
|
||||
fs::write(&corrupt_bson, [64u8, 0, 0, 0, 1, 2, 3, 4]).expect("write corrupt bson");
|
||||
let missing_map = dir.0.join("missing_map.tsv");
|
||||
|
||||
for (label, te, map, role) in [
|
||||
("bad series-map header", &te_data_path, &bad_header, None),
|
||||
(
|
||||
"truncated teData",
|
||||
&corrupt_bson,
|
||||
&series_map_path,
|
||||
Some("te-data"),
|
||||
),
|
||||
(
|
||||
"missing series-map",
|
||||
&te_data_path,
|
||||
&missing_map,
|
||||
Some("series-map"),
|
||||
),
|
||||
] {
|
||||
let result = run_cli_paths(te, map, &out);
|
||||
assert_eq!(result.status.code(), Some(1), "{label}: {result:?}");
|
||||
assert!(result.stdout.is_empty(), "{label}: {result:?}");
|
||||
let stderr = String::from_utf8(result.stderr).expect("utf-8 stderr");
|
||||
assert_eq!(stderr.lines().count(), 1, "{label}: {stderr:?}");
|
||||
assert!(stderr.starts_with("error: "), "{label}: {stderr:?}");
|
||||
assert!(!stderr.contains("Usage:"), "{label}: {stderr:?}");
|
||||
if let Some(role) = role {
|
||||
assert!(stderr.contains(role), "{label}: {stderr:?}");
|
||||
}
|
||||
assert_eq!(
|
||||
fs::read(&parquet).expect("re-read parquet"),
|
||||
original,
|
||||
"{label}: failed run must not touch the published parquet"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_rerun_on_same_inputs_is_byte_deterministic() {
|
||||
let dir = TempDir::new("rerun");
|
||||
let (te_data_path, series_map_path) = write_policy_rate_fixture(&dir.0);
|
||||
let out_a = dir.0.join("out_a");
|
||||
let out_b = dir.0.join("out_b");
|
||||
|
||||
let a = run_cli_paths(&te_data_path, &series_map_path, &out_a);
|
||||
let b = run_cli_paths(&te_data_path, &series_map_path, &out_b);
|
||||
assert!(a.status.success() && b.status.success(), "{a:?} {b:?}");
|
||||
assert_eq!(a.stdout, b.stdout);
|
||||
assert_eq!(
|
||||
fs::read(out_a.join("macro/part.parquet")).expect("read a"),
|
||||
fs::read(out_b.join("macro/part.parquet")).expect("read b")
|
||||
);
|
||||
|
||||
// Republishing into the same directory replaces the file with identical bytes.
|
||||
let again = run_cli_paths(&te_data_path, &series_map_path, &out_a);
|
||||
assert!(again.status.success(), "{again:?}");
|
||||
assert_eq!(
|
||||
fs::read(out_a.join("macro/part.parquet")).expect("read a again"),
|
||||
fs::read(out_b.join("macro/part.parquet")).expect("read b")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cli_unmapped_only_input_succeeds_and_matches_runner_report() {
|
||||
let dir = TempDir::new("unmapped");
|
||||
let te_data_path = dir.0.join("teData.bson");
|
||||
let series_map_path = dir.0.join("macro_series_map.tsv");
|
||||
let doc = make_te_data_doc(
|
||||
"UNMAPPED",
|
||||
"Atlantis",
|
||||
"Interest Rate",
|
||||
&[("2024-03-20", 1.25)],
|
||||
&[],
|
||||
);
|
||||
fs::write(&te_data_path, doc.as_bytes()).expect("write teData");
|
||||
fs::write(
|
||||
&series_map_path,
|
||||
format!(
|
||||
"{MACRO_SERIES_MAP_HEADER}\nFDTR\tUnited States\tInterest Rate\tUS\tfed_funds_rate\tpolicy_rate\n"
|
||||
),
|
||||
)
|
||||
.expect("write tsv");
|
||||
|
||||
let baseline_out = dir.0.join("baseline_out");
|
||||
let baseline = run_curate_macro(&CurateMacroArgs {
|
||||
te_data: te_data_path.clone(),
|
||||
series_map: series_map_path.clone(),
|
||||
out_dir: baseline_out.clone(),
|
||||
})
|
||||
.expect("library run");
|
||||
assert_eq!(baseline.curate_stats.rows_out, 0);
|
||||
|
||||
let cli_out = dir.0.join("cli_out");
|
||||
let result = run_cli_paths(&te_data_path, &series_map_path, &cli_out);
|
||||
assert!(result.status.success(), "{result:?}");
|
||||
assert!(result.stderr.is_empty(), "{result:?}");
|
||||
assert_eq!(
|
||||
String::from_utf8(result.stdout).expect("utf-8 stdout"),
|
||||
format!("{}\n", format_curate_macro_report(&baseline))
|
||||
);
|
||||
assert_eq!(
|
||||
cli_out.join("macro/part.parquet").exists(),
|
||||
baseline_out.join("macro/part.parquet").exists(),
|
||||
"CLI and runner must agree on zero-row publication"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"]
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue