# Architectural & Quantitative Review of `docs/PLATFORM-PLAN.md` **Reviewed against:** `stock-bot` working tree at `HEAD = c353ddbe` (+ uncommitted env-safety/compose WIP), QA MongoDB `stock` (read-only via `MONGODB_READ_URI` as `studio_stock_bot_read@stock`), deployed QuestDB `10.2.0`, `docs/data-pipeline/phase1-investigation.md`, October backlog ADRs (`ADR-001`–`ADR-008`), and current QuestDB / IBKR API / marimo documentation. **Date:** 2026-11-26 > **Verification tags used throughout this review** > - **`[Verified: repo]`** — confirmed directly in source, SQL migrations, tests, or committed benchmark measurements (`file:line` cited). > - **`[Verified: QA Mongo / PG]`** — confirmed via read-only queries against the 31 collections in `stock` (`studio_stock_bot_read`) and `trading_bot` PostgreSQL. > - **`[Verified: external]`** — confirmed against deployed QuestDB `10.2.0` (`SELECT version(), build`), current QuestDB 9.x/10.x docs, IBKR TWS/Web API docs, and marimo 2025/2026 docs. > - **`[Assumed]`** — explicitly stated engineering or market assumption not directly observable in the repo or ingested snapshot. --- ## 1. Executive Summary ### Is the plan sound? **Directionally yes; mechanically no — several load-bearing assumptions in Sections 5, 6, 7, 9, and 13 fail against the actual raw data in QA MongoDB and the existing code.** Your core strategic instincts are right: **signal-first before strategy-first**, **permanent `listing_id` keys**, **mandatory multiple-testing adjustment via a trial ledger**, **desktop MCP copilot first (D2)**, and **keeping the deterministic fixed-decimal Rust financial kernel (`apps/stock/engine/src/financial/*`) as the sole accounting authority**. The October backlog left you with an unusually strong foundation for invariant enforcement (write-once PostgreSQL triggers, 8-decimal `BigRational`-backed postings, and a real seccomp/cgroup Docker + Rust PID1 sandbox). However, the plan was written against an *idealized* mental model of what the vendors delivered and how QuestDB, the NAPI engine boundary, and the holdout gates behave. In reality: - Your primary fundamentals (`qmFinancials`, `eodFinancialsOLD`, `eodFundamentalsOLD`) and macro (`teData`) collections **lack point-in-time filing/release dates and restatement/vintage history**; `eodIntraday1M` (`3.40B` bars) is **already split-adjusted** while `eodPrices` has **raw OHLC + split-adjusted volume**; and `eodSymbolChange` contains **only 230 US rows from 2024–2025**. - Section 6's `ISIN + MIC` blocking fails on **>80–90% of `ibSymbols`** because IB tags NYSE, Nasdaq, and TSX stocks with secondary execution/ATS venues (`AEQLIT`, `ARCAEDGE`, `BEX`, `IEX`, `OTCLNKECN`) rather than primary listing MICs. - Today's "sealed" holdout is **readable in plaintext JSON by any `sb-research.*` agent token**, the Rust/TS pull loop runs at **~5,400 bars/s** (making universe-scale callbacks unviable without a feature side-channel and atomic rebalancing fixes), and a solo-developer Phase A→C waterfall delays your first honest signal test by months. ### The three things most likely to sink it 1. **Silent phantom alpha from vendor data illusions (Sections 5, 6, 7).** Treating `eodFinancialsOLD.filingDate` as real (`99.26%` equal `reportDate`), `teData` as release-dated (`0%` release dates, 100% final-revised values), `eodIntraday1M` as raw (it is retroactively split-adjusted, so applying `adj_factors` double-adjusts every split), `eodPrices.volume` as raw (it is split-adjusted, inflating historical dollar-volume capacity by $10\times\text{–}56\times$), and exchange-delisted bars (`SIVB.US` ending at `$106.04`) as terminal without OTC-pink continuation (`SIVBQ.US` → `$0.006`) or bankruptcy delisting returns will systematically manufacture fake 3.0+ Sharpe backtests that agents will aggressively mine. 2. **Unplugged trial-ledger bypasses and adaptive holdout burn (Sections 1, 9, 11, 12).** Today `sb-research.*` tokens are explicitly allowed to export full holdout OHLCV JSON (`research-agents.service.ts:51`), agent budgets enforce concurrent (`maxActiveTrials`) rather than cumulative lifetime limits, and giving Claude Code / marimo raw table access (`stockbot.data.bars()` or raw SQL) lets an agent evaluate 5,000 signals in Polars memory and log `N = 1` on the winner. Worse, letting unattended campaigns (§15) touch the holdout and feed pass/fail into the Knowledge Base / Studio `evolve` loop adaptively overfits the holdout within weeks. 3. **Solo-developer infrastructure sprawl before testing one real signal (Sections 5, 9, 14, 16).** Building a full 6-pass security master + review UI, curating 10 datasets into QuestDB, writing a dual-backend QuestDB↔Parquet parity harness, building 4 playground pillars, and extending the single-asset Rust engine into a multi-currency long/short portfolio engine *serially* before testing a single cross-sectional hypothesis is ~9–12 months of plumbing. --- ### Verdicts on Decisions Log (D1–D9) Per ground rules, D1–D8 are treated as settled unless concrete evidence proves a failure mode: | # | Decision | Verdict | Concrete Evidence & Required Adjustment | | --- | --- | --- | --- | | **D1** | QuestDB for all curated data + parity harness | **Challenge partially** | Keep **QuestDB `10.2.0`** for intraday (`bars_1m`/`5m`/`1h`) where `SAMPLE BY` and WAL streaming excel, **but put daily bars, corporate actions, PIT fundamentals/events/shorts/macro, and features directly in Parquet + DuckDB from Day 1, and drop the parity harness.** QuestDB `ASOF JOIN` breaks on long-format EAV `fundamentals` and regresses fiscal periods on restatements/10-K comparative backfills; `DEDUP UPSERT KEYS` destroys `known_at` history or breaks `LATEST ON`; and `libs/data/questdb` is currently broken/disabled (`data-pipeline/src/index.ts:66`). *(See Finding F3.)* | | **D2** | Desktop copilot first via MCP | **Settled (with boundary fix)** | Keep D2, **but** distinguish interactive desktop Claude Code (which has host shell/DB access in `studio.config.json:5,9`) from autonomous campaign agents (which must run in network-isolated containers with MCP-only access), and air-gap the final Vault Holdout from both. *(See Finding F4.)* | | **D3–D8** | US+CA priority, incremental UI, Step 1 merge first, IB live end-state, full strategy & lab scope | **Settled** | Sound; sequenced into vertical slices in Section 4 so D7/D8 do not block early research. | | **D9** | **marimo** for Python labs inside the app | **Confirm (with 4 rules)** | Confirm marimo over Jupyter (`[Verified: external]`). Pure `.py` git diffs, deterministic DAG execution, `marimo check --format=json` static validation for LLM edits, `marimo edit --mcp`, and zero-RAM `marimo export html` snapshots fit agentic quant research far better than `.ipynb`. Enforce: **(1)** separate origin (never same-origin `allow-same-origin` with `web-app`'s `SameSite=Strict` session cookie), **(2)** static HTML snapshots by default in the Agent Lab Feed (`--session-ttl 300` for on-demand `marimo run`), **(3)** marimo's `CLAUDE.md` rules + `marimo check` pre-hook to prevent `MB002` variable-redefinition errors and `_underscore` cell-local scoping so intermediates don't pin GBs of RAM, and **(4)** `register_signal` materializes batch feature columns rather than translating Python into TS. *(See Findings F5 & F11.)* | --- ## 2. Findings Ranked by Impact --- ### F1 [CRITICAL — PIT & Data Integrity] — Raw Fundamentals, Macro, Earnings, Filings, and Shorts Cannot Support the Plan's `known_at` Claims as Written - **What the plan says (§5 lines 248–251, §7 lines 364–371):** - Fundamentals (`qmFinancials`, `eodFinancialsOLD`, `eodFundamentalsOLD`): *"Point-in-time by filing date (`known_at`), not period end; restatements as new versions."* - Macro (`teData`): *"release date as `known_at`."* - Filings (`qmFilings`): *"insider transactions extracted where present."* - Earnings (`qmEarnings`), Shorts (`ceoShorts`), Corporate actions (`qmSplits`, `qmDividends`, `eodSymbolChange`), FX (*"to be sourced"*). - **What I found (`[Verified: QA Mongo]`):** Every dataset in Section 7 was sampled and audited via `MONGODB_READ_URI`: | Dataset (Collection & Count) | Empirical Audit Result in QA MongoDB | Real PIT `known_at` Derivable? | Honest Fallback & Research Ruled Out | | --- | --- | --- | --- | | **Fundamentals — QM** (`qmFinancials` `1.86M` + omitted `qmFinancials-old` `908k`) | **0 / 5,000 (`0.0%`)** have `filingDate` or `acceptedDate`; only `reportDate`, `periodEndDate`, `created_at` (2025 crawl). Unique-indexed on `(qmSearchCode, reportPeriod, reportDate)` and overwritten in place → **0 restatement versions** across `AAPL`, `NVDA`, `SMCI`, `TSLA`, `SHOP:CA`, `RY:CA`, `X:CA`. | **Only `filingDate` via `qmFilings` join; NO restatement history.** | Join `(listing_id, periodEndDate)` to earliest matching `10-Q`/`10-K`/`40-F`/SEDAR `52-109` filing `timefiled` in `qmFilings`. Where unmatched, add statutory deadline lag (**US: +45d Q / +90d FY; CA TSX: +45d Q / +90d FY; CA TSXV/CSE venture: +60d Q / +120d FY** per NI 51-102) + flag `known_at_quality = 'estimated_lag'`. **Rules out:** restatement alpha, pre-restatement surprise studies, exact filing-day fundamental triggers on unlinked rows. | | **Fundamentals — EOD** (`eodFinancialsOLD` `2.98M`, `eodFundamentalsOLD` `106.6k`) | In `eodFinancialsOLD` (20k sample): **`19,851 / 20,000` (`99.26%`) have `filingDate === reportDate`** (30–90d look-ahead!). In `eodFundamentalsOLD`: `filing_date` is `null` across quarters, `Highlights`/`Valuation` are unversioned scrape-time snapshots, and **currency labels are corrupted on CDRs** (`AAPL` on `NEO`, `_id: 658615f03d1ee2d2611de872`, labels Apple's `$335.0B` USD `totalAssets` as `"CAD"` on alternating quarters!). | **No.** | **Quarantine `eodFundamentalsOLD` `Highlights`/`Valuation` completely from backtests** (live screener display only). Use `eodFinancialsOLD` only for pre-QM history with mandatory +45d/+90d/+120d lag, ignoring its bogus `filingDate == reportDate`, and cross-check statement currency against magnitude/instrument currency. | | **Macro** (`teData` `14,794` docs) | Every document stores `data: [{ d: "YYYY-MM-01", v: }]` with `lastUpdated: 2026-04-02` (e.g., US `GDP CQOQ` `{d: "2025-12-01", v: 0.7}`, US `NFP TCH` `{d: "2026-02-01", v: -92}`, CA `CACPIYOY` `{d: "2026-02-01", v: 1.8}`). **Zero release dates; zero initial/revised vintages.** | **No.** | Apply conservative publication lags (`+1d` central-bank rates `FDTR`/`CCLR`; `+35d` monthly CPI/NFP/unemployment; `+65d` initial / `+90d` final quarterly GDP) and restrict `teData` to **coarse slow-moving regime filters**. **Rules out:** macro release event studies, macro surprise trading, and un-revised real-time GDP/NFP models (unless ALFRED/FRED + StatCan real-time vintages are ingested). | | **Earnings** (`qmEarnings` `444,865` docs) | **`297,779 / 444,865` (`66.94%`)** have `announceTime: "N/A"` (`80,481` `AMC`, `66,605` `BTO`). `consensusEps` is overwritten in place (`created_at: 2025-06-29`), with no estimate revision history. | **Date yes; intraday session only on 33% (unless linked to `qmFilings`).** | Link to `qmFilings` (`8-K` / Canadian `News release` `timefiled`) to resolve BMO vs AMC. Where `announceTime == "N/A"` and unlinked, stamp `known_at = reportDate 16:05 ET` (tradable at `T+1` open). **Rules out:** pre-announcement analyst-revision drift and `T+0` open PEAD entries on un-timestamped rows. | | **Filings** (`qmFilings` `30.52M` docs) | `100%` of sampled rows carry second-precision `timefiled` (`"2024-10-08T17:30:13 EST"`, `"2023-11-28T10:02:05 EST"`). **However, documents contain metadata + external QuoteMedia URLs (`htmllink`/`xlslink`) ONLY — zero filing body text and zero parsed Form 4 / SEDI share counts or buy/sell indicators** (verified on AAPL Form 4 `acc: 0000320193-24-000114`, `filer: "MAESTRI LUCA"`). | **Yes (`timefiled`, convert `EST`/`EDT` cleanly to UTC).** | Filing-arrival/form-type event studies work immediately (`Form 4` count, `144` sale notice count, `8-K`, `NI 43-101`, `52-109`). **Rules out:** insider net-buy dollar/share-size signals until Form 4 XML / SEDI is fetched and parsed. | | **Dividends & Splits** (`qmDividends` `495,942`, `qmSplits` `18,751`) | `qmDividends`: `408,295` (`82.33%`) have valid `declared < date` (ex-date); `86,588` (`17.46%`) lack `declared`; `1,059` have `declared >= date`; CAD dividends carry bogus `usdFxRate: 1` (`X:CA` `_id: 6861bc9c9aba109fccfe8659`). `qmSplits`: **only `5,646 / 18,751` (`30.11%`)** have `declared`, plus `258` no-op `splitratio == 1` rows. | **Ex-date accounting: 100%. Announcement `known_at`: 82% divs, 30% splits.** | Filter `splitratio == 1` and ignore `qmDividends.usdFxRate` (join real `fx` instead). Accounting/adjustments trigger on `ex_date` (known to market at `ex_date` open). **Rules out:** split-announcement drift on the 70% missing `declared` unless linked to `qmFilings`. | | **Symbol Changes** (`eodSymbolChange` `230` docs) | **230 rows total**, **100% `exchange: "US"`**, `effective` spanning **`2024-08-12` to `2025-07-03` only** (`0` Canadian rows, `0` pre-Aug-2024 history). | **Useless for 20y history.** | Cannot drive `listing_symbol_history` (see Finding F2). | | **CEO Posts & Shorts** (`ceoPosts` `14.78M`, `ceoShorts` `692,904`) | **100% Canadian** (`CNQ` 4,583, `TSX` 4,127, `CDX` 3,292, `AQL` 587; `0` US). `ceoPosts` has ms `timestamp`, **but `360 / 20,000` (`1.80%`) have `edited != null`** where `spiel` text was overwritten later, and includes `@thenewswire` press-release bots (`bot: "1"`). `ceoShorts` timestamps (`SHOP.TO`: `2025-05-15`, `2025-05-31`, `2025-06-15`) are **CIRO/IIROC semi-monthly report period-ends, NOT publication dates** (published 3–4 business days later). | **Posts: yes (with edit guard). Shorts: requires +4 business-day lag.** | For `ceoPosts`, if `edited != null`, either set text `known_at = edited` or exclude edited text from NLP while keeping unedited post-count pulse at `timestamp`; separate `bot == "1"` newswires from retail posts! For `ceoShorts`, set `known_at = timestamp + 4 Canadian business days (17:00 ET)`. **Rules out:** US social/short research from CEO.ca. | | **FX (`USD/CAD`)** | **Already ingested (`[Verified: QA Mongo]`)!** `eodPrices` has `CAD.FOREX` (`12,109` daily bars, `1971-01-04..2025-08-13`) and `CADUSD.FOREX` (`9,351` daily bars); `eodIntraday1M` has **`5,202,056` 1m bars** for `CAD.FOREX` + `5,204,726` for `CADUSD.FOREX`; `teMarketData` has `USDCAD` (`2,865` daily bars through `2026-04-02`). | **Yes.** | No external FX sourcing needed for Phase A–E; curate `CAD.FOREX` (1m + 1d) supplemented by `teMarketData.USDCAD` (post-Aug 2025). | | **Futures** (`ttFutures` `1.46M` docs) | Individual historical contracts (`AD90M`, `CD`, `CL`, `SP`, `US`) from 1959 onward with **corrupted date strings** (`minDate: "2001-/0-2/"`, `maxDate: "NaN-at-e\""`). | **Dirty / archival.** | Defer completely out of scope until post-equity live. | - **Recommendation:** Add an explicit `known_at_source` enum (`'filing_timestamp' | 'exchange_bar_close' | 'declared_date' | 'statutory_lag_estimate'`) to every curated PIT row, implement the `qmFilings` → `qmFinancials`/`qmEarnings` timestamp join + NI 51-102 / SEC statutory lag fallbacks + `+4bd` CIRO short lag, quarantine `eodFundamentalsOLD` snapshots, and restrict `teData` to lagged regime features (adding FRED/ALFRED + StatCan real-time vintages later only if macro-release alpha becomes a priority). --- ### F2 [CRITICAL — Price/Volume/Survivorship Corruption] — Split-Adjustment Asymmetry Across `eodPrices`, `qmPrices`, and `eodIntraday1M`, Plus Unmodeled Terminal Delisting Losses - **What the plan says (§5 lines 245–247, §6 lines 317–320, §9 lines 430–431):** - `bars_1m`, `bars_5m`, `bars_1h`, `bars_1d` store **raw OHLCV**, with `adj_factors` applied on read or materialized (`ADR-003:17` also mandates raw prices for share/cash execution). - Universe is *"survivorship-free"* with *"delistings with delisting returns"*. - **What I found (`[Verified: QA Mongo]`):** 1. **`eodIntraday1M` (`3.40B` bars) is ALREADY retroactively split-adjusted, whereas `eodPrices` (`845.7M` bars) has RAW OHLC:** - Tested on `NEXM.V` / `NEXM:CA` (`1:20` reverse split on `2025-06-20` in `qmSplits`, `splitratio: 20`): pre-split `eodIntraday1M` on `2025-06-18 16:01` already reports `close: 24.29` (matching post-split `2025-06-20 18:02` `close: 24.2799`), instead of raw `~$1.21`! Storing `eodIntraday1M` into `bars_1m` as "raw" and applying `adj_factors` **double-adjusts every split across 3.4 billion bars**. Conversely, `qmIntraday` (`173M` bars) stores *both* raw (`open..close`, `sharevolume`) and split-adjusted (`adjustedopen..adjustedclose`, `avolume`). 2. **`eodPrices.volume` is SPLIT-ADJUSTED while `eodPrices.close` is RAW (10×–56× dollar-volume inflation!):** - Tested on `X.TO` / `X:CA` (`5:1` split on `2023-06-14`): on `2023-06-13`, `eodPrices` has `close: 147.78` (raw), `adjustedClose: 28.1493`, and **`volume: 676,795` (`= 5 × 135,359`)**, whereas `qmPrices` has `unadjustedclose: 147.78` and **`sharevolume: 135,359` (raw)**! - Tested on `NVDA` (`10:1` split on `2024-06-10`): on `2024-06-07`, `eodPrices` has `close: 1208.88` (raw) and **`volume: 412,385,776` (`= 10 × 41,238,580`)**, whereas `qmPrices` has `unadjustedclose: 1208.88` and **`sharevolume: 41,238,580` (raw)**! - Multiplying `eodPrices.close * eodPrices.volume` yields **$498.5B/day** for NVDA pre-split (10× overstated) and **56× overstated pre-2014 liquidity** for AAPL — completely breaking universe dollar-volume filters and `ADR-003:12`'s `participation_rate * bar.volume` fill-capacity cap! 3. **Delisted symbols exist (`52,745` US + `3,136` CA in `eodSymbols`; `15,790` US + `3,626` CA inactive in `qmSymbols`), BUT terminal delisting losses & spliced bankruptcies corrupt naive survivorship:** - **Primary → OTC Pink venue drop hides bankruptcy wipeouts:** `SIVB.US` (`Exchange: NASDAQ`, `ISIN: US78486Q1013`) ends on `2023-03-09` at **`close: $106.04`**, then reappears as a *separate* symbol `SIVBQ.US` (`Exchange: PINK`, same ISIN `US78486Q1013`) trading pennies down to `$0.006`. Under §6's `listing = instrument + mic`, `XNAS` (`SIVB`) and `OTCM` (`SIVBQ`) are distinct `listing_id`s: marking or exiting `SIVB` at its last `XNAS` bar (`$106.04`) misses a **-99.5% loss**! - **Missing terminal cancellation bars:** `BBBYQ.US` ends on `2023-09-29` at `$0.0789` with no `$0.00` (-100%) Chapter 11 cancellation event; meanwhile cash M&A (`AAR-UN.TO` ending `2018-05-25` at `$8.09`, `X.US` ending `2025-06-20` at `$54.84`) ends near deal price. - **Overwritten pre-bankruptcy tickers in EOD:** `GM.US` in `eodPrices` starts `2010-11-18` (post-bankruptcy IPO) and `HTZ.US` starts `2021-07-01` — pre-2009 Old GM and pre-2020 Old Hertz were overwritten under their root tickers. - **Recommendation:** 1. **Un-adjust `eodPrices.volume` and `eodIntraday1M` OHLCV** during Step 2 curation using cumulative post-bar split factors from `qmSplits` (cross-checked against `eodPrices` step changes and `qmPrices`/`qmIntraday` raw series where overlapping), so `bars_*` is genuinely raw in both price *and* share count; reject or flag any symbol where split un-adjustment leaves an unexplained step jump. 2. **Link exchange delistings to same-ISIN OTC continuation (`XNAS`/`XNYS` → `OTCM`)** as a mandatory corporate-action liquidation bridge: if a strategy's universe excludes OTC, force-exit at the **first tradable OTC open** (capturing the `$106.04 → $0.50` SVB gap loss!), and if a delisted equity has no M&A/cash payout filing and disappears below `$1.00` (or with `-Q` bankruptcy suffix), apply a Shumway terminal delisting return (**`-30%` default on involuntary exchange delisting without OTC print; `-100%` on cancelled `PINK`/`Q` shares**). --- ### F3 [CRITICAL — Storage Architecture (D1 & §5)] — QuestDB `ASOF JOIN`, `DEDUP`, and `INT` Keys Break on Bitemporal Fundamentals and Cross-Sectional Scans; `libs/data/questdb` Is Broken Today - **What the plan says (§3 D1, §5 lines 192–253):** - Keep all curated data (`bars_*`, `adj_factors`, `corporate_actions`, long-format `fundamentals (listing_id, period_end, field)`, `events`, `shorts`, `macro`, `fx`) in QuestDB with integer `listing_id` keys and `known_at` on every row (`known_at <= asOf` as a query rule), plus a dual-backend parity harness from Day 1. - **What I found (`[Verified: external — QuestDB 10.2.0]` + `[Verified: repo]`):** 1. **Deployed QuestDB version discrepancy:** `docker-compose.yml:67` and `docker-compose.dev.yml:82` use unpinned `questdb/questdb:latest` (`quant` pulled **QuestDB `10.2.0`**, while the pre-migration local image was built `2025-05-30`). Worse, `apps/stock/data-pipeline/src/index.ts:66` sets `enableQuestDB: false` (*"Disabled for now due to auth issues"*), and `libs/data/questdb` is broken: `client.ts:272` & `query-builder.ts:230` emit deprecated `LATEST BY`, `client.ts:323` runs invalid `SELECT * FROM table_columns WHERE table_name = ?`, `schema.ts:313-335` silently drops `WAL`/`dedup`/`capacity`/`index` options, `query-builder.ts:95-111` interpolates raw SQL strings, and `schema.ts:28-156` auto-creates 6 legacy ticker-keyed tables on every `connect()`. 2. **Long-format EAV `fundamentals (listing_id, period_end, field, value, known_at)` breaks QuestDB `ASOF JOIN`:** - QuestDB `ASOF JOIN` requires both tables to be ordered by their **designated timestamp** and returns **at most ONE right-hand row** per left row (`bars_1d ASOF JOIN fundamentals ON (listing_id)` returns **1 random `field`**, dropping the other 120 fields!). Joining 20 fields requires 20 chained self-joins, and `PIVOT` strips the designated timestamp while clobbering un-updated fields to `NULL` on partial filings. 3. **The Bitemporal Restatement / Comparative-Backfill Trap:** - Suppose Q1 (`period_end = 2024-03-31`) is filed `2024-05-10`, Q2 (`period_end = 2024-06-30`) is filed `2024-08-10`, and on `2024-09-01` a 10-Q/A restatement (or 10-K comparative table) updates Q1 (`period_end = 2024-03-31`, `known_at = 2024-09-01`). At bar `2024-09-15`, a 1D `ASOF JOIN` on `known_at` picks `2024-09-01` and **overwrites Q2 with restated Q1**, moving the company backward in fiscal time! Nor can `ASOF JOIN` compute 4-quarter TTM sums (`E/P`, `FCF yield`, `ROE`). 4. **`DEDUP UPSERT KEYS` vs. `known_at` Versioning on `bars_*`:** - QuestDB WAL `DEDUP UPSERT KEYS(ts, listing_id)` is **destructive last-writer-wins**: updating a historical bar with a new `known_at` destroys prior history and makes `WHERE known_at <= old_asOf` **drop that bar entirely** (creating a missing-date hole!). Putting `known_at` in the dedup key (`DEDUP UPSERT KEYS(ts, listing_id, known_at)`) creates duplicate `(listing_id, ts)` rows that QuestDB's `LATEST ON` **cannot** deduplicate across a time range because `LATEST ON` only accepts the designated timestamp (`ts`) and returns 1 row per partition key (`75M` `(listing_id, ts)` keys!). 5. **`INT` `listing_id` Disables QuestDB's Fast Paths:** - In QuestDB, `LATEST ON ts PARTITION BY col` only halts backward partition scans early when `col` is `SYMBOL` (dictionary-encoded); on `INT` it scans every partition in range. `ASOF JOIN` likewise uses specialized memoized paths on `SYMBOL`. At 50k–400k listings across 10 tables, `SYMBOL` must be declared `SYMBOL CAPACITY 65536 NOCACHE` to avoid JVM heap bloat. 6. **QuestDB Native Parquet Reality (`QuestDB 10.2.0`):** - QuestDB 10.2 supports `read_parquet()` and `ALTER TABLE ... CONVERT PARTITION TO PARQUET`, which cuts disk usage 5–10× on cold `bars_1m` partitions — **but queries slower inside QuestDB than native mmap** and rewrites entire partitions on out-of-order writes, and its internal `table~N/` directories (`_txn`/`_meta`) are not external Hive Parquet lakes. - **Recommendation:** **Amend D1 now to split curated storage by workload behind `MarketDataStore`, and cut the dual-backend parity harness.** - **DuckDB + Hive Parquet (`/mnt/data/stockbot/curated/*.parquet`):** Store `bars_1d`, `corporate_actions`, `adj_factors`, bitemporal `fundamentals`, `events`, `shorts`, `macro`, `fx`, and `features` in ZSTD Parquet queried via DuckDB. DuckDB handles 75M daily rows (`20y × 15k` listings) with `RANK() OVER (PARTITION BY ts)`, true 2D bitemporal `QUALIFY row_number() OVER (PARTITION BY listing_id, period_end ORDER BY known_at DESC) = 1`, and zero-copy Arrow export to Polars/marimo in **<1–3 seconds** on `quant`'s SN850X NVMe + 125 GiB RAM. - **QuestDB `10.2.0` (pinned image tag, rebuilt thin client):** Reserve strictly for `bars_1m` (deriving `5m`/`1h` via `SAMPLE BY` or materializing where needed) + live/paper hot streaming bars, using `listing_id SYMBOL CAPACITY 65536 NOCACHE`, single-version `DEDUP UPSERT KEYS(ts, listing_id)` + a separate sparse `bar_revisions` table, and converting sealed `>90d` `bars_1m` partitions to Parquet (`CONVERT PARTITION TO PARQUET`) only if NVMe space requires it. - *(Close runner-up if you insist on keeping 100% of v1 in QuestDB: materialize wide forward-filled `fundamental_pit_snapshots` + TTM columns in `data-pipeline` before writing to QuestDB, store `listing_id` as `SYMBOL NOCACHE`, keep `bars_1d` single-version + sparse `bar_revisions`, and still skip building the DuckDB parity harness until QuestDB fails a measured exit target.)* --- ### F4 [CRITICAL — Statistical Rigor & Security (§1, §9, §11, §12)] — Active Holdout Leak in `web-api` Today, Six Trial-Ledger Bypass Vectors, and Adaptive Holdout Overfitting - **What the plan says (§1 lines 44–50, §9 lines 437–458, §11 lines 531–535, §15 line 671):** - Sealed out-of-sample holdout *"Exists"*; every signal analysis, screen, and backtest from any agent, notebook, or UI is recorded in the trial ledger; notebooks get a *"flagged raw-SQL escape hatch"*; and *"Everything up to Validated can run unattended."* - **What I found (`[Verified: repo]`):** 1. **The "sealed" holdout is wide open across calls today:** - While a single `ChronologicalValidation` state machine (`apps/stock/web-api/src/services/chronological-validation.service.ts:163-444`, `database/postgres/init/24-chronological-validation.sql`) freezes `train` selection before running `test`, **`research-agents.service.ts:51` explicitly permits `sb-research.*` tokens to call `GET /api/v2/datasets/canonical/:hash/export`!** Because `submitValidation` immediately inserts the `test` slice into `backtest_datasets` and returns its hash (and the parent `backtestId` spans `train+validation+test`), **any agent can download every bar of the `test` holdout in plaintext JSON** (`scripts/research-client.ts:782-797`), run whole-window sweeps on `backtestId`, read all other principals' `test` trade logs via unscoped global `GET`s (`research-agents.service.ts:46-53`), and re-submit `v1, v2, ..., v500` against `test` with **zero cumulative budget** (`28-research-agents.sql:100-191` only caps concurrent `active_trials` and per-experiment `<= 100` runs, never lifetime trials!). 2. **No trial ledger, DSR, PBO, or CPCV exists in the live stack:** - `chronological-validation.ts:30-31` hardcodes `labelHorizonMs: z.literal(0)` (no purge/embargo). The only DSR code in the repo (`apps/stock/analytics/src/analysis/statistical_validation.py:56-58, 130-156`) is dead (`503` disabled in `CL35`), omits skewness/kurtosis and cross-trial Sharpe variance, and calls `calculate_deflated_sharpe_ratio` with default `num_trials = 1` (`ln(1) = 0`)! 3. **Three fatal bypasses in the proposed MCP + Python SDK + marimo design:** - **In-memory Polars evasion:** Once `stockbot.data.bars()` or MCP `query_data` returns a DataFrame to marimo or a script, an agent can loop over 5,000 expressions in Python memory with **zero SDK analysis calls** and register only the winner (`N = 1` logged instead of `5,000`). - **Desktop Claude Code host access:** `studio.config.json:5,9` gives desktop agents `"shell": true` on the host where `.env` and unauthenticated QuestDB (`:9000`/`:8812`) live. - **Raw-SQL escape hatch (§5 line 211):** Bypasses `known_at <= asOf`, holdout date fences, and trial counting simultaneously. "Flagging" a notebook does not stop an agent or human from copying the winning formula into a clean MCP backtest call. 4. **Adaptive holdout destruction (§15 line 671):** Allowing unattended agent campaigns to run through `Validated` on the holdout and write verdicts to the Knowledge Base / Studio `evolve` loop turns the holdout into an adaptive training oracle ($k$ adaptive queries leak information at $O(\sqrt{k/T})$). - **Recommendation:** 1. **Two-Tier Air-Gapped Holdout:** Split OOS into **(a) Research Validation (`ts < VAULT_CUTOFF_DATE`, e.g., trailing 24 months reserved)** evaluated via **Purged Walk-Forward + CPCV (`purge = horizon + warmup`, `embargo = max(5d, 0.01*T)`) + DSR/PBO** for unattended `Validated` gating, and **(b) a Physically Air-Gapped Vault Holdout (`ts >= VAULT_CUTOFF_DATE`)** stored in a separate vault path unreadable by `MarketDataStore`, `export`, marimo, or `sb-research.*` tokens. Only a human `Validated → Paper` action triggers a **one-shot Vault evaluation** (hard-capped at $\le 10$ vault burns/year in an immutable Postgres table, rolling forward annually). 2. **Patch `research-agents.service.ts` & `28-research-agents.sql` immediately:** Remove `/export` from `sb-research.*`, scope `GET` routes by `allowedProjectIds`/grants, and add **cumulative per-campaign and daily trial + bar-evaluation counters** enforced in SQL triggers. 3. **Define "related trial" deterministically & store return vectors for $\hat{N}$:** Group trials by **objective `(universe_market, horizon_bucket)`** (`{US, CA, US_CA} × {intraday, swing_1_10d, position_10d_plus}`), never by agent-invented `family` labels. Persist the **daily out-of-warmup return/IC vector** (float32 array, ~20 KB for 20y daily) of every evaluated variant in `trial_ledger` so **DSR** computes Bailey & López de Prado's **effective independent trials $\hat{N} = 1 + (N-1)(1 - \bar{\rho})$**, cross-trial Sharpe variance $\text{Var}[\{\widehat{SR}_n\}]$, and non-normal $(\hat{\gamma}_3, \hat{\gamma}_4)$, while **PBO (CSCV, $S=16$ slices)** runs over synchronous campaign return matrices $M_{T \times N}$. 4. **Close notebook/agent bypasses:** Run autonomous agents in `--network` isolated containers talking **only** to the MCP/HTTP API (no raw SQL, no DB ports, no host shell); restrict the raw-SQL escape hatch to human localhost sessions over pre-vault views; and log data-pull footprints (`universe × window × features`) alongside every trial. --- ### F5 [HIGH — Security Master (§6)] — Blocking on `MIC` Breaks on >80% of `ibSymbols`, Ticker Reuse (`FB`, `GM`, `HTZ`) Collides Without Validity Windows, and Naïve MongoDB Price Cross-Checks Are 13.6× Slower Due to Index Order - **What the plan says (§6 lines 260–351):** - Pass 1 maps each provider exchange code to a canonical ISO 10383 `mic`. - Pass 3 blocks candidates within **`country + MIC`**: Tier 1 = `Valid ISIN + MIC` (`IB, EOD`), Tier 2 = `CUSIP-derived ISIN + MIC` (`IB → EOD`), Tier 3 = `Normalized ticker + MIC (+ currency)`. - Pass 4 compares overlapping daily closes per candidate pair; Pass 6 sources ticker history from `eodSymbolChange`. - **What I found (`[Verified: QA Mongo]` + `[Verified: repo]`):** 1. **`ibSymbols` (`18,402` rows) stores execution/ATS venues, NOT primary listing MICs (`isPrimeExchId` is `null`):** - Actual `ibSymbols` venue distribution (`[Verified: QA Mongo]`): - **Canada (`3,846` rows):** `AEQLIT` (Cboe/NEO Lit ATS) = **`2,506` (`65.2%`)**, `VENTURE` = `826`, `TSE` = **`514` (`13.4%`)**. Over **83% of TSX-listed stocks** in `ibSymbols` (e.g. `CIA` = Champion Iron) have `exchangeId = "AEQLIT"` (`NEOE`), whereas EOD (`TO`) and QM (`TSX`) place them on `XTSE`! - **US (`14,556` rows):** `OTCLNKECN` = `6,627`, `ARCAEDGE` = `1,067`, `AMEX` = `838`, `BEX` = `777`, `DRCTEDGE` = `682`, `EDGEA` = `523`, `IEX` = `509` (e.g., Agilent `A`!), `LTSE` = `426`, `MEMX` = `397`, **`NYSE` = ONLY `370` (`2.5%`)**, `CHX` = `310`, `NYSENAT` = `250`, **`NASDAQ` = ONLY `241` (`1.7%`)**! - Meanwhile, `eodSymbols` puts `103,792` US rows under composite `eodExchange = "US"` (including **`44,970` `NMFQS` mutual funds** that must be excluded from equity universes, plus `262` `Exchange: null` and `288` `Exchange: "US"` rows), and existing `normalizeProviderSymbol` (`apps/stock/data-pipeline/src/normalization/provider-symbol.ts:34-49`) ignores `exchangeId` and `description`, skipping **100% of `ibSymbols`** today! - **Result:** Blocking or matching Tier 1/Tier 2 on `ISIN + MIC` **misses >90% of US NYSE/Nasdaq stocks and >83% of TSX stocks in `ibSymbols`**! 2. **Matching without temporal validity windows corrupts reused tickers (`FB` vs `META`, CSE duplicates):** - Verified live collision (`[Verified: QA Mongo]`): EOD retroactively renamed Facebook's 2012–2022 bars to `META.US`, while `FB.US` is now **active** (`Name: "ProShares Trust ProShares S&P 500 Dynamic Buffer ETF"`, `Exchange: "BATS"`, `Isin: null`, bars starting `2025-06-26`). Meanwhile `qmFilings` (`30.5M` docs) keys historical 2012–2022 Facebook filings by `symbol: "FB"`! Static Tier 3 ticker matching attaches Meta's historical filings/events onto a 2025 S&P 500 Buffer ETF. Similarly, `qmSymbols` has duplicate `(symbol, exchange)` rows on `CNQ` (`VOY:CNX` active + `VOY:CC` inactive, `PKK`, `RIPP`, etc.). 3. **ISINs and CUSIPs are NOT immutable across reorganizations and TSXV share consolidations:** - `instrument(instrument_id, ISIN, CUSIP, ...)` assumes 1 permanent ISIN per company. In Canada (`XTSX`/`XCNQ`), every reverse split / name change / continuance issues a **new CUSIP and ISIN**, and corporate redomiciliations (`LIN` Praxair/Linde US → Ireland → UK ISINs; SPAC de-SPACs) change ISIN while the economic listing continues. 4. **Pass 4 Price Cross-Check MongoDB Index Trap:** - `eodPrices` (`845.7M` docs) has `{date: 1, eodSearchCode: 1}` and `{eodSearchCode: 1}` — **no `{eodSearchCode: 1, date: 1}` index**! Benchmarking 10 symbols via `MONGODB_READ_URI` took `309.6 ms` on `eodPrices` (scanning full 25y symbol history) vs `22.8 ms` on `qmPrices` (`13.6×` slower warm; seconds per symbol cold on uncached delisted symbols → many hours for 50k pairs). - **Recommendation:** 1. **Two-stage resolution (Instrument first, Venue second):** Resolve **`instrument`** globally by Luhn-valid ISIN / CUSIP-derived ISIN (with an `instrument_identifier_history(instrument_id, id_type, id_value, valid_from, valid_to)` table for reorganizations/reverse-splits). Determine primary `listing (instrument_id, mic)` from **EOD `Exchange` + QM `exchange`** (filtering out `NMFQS` mutual funds from equity universes), and attach `ibSymbols` (`conid`) at **`(instrument_id, currency)`** — never treating IB `AEQLIT`/`IEX`/`BEX`/`ARCAEDGE` as primary listing MICs! 2. **Precompute `[first_bar_date, last_bar_date]` per `(source, source_id)` before Pass 3:** Require overlapping active date windows on Tier 3/4 ticker matches, populate `provider_mapping.(valid_from, valid_to)` from observed bar/filing spans + corporate actions rather than relying on the 230-row `eodSymbolChange` table, and route non-overlapping same-ticker pairs (like pre-2022 `FB` vs 2025 `FB`) to separate `listing_id`s. 3. **Execute Pass 4 Price Cross-Check via 25 stratified cross-sectional dates (`{ date: { $in: sampleDates } }`), NOT per-pair queries:** Querying `eodPrices` by `date` first hits `{date: 1, eodSearchCode: 1}` sequentially (or run Pass 4 in DuckDB *after* bulk-extracting US+CA daily closes), completing all US+CA candidate return-correlation & USD/CAD ratio checks in **<30 seconds** instead of hours. --- ### F6 [HIGH — "One Engine" vs. Actual Design (§4, §8, §9, §11)] — Three Engines, 5× Conflicting Math Implementations, a 5,400 bars/s NAPI Bottleneck, Two Multi-Asset Rust Bugs, and a Five-Wall Python→TS Promotion Blockade - **What the plan says (§1 line 46, §8, §9, §11 lines 534–536):** - *"One engine. The same Rust core runs backtest, paper and live."* - Tier 1 fast vectorized screener *"Reopens deferred task P06"*. - Tier 2 extends the Rust engine to multi-asset cross-sectional long/short portfolios; strategies stay sandboxed TypeScript; `register_signal(...)` promotes a Python notebook signal into the feature library and strategy lifecycle. - **What I found (`[Verified: repo]`):** 1. **Three coexisting simulators + 5–6 conflicting indicator/metric implementations exist today:** - Engines: **(a)** Canonical fixed-decimal Rust `financial/*`, **(b)** Legacy `f64` Rust `BacktestEngine` (`engine/src/backtest/engine.rs`), and **(c)** Legacy TypeScript `SimulationExecution` (`orchestrator/src/execution/SimulationExecution.ts`). - Math divergence (`[Verified: repo]`): **RSI** has 3 incompatible formulas (on flat prices `gain=loss=0`, Rust `rsi.rs:72-77` returns **`99.01`**, Rust `calculate_rsi` returns **`100.0`**, TS `RsiIndicator` `rsi.ts:36-38` returns **`50.0`**, and `trailingSimpleRsi` uses simple rolling averages instead of Wilder smoothing!). **Sharpe, Sortino, Volatility, Annualization, and Max Drawdown** have 5–6 implementations using conflicting `ddof=0` vs `ddof=1`, `252` vs `365` vs `365.25` days/year, geometric vs arithmetic returns, and Sortino denominators (`return-statistics.ts:50-102` vs `simple_results.rs:174-235, 399-431` vs `performance.py:139-163` vs `statistical_validation.py:94-108`). 2. **`P06` is mischaracterized (§9 line 418 vs `docs/development/backlog/tasks/P06.md`):** - `P06` is a tiny declarative AST inside the event-driven Rust `Replay` loop requiring **exact economic-hash equivalence** — *not* a vectorized cross-sectional screener. A vectorized matrix screener (`Polars`/`DuckDB` computing `(T × N)` weights × forward returns minus linear turnover cost) intentionally omits integer lot rounding, cash reservations, and path-dependent halts: it **will** implement simplified portfolio math separate from Rust, and the plan should own that explicitly rather than calling it `P06`. 3. **Two concrete multi-asset bugs inside `apps/stock/engine/src/financial/` today:** - **Bug A — Non-atomic `Target` cash reservation blocks portfolio rotation (`matching.rs:1083-1136`, `risk.rs:564-566`):** `Ledger`, `RiskAccount`, and `MatchingAccount` already use multi-instrument `BTreeMap`s internally (single-asset is gated in TS at `native-worker.ts:49-51` and `candidate-execution.ts:27-42`), **but** `StrategyIntent::Target` submits `Sell A` and `Buy B` sequentially against `available_cash()`. Because pending `Sell A` proceeds are not credited until next-open fill, any fully invested cross-sectional rebalance rejects `Buy B` with `RiskRejection::InsufficientCash`! - **Bug B — Sequential same-timestamp marking latches false drawdown halts (`ROADMAP.md:44`, `replay.rs:24-28`):** Updating marks lexically one instrument at a time at timestamp `t` trips irreversible portfolio daily-loss/drawdown halts on intermediate unhedged marks even when simultaneous offsetting long/short moves leave net equity flat. 4. **The 5,400 bars/s NAPI + JSON wall (`conditional-review.md:27-28`, `api/canonical.rs:33-43`):** - Every trading bar crosses JS↔Rust NAPI twice (`advance` + `submit`), double-parsing JSON inside `api/canonical.rs:33-43` and recursively cloning/freezing plain JSON state (`strategy-decision.ts:35-88`) — plus two Docker stdio pipe crossings per bar for sandboxed candidates (`candidate-sandbox.ts:279-323`). At ~5,400–7,400 bars/s, a single 20-year daily cross-sectional backtest over 8,000 listings (`40M` bars) takes **~1.8 hours** unless strategies trigger **only on rebalance barriers** (e.g., daily close / weekly) with batch binary/Arrow observation loading rather than stringified JSON per bar! 5. **Five hard walls block moving a signal from Python/marimo to a TypeScript strategy today:** - **(i)** `candidate-host.ts:29-42` bans **all `import`s** (even `@stock-bot/calculations`); **(ii)** `StrategyContext` (`libs/research/src/strategy-api.ts:39-60`) only carries OHLCV `PreparedBar`s — **zero channel for features, fundamentals, or events**; **(iii)** `Replay::validate` (`replay.rs:404-413`) requires `open/high/low/close > 0` (`Positive`), so signed signals/z-scores cannot even be passed as synthetic bars; **(iv)** `copyJsonState` bans `Float64Array`/`Map`; and **(v)** promoting a candidate to `paper-host.ts:34-37` drops the Docker/seccomp sandbox completely! - **Recommendation:** 1. **Make Feature Materialization the sole Python → TypeScript bridge:** Define features once as versioned **DuckDB SQL or Python/Polars batch jobs** (`features//v.py|.sql`) that write `(listing_id, ts, known_at, value: f64)` to the `features` store. Add a read-only `features: Record` map to Rust `Replay` decision barriers and `StrategyContext`. Then Python notebooks, the vectorized screener, AND TypeScript strategies all read the **exact same precomputed feature values** — zero Python→TS indicator rewrites, and sandboxed TS strategies shrink to ~40 lines of pure sizing/rebalance logic! 2. **Consolidate metrics & retire legacy engines:** Delete dead `apps/stock/analytics` metric code and retire legacy `f64` `BacktestEngine` + TS `SimulationExecution` once multi-asset cutover lands; make `libs/calculations` (`returnStatistics`, `drawdownAnalysis`, plus new DSR/PBO) the **single** metric calculator served by the Research Kernel API to UI, MCP, and Python SDK. 3. **Fix Rust multi-asset replay before Phase C:** **(a)** Apply all bar marks at timestamp `t` atomically before evaluating `RiskAccount` drawdown/daily-loss latches; **(b)** add net-proceeds target rebalancing (`expected_sell_proceeds * (1 - haircut)` offsetting same-barrier buy reservations for next-open `Target` batches); **(c)** strip the duplicate `serde_json::Value` round-trip in `api/canonical.rs:33-43` and load datasets into Rust from Parquet/Arrow paths instead of `JSON.stringify` (which also hits PostgreSQL's 1 GB `JSONB` limit on universe datasets!). --- ### F7 [HIGH — Phase 0 Safety & Bootstrap] — Three Undocumented Bugs in the Current Working Tree Break Phase 0 Isolation and Leak Secrets - **What the plan says (§2 lines 71–92, §6 line 351, §16 Phase 0, §17 lines 691–698):** - Only 2 gates fail (`test:tooling` and `lint:check`); `audit:secrets` passes; `mongoReadOnly` rejects all MongoDB writes at the client layer; `assertEnvironmentSafety()` enforces dev isolation; Phase 0 starts `trading_bot_dev` (`5433`) and runs `data-pipeline` against QA Mongo via `MONGODB_READ_URI`. - **What I found (`[Verified: repo]`):** 1. **Dev PostgreSQL init scripts (`01`–`05`) hardcode `\c trading_bot;` — leaving `trading_bot_dev` with ZERO master tables:** - `database/postgres/init/01-init-database.sql:5-9` runs `CREATE DATABASE trading_bot` and `\c trading_bot;`, and `02-master-schema.sql:3`, `03-initial-data.sql:2`, `04-provider-exchange-mapping-schema.sql:3`, and `05-add-visible-column.sql:3` all execute `\c trading_bot;`! Meanwhile `06`–`33` omit `\c` and run in `POSTGRES_DB` (`trading_bot_dev`). On a fresh `docker-compose.dev.yml` volume, `exchanges`, `symbols`, `provider_mappings`, `provider_exchange_mappings`, and `sync_status` are created in an unused `trading_bot` DB, so `data-pipeline` connecting to `trading_bot_dev` immediately crashes on missing tables! 2. **`MongoDBClient` `readOnly: true` is bypassed by `getDatabase()` / `collection()`, and `data-pipeline` has an active MongoDB write handler:** - `libs/data/mongodb/src/client.ts:195-202, 384-395, 637-639, 682-684` (`getDatabase()`, `getDb()`, `database`, `getCollection()`, `collection()`) return unwrapped native `mongodb` driver objects with zero `assertWritable()` checks! - `apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts:73-128` calls `mongoClient.getDatabase().collection('masterExchanges').updateOne(...)` and `.insertOne(...)`! - Worse, `apps/stock/config/src/env-safety.ts:86-94` only emits `logger.warn` (does **not** throw!) if `development` `dataPipeline` connects to QA MongoDB as `trading_admin`, and `isQaMongoTarget` (`lines 43-47`) returns `false` if `MONGODB_URI` omits `/stock` in the URL path (`mongodb://localhost:27017?authSource=admin`)! 3. **Live third-party credentials committed in source missed by `audit:secrets` + scheduled ingestion auto-start:** - `apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19` hardcodes a live rotating Webshare proxy URL with username/password, and `docs/data-sources.md:15` contains a plaintext Alpha Vantage key. - Starting `data-ingestion` runs scheduled background crawls automatically unless `QUEUE_ENABLE_SCHEDULED_JOBS=false` (verified live when `teCountries.updated_at` advanced on container boot). - **Recommendation:** Add four mandatory items to **Phase 0** before touching Phase A: **(1)** strip `CREATE DATABASE trading_bot` and `\c trading_bot;` from `database/postgres/init/01..05.sql`; **(2)** throw in `MongoDBClient.getDatabase()`/`collection()` when `readOnly: true` (or proxy read-only collections), delete legacy `sync-ib-exchanges.operations.ts`, and make `assertEnvironmentSafety()` **throw** if `dataPipeline` targets port `27017` without `readOnly` or with `trading_admin`; **(3)** rotate and remove the hardcoded Webshare proxy credential in `ib/shared/config.ts:19` (and `docs/data-sources.md:15`) and add `http://user:pass@` URL patterns to `scripts/audit-secrets.ts`; **(4)** default `QUEUE_ENABLE_SCHEDULED_JOBS=false` outside explicit ingestion worker deployments. --- ### F8 [HIGH — Live Execution & Drift (§13)] — Missing Live Bar Architecture, Confounded Drift Monitoring, Unbounded $O(N)$ Paper State Replay, and IBKR USD/CAD + TSX Microstructure Gaps - **What the plan says (§13 lines 600–615):** - Extend existing restart-safe paper host to multi-strategy/multi-asset → add IB adapter (TWS/IB Gateway) for US + Canada → OMS, continuous reconciliation, per-strategy/global risk, *"Live vs backtest tracking error on the same bars; auto-demote when outside bounds"*, and *"USD and CAD accounts/positions; base-currency P&L"*. - **What I found (`[Verified: repo]` + `[Verified: external — IBKR API]`):** 1. **Zero IB API code exists in the repo, and `paper-host` has 4 concrete defects today:** - Only a `@Disabled()` Playwright marketing-page scraper exists (`apps/stock/data-ingestion/src/handlers/ib/`), which also writes to `ib_symbols` instead of `ibSymbols` (`fetch-symbols.action.ts:108`). - **`O(N)` genesis replay per quote (`apps/stock/engine/src/api/paper.rs:68-125`):** `stage_financial_transaction` is stateless across NAPI; on **every single quote**, it loads the entire uncompacted `simulation_accounts.state` JSONB from Postgres and replays every `MatchingReceipt` and `RiskReceipt` **from account genesis twice** (`MatchingAccount::restore` at line 75 + `RiskAccount::restore` at line 95)! Over weeks of 1m/quote paper trading, every tick grows linearly slower until timeouts trip. - **Backtest vs. Paper execution-mode split:** Backtest `Replay` rejects `ExecutionMode::Quote` (`replay.rs:360-361`, forcing `Open`), whereas `validatePaperConfiguration` rejects `ExecutionMode::Open` (`paper-configuration.ts:36-37`, forcing `Quote` and requiring every pushed HTTP frame to end with an L1 `quote`, `feed.ts:370-372`). - **Bar-revision crash & missing reset/sandbox:** `CanonicalPaperRuntime` (`feed.ts:158-161`, `CanonicalPaperRuntime.ts:344-349`) throws a fatal `conflict` if a bar is revised; `api/paper.rs:20-32` omits `MatchingReset` (so a drawdown halt can never be operator-reset via NAPI); and `paper-host.ts:34-37` loads promoted candidate JS **unsandboxed** inside the privileged orchestrator process! 2. **Source of live IB bars & why they systematically diverge from EOD/QM bars:** - IB `reqRealTimeBars` emits **5-second bars only** (`whatToShow="TRADES"` required for non-zero volume) and shares IBKR's **100 concurrent market-data line cap** (and 60 req / 10 min pacing limit) with L1 `reqMktData` quote streams! Meanwhile `reqHistoricalData(..., keepUpToDate=True)` mutates forming bars in place, sends no explicit bar-closed event, revises just-closed bars on late prints, and silently dies during IBKR's nightly ~21:00 ET server reset. - **Vendor vs. IB bar divergence:** IBKR `SMART` `TRADES` filters out away-from-NBBO, combo, contingent, and certain off-exchange/odd-lot prints included in US SIP / TMX consolidated EOD & QM feeds (so IB bar volume is systematically lower and H/L wicks differ), and primary opening/closing crosses (`15:50 ET` NYSE/Nasdaq MOC cutoff; **`15:40 ET` TSX MOC cutoff**) differ between `SMART` and `primaryExchange`. Comparing live IB P&L against a backtest rerun on EOD/QM bars **confounds feed divergence with execution drift**! 3. **USD/CAD & Canadian market-structure traps on IBKR:** - **Margin vs. Cash FX:** On an **IBKR Margin account**, buying USD stocks in a CAD-funded account **does NOT auto-convert currency** — it creates a **negative USD cash balance (a margin loan accruing daily USD interest)**! On a Cash account, auto-conversion charges ~3 bps markup. Explicit programmatic FX conversion must route to **`exchange="FXCONV"`** (`secType="CASH"`, `USD.CAD`, $2 min), **never `IDEALPRO`** (which creates a virtual `USD.CAD` FX position in `positions()` that breaks reconciliation!). Both US and CA equities + `USD.CAD` settle `T+1`, except across mismatched US/CA bank holidays (Thanksgiving, Victoria Day, Civic Holiday, Boxing Day). - **Interlisted routing & TSX/TSXV board lots:** Interlisted stocks (`SHOP`, `RY`, `TD`, `CNQ`) **must** pin `conid` + `currency` + `primaryExchange` (`TSE` vs `NYSE`) so `SMART` never routes across the border. And TSX/TSXV enforce price-tiered **Standard Trading Units (Board Lots)**: **`100` shares ($\ge \$1.00$)**, **`500` shares ($\$0.10\text{–}\$0.995$)**, **`1,000` shares ($<\$0.10$)** — whereas current `wholeShareTarget` (`canonical-sma.ts:148`) sizes to 1-share integers, generating odd-lot/mixed-lot orders routed to Canadian odd-lot dealers with inferior resting fill semantics! - **Recommendation:** 1. **Build a dedicated IB Gateway Market Data & OMS Bridge service** (speaking TWS socket API to headless `IB Gateway` managed by `IBC` on the isolated `9900K` box per `docs/servers.md`): aggregate `reqRealTimeBars(5s, TRADES)` + L1 `reqMktData` quotes into session-aligned bars emitted **only after bar-close + 2s grace** (so `CanonicalPaperRuntime` never sees mid-bar mutations), capped to $\le 80$ active symbols without quote boosters (or run daily strategies off scheduled post-close/pre-open snapshots). 2. **Split Drift Monitoring into two orthogonal checks:** - **Engine/Execution Drift:** Live IB fills vs. Rust backtest replay on the **exact recorded IB live bars & quotes** (isolates slippage, partial fills, latency, and OMS bugs). - **Feed Basis Drift:** Rust replay on **recorded IB bars** vs. Rust replay on **ingested EOD/QM bars** for the same dates (isolates SIP vs. IB `SMART` bar/volume divergence). 3. **Fix Rust `Ledger` & `paper.rs` before multi-strategy paper:** Compact `simulation_accounts` checkpoints (periodic snapshot + tail receipts instead of $O(N)$ genesis replay), expose `MatchingReset`, model per-currency cash buckets `BTreeMap` with explicit `FXCONV` rebalance policy (or daily IB margin-interest accrual if intentionally borrowing), pin `conid + currency + primaryExchange` from the security master, and enforce TSX/TSXV board-lot rounding (`100`/`500`/`1000`) in position sizing. --- ### F9 [MEDIUM — PostgreSQL Migrations (§18 Q2)] — `web-api`'s `migration-runner.ts` Cannot Be Reused As-Is for `data-pipeline` - **What the plan says (§18 line 713):** - *"How are schema changes applied to existing PostgreSQL volumes? Recommendation: reuse `apps/stock/web-api/src/migrations/migration-runner.ts` for master tables instead of init SQL only."* - **What I found (`[Verified: repo]`):** - `apps/stock/web-api/src/migrations/migration-runner.ts:9-102` uses a solid transaction-pinned advisory lock (`pg_advisory_xact_lock(0x53544254, 1)`), **but** has four blockers: **(1)** importing from `apps/stock/web-api` into `apps/stock/data-pipeline` violates the `CL26` cross-app import gate (`scripts/test/shared-runtime.test.ts:13-24`), while `libs/data/postgres/src/index.ts:12` still has `// TODO: Implement migrations`; **(2)** `migration-runner.ts:48-77` hardcodes an exact `===` filename allowlist (`09`–`33`) duplicated across 3 test files (`test/postgres/migration-runner.test.ts:13-39`, etc.); **(3)** `09-backtest-run-contract.sql` crashes on standalone `data-pipeline` test schemas (`test/postgres/pipeline-safety.test.ts`) where `06..08` (`backtests`/`runs`) weren't pre-created; and **(4)** `PipelineSyncRepository.ts:19` uses a *different* advisory lock key (`0x73746274`). - **Recommendation:** Extract `runMigrations` into `@stock-bot/postgres` (`libs/data/postgres`), fix `\c trading_bot;` in `01..05.sql`, split migrations into two ordered tracks (`master` DDL `02..05 + security_master` vs `research` DDL `06..33+`) using idempotent baseline guards (`CREATE TABLE IF NOT EXISTS` for `02..08`), and expose `bun run db:migrate` so both `data-pipeline` and `web-api` apply only pure fast DDL on startup. --- ### F10 [MEDIUM — Agent Knowledge Base & Web App (§12, §14)] — Unnecessary Duplication of Studio's 83-Card Quant Library, Plus Misstated `web-app` Baseline - **What the plan says (§12 lines 556–566, 589; §14 lines 638–648):** - Build a Knowledge Base in Stock Bot *"modeled on Studio's cards: Methods, Known anomalies and their literature, Your verified findings and dead ends, Data caveats"* that *"can feed Studio's quant library."* - Evolve `dashboard → Home`, `research/experiments/backtest → Lab + Strategies + Agents`, `charts → Shared chart components`. - **What I found (`[Verified: repo]`):** 1. **`/home/boki/repos/studio/catalog/quant/library/library.yml` already contains 83 curated quant cards across 12 sections** (`validation`, `alphas`, `features`, `statistics` [DSR, BH-FDR, White's Reality Check, Newey-West], `ml`, `regimes`, `pitfalls` [PBO, look-ahead, survivorship], `portfolio`, `risk`, `microstructure`, `execution`, `live-ops`). Maintaining a second copy of generic quant methods/literature in Stock Bot creates guaranteed two-way sync rot. 2. **`web-app` baseline discrepancies (`29,590` LOC):** - `apps/stock/web-app/src/features/dashboard` is an **empty directory (`0` files)** removed in `CL24` (`App.tsx:27-28` redirects `/` to `/backtests`) — `Home` is greenfield, not an evolution of `dashboard`. - Conversely, `ResearchAgentsPage.tsx` (`377` LOC at `/research/agents`, `App.tsx:55`) and `StoredSourceInspector.tsx` (`364` LOC) **already exist** today (though `/research/agents` is missing from `Sidebar.tsx`!), and **two separate chart stacks** exist (`src/components/charts/Chart.tsx` vs `src/features/charts/components/SymbolChart.tsx`). - Also minor repo-state inaccuracies in §2 & §3: `studio.config.json:34-42` points to nonexistent `design/*` and `docs/marketing/brand.md`; actual backlog completion after E13 (`CL22–CL35`, `docs/development/backlog/README.md:3-15`) is **113 done / 5 deferred / 4 merged = 122 IDs** (not `99/5/4 = 108`); and §2 `lint:check` (`line 85`) is `61` in `phase1-inventory.ts` (`59` errors + `2` warnings) + **`4`** in WIP files = `65` (not `61 + 7`). - **Recommendation:** Mount/read Studio's `catalog/quant/library/library.yml` directly as read-only methodology/literature context in the MCP server, and store **only empirical Stock Bot artifacts** (`findings`, `dead_ends`, and `provider_caveats` linked to run/signal hashes) in PostgreSQL. In `web-app`, wire existing `/research/agents` into `Sidebar.tsx`, unify the two `lightweight-charts` wrappers before building Lab screens, and defer greenfield `Home` + `Markets` until after Signal Lab and Portfolio Backtest v2 work. --- ### F11 [MEDIUM — marimo Integration Details (D9 & §11)] — Cookie/Origin Isolation, Kernel RAM Pinning, and `MB002` Agent Codegen Failures - **What the plan says (§3 D9, §11 lines 507–539):** - Agents write `research/notebooks/*.py`; `marimo edit` for your sessions on localhost behind the app's auth; `marimo run` / static HTML for agent findings embedded in the App `Lab` tab. - **What I found (`[Verified: external — marimo docs]` + `[Verified: repo]`):** 1. **Same-origin `