From 904def37e2e9cff5dce538c3d1f61ffca3594e9d Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 15:06:10 -0500 Subject: [PATCH 01/21] =?UTF-8?q?T-128:=20M2.0=20=E2=80=94=20Baseline=20ga?= =?UTF-8?q?te=20rerun=20on=20master=20(56b73b7e,=20contains=20M1=20d52aa20?= =?UTF-8?q?b)=20before=20M2=20implementation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- design/m2-baseline-report.md | 82 ++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 design/m2-baseline-report.md diff --git a/design/m2-baseline-report.md b/design/m2-baseline-report.md new file mode 100644 index 00000000..79550824 --- /dev/null +++ b/design/m2-baseline-report.md @@ -0,0 +1,82 @@ +# Milestone M2 Baseline Verification Report (T-128 / M2.0) + +**Verdict:** **GREEN (sandbox gates + full `bun test` triage clean; 0 real failures)** — pending Studio's authoritative unsandboxed `bun run build` and `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` handoff run for the 40 sandbox-boundary failures (38 `.git` worktree metadata + 2 PostgreSQL `stock_bot_safety*` env). + +--- + +## 1. Repository Provenance + +Worktree `.git` file content: +```text +gitdir: /home/boki/repos/stock-bot/.git/worktrees/slot-1 +``` + +Because `/home/boki/repos/stock-bot/.git/worktrees/slot-1` lies outside the agent sandbox boundary, `git` commands inside the sandbox exit `128` as expected: + +| Command | Exit Code | Output (verbatim) | +| --- | --- | --- | +| `git rev-parse HEAD` | `128` | `fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | +| `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 HEAD` | `128` | `fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | + +- **Unsandboxed provenance (confirmed by producer in the plan worktree):** `master` is at `56b73b7e` and `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 master` exited `0` (confirming accepted M1 commit `d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1` is an ancestor of `master`). +- No exit `0` was fabricated for sandbox `git` commands; Studio's unsandboxed runner operates with full `.git` access. + +--- + +## 2. Sandbox-Runnable Gates (Sequential) + +All seven sandbox-runnable gates exited `0` with zero failures and zero warnings: + +| Gate Command | Exit Code | Result / Counts | +| --- | --- | --- | +| `bun run typecheck` (`tsc --project tsconfig.check.json --noEmit`) | `0` | PASS (0 errors) | +| `bun run test:contracts` (`tsc --project tsconfig.contracts.json --noEmit`) | `0` | PASS (0 errors) | +| `bun run lint:check` (`eslint apps/stock libs tools test --ext .ts,.tsx --max-warnings 0`) | `0` | PASS (0 errors, 0 warnings) | +| `bun run test:utils` (`bun test libs/utils/test/ libs/core/handlers/test/base-handler-http.test.ts`) | `0` | PASS — 32 pass, 0 fail (59 `expect()` calls, 3 files) | +| `bun run test:calculations` (`bun test libs/calculations/test/`) | `0` | PASS — 144 pass, 0 fail (76,602 `expect()` calls, 12 files) | +| `CARGO_BUILD_JOBS=2 bun run test:native` (`cargo test -p engine --lib --offline && cargo test -p curate-etl --offline`) | `0` | PASS — 1,078 passed, 0 failed, 4 ignored across 49 test binaries/suites | +| `CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | `0` | PASS — 732 passed, 0 failed, 4 ignored across 2 lib suites | + +--- + +## 3. Full Unfiltered Sandbox `bun test` Triage + +- **Command:** `bun test` (complete unfiltered stdout/stderr captured and inspected from start to finish) +- **Exit Code:** `1` +- **Totals:** `3,498 pass`, `125 skip`, `40 fail`, `3 errors`, `885,783 expect() calls` across `282 files` (`57.36s`) +- **Real failures:** **`0`** (all `40` failures and `3` `beforeAll` unhandled errors are expected sandbox-boundary failures; zero tests were skipped, mocked, or deleted) + +### Failure Classification Table (10 files, 40 failures, 3 unhandled `beforeAll` errors) + +| Test File | Fails (+ Unhandled Errors) | Exact Error Text | Classification | +| --- | --- | --- | --- | +| `test/integration/retained-strategy-worker.test.ts` | 15 (+1 `beforeAll` error) | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | +| `test/integration/chronological-validation-native.test.ts` | 2 | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | +| `test/integration/reproduction-comparison.test.ts` | 4 (+1 `beforeAll` error) | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | +| `test/postgres/security-master-run.test.ts` | 1 | `error: Dedicated stock_bot_safety database required` (`test/postgres/security-master-run.test.ts:37:11`) | **(a) Expected sandbox-only** — requires `PIPELINE_TEST_DATABASE_URL` (`/home/boki/.studio/test-env/stock-bot.env`) & host PostgreSQL `127.0.0.1:5432` | +| `test/postgres/security-master-export-curate-inputs.test.ts` | 1 | `error: Dedicated stock_bot_safety database required` (`test/postgres/security-master-export-curate-inputs.test.ts:35:11`) | **(a) Expected sandbox-only** — requires `PIPELINE_TEST_DATABASE_URL` (`/home/boki/.studio/test-env/stock-bot.env`) & host PostgreSQL `127.0.0.1:5432` | +| `scripts/test/strategy-packaging.test.ts` | 10 (+1 `beforeAll` error) | `error: Cannot read packaging source identity: git rev-parse failed` (`scripts/package-builtin-strategies.ts:42:11`) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | +| `scripts/test/benchmark-sma.test.ts` | 1 | Child process exit `1`: `git failed: fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | +| `scripts/test/benchmark-replay.test.ts` | 2 | Child process exit `1`: `git failed: fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | +| `scripts/test/benchmark-research.test.ts` | 1 | Child process exit `1`: `git failed: fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | +| `scripts/test/audit-secrets-repo.test.ts` | 3 | Child process exit `1`: `Cannot inspect tracked files for the secret audit` (`git ls-files` blocked by worktree `.git` outside sandbox) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | + +### Authoritative Unsandboxed Gate (Studio Runner) +Per `studio.config.json`: +- **Build:** `bun run build` +- **Test:** `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` + +Studio executes both commands outside the sandbox immediately after handoff, covering the 38 `.git`-dependent tests, the 2 `stock_bot_safety*` PostgreSQL tests, and the skipped PostgreSQL suites that activate under `/home/boki/.studio/test-env/stock-bot.env`. The Rust half (`CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline`) already passed inside the sandbox (`732 passed, 0 failed, 4 ignored`). + +--- + +## 4. Read-Only M2 Planning Facts (No Config or Code Changes Made) + +1. **`@modelcontextprotocol/sdk` availability and agent network allowlist:** + - `@modelcontextprotocol/sdk` is **not present** in `bun.lock` or any `package.json` (`package.json`, `apps/`, `libs/`, `tools/`). + - `studio.config.json` (`agentExecution.programmer.networkDomains` and `agentExecution.qa.networkDomains`, lines 3–19) allows only `crates.io`, `index.crates.io`, and `static.crates.io` (no npm registry access in agent sessions). Any M2 MCP server task that needs `@modelcontextprotocol/sdk` will either need a lightweight dependency-free JSON-RPC 2.0 / MCP stdio+SSE implementation or an explicit dependency install / networkDomain decision before implementation. +2. **Python test suite (`python/tests/test_stockbot_sdk.py`) coverage:** + - `python/tests/test_stockbot_sdk.py` exists under `python/tests/`, but **is not invoked** by any script in `package.json`, `scripts/check.ts`, or `studio.config.json` (`test.command`). +3. **`studio.config.json` `docs.*` path mismatch (left untouched):** + - `docs/` does not exist at the repository root. + - `studio.config.json` lines 43–55 still point `docs.index`, `docs.plan`, `docs.milestones`, `docs.dataContracts`, `docs.validation`, `docs.dataPipeline`, and `docs.servers` at `docs/...` paths, whereas the actual milestone and architecture documents live under `design/` (e.g., `design/MILESTONES.md` lines 83–103 contain the M2 checklist and exit criteria). `studio.config.json` was intentionally left untouched in this task. From 136cecf7f3971280baf9b9723eb95b0f35344e4e Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 15:11:43 -0500 Subject: [PATCH 02/21] =?UTF-8?q?T-128:=20M2.0=20=E2=80=94=20Baseline=20ga?= =?UTF-8?q?te=20rerun=20on=20master=20(56b73b7e,=20contains=20M1=20d52aa20?= =?UTF-8?q?b)=20before=20M2=20implementation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- design/m2-baseline-report.md | 125 ++++++++++++++++++++++++++++++----- 1 file changed, 109 insertions(+), 16 deletions(-) diff --git a/design/m2-baseline-report.md b/design/m2-baseline-report.md index 79550824..4bbefde1 100644 --- a/design/m2-baseline-report.md +++ b/design/m2-baseline-report.md @@ -1,29 +1,53 @@ # Milestone M2 Baseline Verification Report (T-128 / M2.0) -**Verdict:** **GREEN (sandbox gates + full `bun test` triage clean; 0 real failures)** — pending Studio's authoritative unsandboxed `bun run build` and `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` handoff run for the 40 sandbox-boundary failures (38 `.git` worktree metadata + 2 PostgreSQL `stock_bot_safety*` env). +**Verdict:** **GREEN — Baseline verified for M2 start (0 real failures).** All 7 sandbox-runnable gates passed on `master` (`56b73b7e663d293079ab7bac264950dfa7a68b00`), all 40 sandbox `bun test` failures are verified sandbox-boundary errors (38 worktree `.git` metadata + 2 `stock_bot_safety*` PostgreSQL env), and Studio's authoritative unsandboxed runs — **Build `#1027`** (`bun run build`) and **Test `#1028`** (`bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline`) — passed (exit `0`) on reviewed commit `904def37e2e9cff5dce538c3d1f61ffca3594e9d`. --- -## 1. Repository Provenance +## 1. Repository Provenance & Revision Mapping + +### Revisions Checked + +| Role | Full SHA | Notes | +| --- | --- | --- | +| Accepted M1 commit | `d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1` | Director-accepted M1 baseline | +| `master` baseline | `56b73b7e663d293079ab7bac264950dfa7a68b00` | Base revision where all sandbox gates and full sandbox `bun test` ran | +| Reviewed report commit (`feat/m2-baseline-gates`) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Adds only `design/m2-baseline-report.md` on top of `56b73b7e663d293079ab7bac264950dfa7a68b00`; revision tested by Studio Build `#1027` and Test `#1028` | + +### Unsandboxed Ancestry Checks (Confirmed) + +| Check | Target Revision | Exit Code | Confirmed By | +| --- | --- | --- | --- | +| `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 56b73b7e663d293079ab7bac264950dfa7a68b00` | `master` (`56b73b7e663d293079ab7bac264950dfa7a68b00`) | `0` | Producer (plan worktree) and Reviewer | +| `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Reviewed HEAD (`904def37e2e9cff5dce538c3d1f61ffca3594e9d`) | `0` | Reviewer | + +### Sandbox `git` Boundary Errors (Preserved Verbatim) Worktree `.git` file content: ```text gitdir: /home/boki/repos/stock-bot/.git/worktrees/slot-1 ``` -Because `/home/boki/repos/stock-bot/.git/worktrees/slot-1` lies outside the agent sandbox boundary, `git` commands inside the sandbox exit `128` as expected: +Because `/home/boki/repos/stock-bot/.git/worktrees/slot-1` lies outside the agent sandbox boundary, `git` commands inside the sandbox exit `128` as expected (no exit `0` was fabricated inside the sandbox): -| Command | Exit Code | Output (verbatim) | +| Command (inside sandbox) | Exit Code | Output (verbatim) | | --- | --- | --- | | `git rev-parse HEAD` | `128` | `fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | | `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 HEAD` | `128` | `fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | -- **Unsandboxed provenance (confirmed by producer in the plan worktree):** `master` is at `56b73b7e` and `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 master` exited `0` (confirming accepted M1 commit `d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1` is an ancestor of `master`). -- No exit `0` was fabricated for sandbox `git` commands; Studio's unsandboxed runner operates with full `.git` access. +### Which Checks Ran on Which Revision + +| Verification Run | Revision | Environment | Outcome | +| --- | --- | --- | --- | +| 7 sequential sandbox-runnable gates (§2) | `56b73b7e663d293079ab7bac264950dfa7a68b00` | Agent sandbox | PASS (7/7 exit `0`) | +| Full unfiltered `bun test` triage (§3) | `56b73b7e663d293079ab7bac264950dfa7a68b00` | Agent sandbox | 3,498 pass, 125 skip, 40 fail (all sandbox-only), 0 real failures | +| Studio Build `#1027` (`bun run build`) (§4) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Studio unsandboxed | PASS (exit `0`) | +| Studio Test `#1028` (`bun --env-file=... test && cargo test ...`) (§4) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Studio unsandboxed | PASS (exit `0`) | +| Targeted 10-file sandbox re-run for individual failure names (§3) | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | Agent sandbox | Confirmed exact same 40 failures across the 10 files | --- -## 2. Sandbox-Runnable Gates (Sequential) +## 2. Sandbox-Runnable Gates (Sequential — Revision `56b73b7e663d293079ab7bac264950dfa7a68b00`) All seven sandbox-runnable gates exited `0` with zero failures and zero warnings: @@ -39,14 +63,15 @@ All seven sandbox-runnable gates exited `0` with zero failures and zero warnings --- -## 3. Full Unfiltered Sandbox `bun test` Triage +## 3. Full Unfiltered Sandbox `bun test` Triage (Revision `56b73b7e663d293079ab7bac264950dfa7a68b00`) - **Command:** `bun test` (complete unfiltered stdout/stderr captured and inspected from start to finish) - **Exit Code:** `1` - **Totals:** `3,498 pass`, `125 skip`, `40 fail`, `3 errors`, `885,783 expect() calls` across `282 files` (`57.36s`) -- **Real failures:** **`0`** (all `40` failures and `3` `beforeAll` unhandled errors are expected sandbox-boundary failures; zero tests were skipped, mocked, or deleted) +- **Skips note:** The `125 skip` count was reported by Bun from pre-existing conditional skips in the repository (e.g., suites that self-skip when PostgreSQL / service environment variables are absent in the sandbox). This task introduced **zero** test skips, mocks, or deletions. +- **Real failures:** **`0`** (all `40` failures and `3` `beforeAll` unhandled errors are expected sandbox-boundary failures). -### Failure Classification Table (10 files, 40 failures, 3 unhandled `beforeAll` errors) +### Failure Classification Summary (10 files, 40 failures, 3 unhandled `beforeAll` errors) | Test File | Fails (+ Unhandled Errors) | Exact Error Text | Classification | | --- | --- | --- | --- | @@ -61,16 +86,84 @@ All seven sandbox-runnable gates exited `0` with zero failures and zero warnings | `scripts/test/benchmark-research.test.ts` | 1 | Child process exit `1`: `git failed: fatal: gitfile does not point to a valid repository: /home/boki/.studio/worktrees/stock-bot/slot-1/.git` | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | | `scripts/test/audit-secrets-repo.test.ts` | 3 | Child process exit `1`: `Cannot inspect tracked files for the secret audit` (`git ls-files` blocked by worktree `.git` outside sandbox) | **(a) Expected sandbox-only** — worktree `.git` metadata outside sandbox | -### Authoritative Unsandboxed Gate (Studio Runner) -Per `studio.config.json`: -- **Build:** `bun run build` -- **Test:** `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` +### Individual Failing Test Names (All 40 Accounted For) -Studio executes both commands outside the sandbox immediately after handoff, covering the 38 `.git`-dependent tests, the 2 `stock_bot_safety*` PostgreSQL tests, and the skipped PostgreSQL suites that activate under `/home/boki/.studio/test-env/stock-bot.env`. The Rust half (`CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline`) already passed inside the sandbox (`732 passed, 0 failed, 4 ignored`). +1. **`test/integration/retained-strategy-worker.test.ts`** (15 fails; `beforeAll` failed on `git rev-parse`): + - `retained canonical strategy worker > sma_crossover exact packaged bytes match the native report and repeat identically` + - `retained canonical strategy worker > mean_reversion exact packaged bytes match the native report and repeat identically` + - `retained canonical strategy worker > a retained version executes its own bytes when the current constructor differs` + - `retained canonical strategy worker > build and retained hashes are checked before module or factory side effects` + - `retained canonical strategy worker > eligible exact single-series data and ownership are required before bundle import` + - `retained canonical strategy worker > factory identity, missing exports, thrown decisions and no-result exits fail closed` + - `retained canonical strategy worker > capture detaches all admitted inputs before the caller can mutate them` + - `retained canonical strategy worker > result parser rejects false identity, policy and statistical claims` + - `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.artifactHash = "f".repeat(64)` + - `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.build.workerSha256 = "f".repeat(64)` + - `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.financial.policy.matching.risk.feeRate = "0"` + - `retained canonical strategy worker > typed worker rejects a malformed completed envelope: result.analytics.metrics.exposureTime = null` + - `retained canonical strategy worker > typed retained results wait for successful child exit` + - `retained canonical strategy worker > alternate and source workers cannot claim the bundled worker identity` + - `retained canonical strategy worker > hard cancellation discards retained execution and the worker can be reused` + +2. **`test/integration/chronological-validation-native.test.ts`** (2 fails; `git rev-parse` in strategy packaging): + - `chronological preflight slices on the authoritative native engine > each phase independently starts with initial cash, empty positions and fresh state; warmup cannot trade` + - `chronological preflight slices on the authoritative native engine > changing only the test suffix cannot change training or validation inputs, native economics or decisions` + +3. **`test/integration/reproduction-comparison.test.ts`** (4 fails; `beforeAll` failed on `git rev-parse`): + - `economic_hash_parity: two actual replays ignore only admission identities and wall-clock metadata` + - `economic hash retains fees, ordered fills, decision ownership, risk, nulls and statistical facts` + - `economic hash preserves actual market-session identities and execution policy` + - `economic hash rejects mixed result/request/session identities rather than hiding them` + +4. **`test/postgres/security-master-run.test.ts`** (1 fail; requires `PIPELINE_TEST_DATABASE_URL` pointing to `stock_bot_safety*`): + - `composeSecurityMasterRun -> persistSecurityMaster PostgreSQL integration > persists FB vs FB-ETF distinct listing_ids, SIVB -> SIVBQ continuity, Pass 4 conflicts (including shared left endpoint), and is idempotent on re-run` + +5. **`test/postgres/security-master-export-curate-inputs.test.ts`** (1 fail; requires `PIPELINE_TEST_DATABASE_URL` pointing to `stock_bot_safety*`): + - `exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*) > exports exact TSV bytes read-only and matches across chunkSize=1 and chunkSize=5000` + +6. **`scripts/test/strategy-packaging.test.ts`** (10 fails; `beforeAll` failed on `git rev-parse`): + - `offline reviewed strategy packaging > repeat packaging retains byte-identical self-contained bundles and lock bytes` + - `offline reviewed strategy packaging > source revision, dirty state, compiler and public descriptor identity are truthful` + - `offline reviewed strategy packaging > isolated bundles require no workspace, installed packages, native engine or service runtime` + - `offline reviewed strategy packaging > residual imports and require references reject instead of retaining incomplete bundles` + - `offline reviewed strategy packaging > packaging inspects generated text without importing or executing it` + - `offline reviewed strategy packaging > a bundle missing its declared factory cannot be published as a valid built-in package` + - `offline reviewed strategy packaging > sma_crossover: source and packaged decisions/checkpoints agree through entry, exit and restore` + - `offline reviewed strategy packaging > mean_reversion: source and packaged decisions/checkpoints agree through entry, exit and restore` + - `offline reviewed strategy packaging > packaged factories retain strict parameter validation and canonical aliases` + - `offline reviewed strategy packaging > CLI writes the retained package envelope and rejects unsupported options` + +7. **`scripts/test/benchmark-sma.test.ts`** (1 fail; child `git` blocked by worktree `.git`): + - `sma_recorded_decision_parity verifies six shapes and actual financial/diagnostic identities` + +8. **`scripts/test/benchmark-replay.test.ts`** (2 fails; child `git` blocked by worktree `.git`): + - `all tiny replay profiles pin financial expectations and distinct strategy identities` + - `canonical self-test measures real sessions and verifies repeated full-result hashes` + +9. **`scripts/test/benchmark-research.test.ts`** (1 fail; child `git` blocked by worktree `.git`): + - `existing-path research benchmark > tiny native self-test records honest phases and pinned identities without timing thresholds` + +10. **`scripts/test/audit-secrets-repo.test.ts`** (3 fails; `git ls-files` blocked by worktree `.git`): + - `audit:secrets passes on the real repository` + - `real-repository audit ignores inherited GIT_DIR, GIT_WORK_TREE and GIT_INDEX_FILE` + - `audit:secrets passes on the real repository when run from scripts subdirectory` --- -## 4. Read-Only M2 Planning Facts (No Config or Code Changes Made) +## 4. Authoritative Unsandboxed Gate (Studio Runner — Revision `904def37e2e9cff5dce538c3d1f61ffca3594e9d`) + +Per `studio.config.json`, Studio executed both authoritative unsandboxed commands against reviewed commit `904def37e2e9cff5dce538c3d1f61ffca3594e9d` (which has identical code and tests to `master` `56b73b7e663d293079ab7bac264950dfa7a68b00`, differing only by adding `design/m2-baseline-report.md`): + +| Studio Run | Revision | Exact Command | Exit Code | Result / Counts | +| --- | --- | --- | --- | --- | +| **Build `#1027`** | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | `bun run build` | `0` | **PASS** (reported passed by Studio; per-package counts not exposed in the Studio run summary) | +| **Test `#1028`** | `904def37e2e9cff5dce538c3d1f61ffca3594e9d` | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | `0` | **PASS** (reported passed by Studio, exercising all 38 `.git`-dependent tests, the 2 `stock_bot_safety*` PostgreSQL tests, and the Rust workspace lib tests; per-test Bun counts are not exposed in the Studio run summary, while the Rust half verified `732 passed, 0 failed, 4 ignored` on the same tree) | + +This closes the authoritative gate for T-128: every failure observed in the sandbox (`40/40`) passed in Studio's unsandboxed test run `#1028`, and `bun run build` passed in Studio build `#1027`. Updating this report triggers a fresh Studio build and test run on the updated doc-only commit. + +--- + +## 5. Read-Only M2 Planning Facts (No Config or Code Changes Made) 1. **`@modelcontextprotocol/sdk` availability and agent network allowlist:** - `@modelcontextprotocol/sdk` is **not present** in `bun.lock` or any `package.json` (`package.json`, `apps/`, `libs/`, `tools/`). From 0bea9a6f1d4887991770df501c613975e257e3e1 Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 15:18:01 -0500 Subject: [PATCH 03/21] T-128: tests --- test/unit/m2-baseline-report-doc.test.ts | 178 +++++++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 test/unit/m2-baseline-report-doc.test.ts diff --git a/test/unit/m2-baseline-report-doc.test.ts b/test/unit/m2-baseline-report-doc.test.ts new file mode 100644 index 00000000..ca0504ba --- /dev/null +++ b/test/unit/m2-baseline-report-doc.test.ts @@ -0,0 +1,178 @@ +import { describe, expect, test } from 'bun:test'; +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +// Guards the T-128 M2.0 baseline report (design/m2-baseline-report.md) against silent drift: it is +// the gate evidence the director reads before M2 starts, so its provenance SHAs, gate commands, +// exit codes and failure accounting must stay complete and internally consistent. Live repository +// facts it records (bun.lock contents, studio.config.json paths) are deliberately not pinned here: +// they are a point-in-time snapshot that M2 work is expected to change. +const repoRoot = join(import.meta.dir, '..', '..'); +const reportPath = join(repoRoot, 'design/m2-baseline-report.md'); +const doc = readFileSync(reportPath, 'utf8'); + +const M1_SHA = 'd52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1'; +const MASTER_SHA = '56b73b7e663d293079ab7bac264950dfa7a68b00'; +const STUDIO_TEST_COMMAND = + 'bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline'; + +function section(title: RegExp): string { + const lines = doc.split('\n'); + const start = lines.findIndex(line => /^## /.test(line) && title.test(line)); + expect(start).toBeGreaterThan(-1); + const rest = lines.slice(start + 1); + const end = rest.findIndex(line => /^## /.test(line)); + return rest.slice(0, end === -1 ? undefined : end).join('\n'); +} + +function subsection(body: string, title: RegExp): string { + const lines = body.split('\n'); + const start = lines.findIndex(line => /^### /.test(line) && title.test(line)); + expect(start).toBeGreaterThan(-1); + const rest = lines.slice(start + 1); + const end = rest.findIndex(line => /^### /.test(line)); + return rest.slice(0, end === -1 ? undefined : end).join('\n'); +} + +function tableRows(body: string): string[][] { + return body + .split('\n') + .filter(line => line.startsWith('|') && !/^\|\s*-/.test(line)) + .map(line => line.split('|').slice(1, -1).map(cell => cell.trim())) + .slice(1); // drop header row +} + +describe('M2 baseline verification report (T-128)', () => { + test('exists and leads with an explicit GREEN verdict and zero real failures', () => { + expect(existsSync(reportPath)).toBe(true); + const verdictLine = doc.split('\n').find(line => line.startsWith('**Verdict:**')); + expect(verdictLine).toBeDefined(); + expect(verdictLine).toContain('GREEN'); + expect(verdictLine).toContain('0 real failures'); + }); + + test('provenance records full M1 and master SHAs and the ancestry check exiting 0', () => { + const provenance = section(/^## 1\./); + expect(provenance).toContain(M1_SHA); + expect(provenance).toContain(MASTER_SHA); + const ancestry = tableRows(subsection(provenance, /Ancestry/)); + expect(ancestry.length).toBeGreaterThan(0); + for (const [command, , exitCode] of ancestry) { + expect(command).toContain(`git merge-base --is-ancestor ${M1_SHA} `); + expect(exitCode).toBe('`0`'); + } + expect(ancestry.some(([command]) => command!.includes(MASTER_SHA))).toBe(true); + }); + + test('sandbox git errors are preserved as exit 128, not reported as passes', () => { + const rows = tableRows(subsection(section(/^## 1\./), /Sandbox `git`/)); + expect(rows.map(r => r[0])).toEqual([ + '`git rev-parse HEAD`', + `\`git merge-base --is-ancestor ${M1_SHA} HEAD\``, + ]); + for (const row of rows) { + expect(row[1]).toBe('`128`'); + expect(row[2]).toContain('fatal:'); + } + }); + + test('every AGENTS.md sandbox gate is listed with exit code 0 and zero failures', () => { + const rows = tableRows(section(/^## 2\./)); + const gates = [ + 'bun run typecheck', + 'bun run test:contracts', + 'bun run lint:check', + 'CARGO_BUILD_JOBS=2 bun run test:native', + 'bun run test:utils', + 'bun run test:calculations', + 'CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline', + ]; + for (const gate of gates) { + const row = rows.find(cells => cells[0]!.startsWith(`\`${gate}\``)); + expect(row, gate).toBeDefined(); + expect(row![1]).toBe('`0`'); + expect(row![2]).toMatch(/^PASS/); + expect(row![2]).toMatch(/0 (errors|fail|failed)/); + } + }); + + test('sandbox failure classification sums to the reported 40 failures, all sandbox-only', () => { + const triage = section(/^## 3\./); + expect(triage).toMatch(/`40 fail`/); + expect(triage).toMatch(/\*\*Real failures:\*\* \*\*`0`\*\*/); + const rows = tableRows(subsection(triage, /Failure Classification Summary/)); + expect(rows).toHaveLength(10); + + let total = 0; + let gitBoundary = 0; + let postgresBoundary = 0; + for (const [file, fails, errorText, classification] of rows) { + const path = file!.replace(/`/g, ''); + expect(existsSync(join(repoRoot, path)), path).toBe(true); + const count = Number(fails!.match(/^(\d+)/)![1]); + total += count; + expect(classification).toContain('(a) Expected sandbox-only'); + if (/stock_bot_safety/.test(errorText!)) { + expect(path.startsWith('test/postgres/')).toBe(true); + postgresBoundary += count; + } else { + expect(errorText).toMatch(/git|Cannot inspect tracked files/); + gitBoundary += count; + } + } + expect(total).toBe(40); + expect(gitBoundary).toBe(38); + expect(postgresBoundary).toBe(2); + }); + + test('individual failing test names match the per-file counts in the classification table', () => { + const triage = section(/^## 3\./); + const summary = new Map( + tableRows(subsection(triage, /Failure Classification Summary/)).map(([file, fails]) => [ + file!.replace(/`/g, ''), + Number(fails!.match(/^(\d+)/)![1]), + ]), + ); + const lines = subsection(triage, /Individual Failing Test Names/).split('\n'); + const listed = new Map(); + let current: string | undefined; + for (const line of lines) { + const header = line.match(/^\d+\. \*\*`([^`]+)`\*\* \((\d+) fails?;/); + if (header) { + current = header[1]!; + expect(Number(header[2])).toBe(summary.get(current)!); + listed.set(current, []); + continue; + } + const name = line.match(/^\s+- `(.+)`$/); + if (name && current) {listed.get(current)!.push(name[1]!);} + } + expect([...listed.keys()].sort()).toEqual([...summary.keys()].sort()); + for (const [file, names] of listed) { + expect(names.length, file).toBe(summary.get(file)!); + expect(new Set(names).size, file).toBe(names.length); + } + }); + + test("Studio's authoritative build and test commands are recorded verbatim with exit 0", () => { + const rows = tableRows(section(/^## 4\./)); + const build = rows.find(r => r[0]!.includes('Build')); + const tests = rows.find(r => r[0]!.includes('Test')); + expect(build?.[2]).toBe('`bun run build`'); + expect(build?.[3]).toBe('`0`'); + expect(tests?.[2]).toBe(`\`${STUDIO_TEST_COMMAND}\``); + expect(tests?.[3]).toBe('`0`'); + for (const row of [build!, tests!]) {expect(row[4]).toContain('PASS');} + }); + + test('records all three M2 planning facts', () => { + const facts = section(/^## 5\./); + expect(facts).toContain('`@modelcontextprotocol/sdk` is **not present** in `bun.lock`'); + expect(facts).toContain('`crates.io`, `index.crates.io`, and `static.crates.io`'); + expect(facts).toContain('`python/tests/test_stockbot_sdk.py`'); + expect(facts).toContain('**is not invoked**'); + expect(facts).toContain('`docs/` does not exist'); + expect(facts).toContain('`design/MILESTONES.md` lines 83–103'); + expect(facts).toContain('left untouched'); + }); +}); From 73ac978bb3a8a7a5a38c361b432693973eeae5a2 Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 15:34:20 -0500 Subject: [PATCH 04/21] =?UTF-8?q?T-129:=20M2.1a=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20core:=20dependency-free=20JSON-RPC/MCP=20stdio=20server=20+?= =?UTF-8?q?=20tool=20registry=20+=20vault-fenced=20`query=5Fdata`=20in=20`?= =?UTF-8?q?libs/research/src/mcp/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 21 + libs/research/package.json | 1 + libs/research/src/mcp/index.ts | 4 + libs/research/src/mcp/protocol.ts | 245 ++++++++++ libs/research/src/mcp/server.ts | 540 ++++++++++++++++++++++ libs/research/src/mcp/stdio.ts | 147 ++++++ libs/research/src/mcp/tools/query-data.ts | 307 ++++++++++++ libs/research/test/mcp-protocol.test.ts | 324 +++++++++++++ libs/research/test/mcp-query-data.test.ts | 482 +++++++++++++++++++ libs/research/test/mcp-stdio.test.ts | 195 ++++++++ 10 files changed, 2266 insertions(+) create mode 100644 libs/research/src/mcp/index.ts create mode 100644 libs/research/src/mcp/protocol.ts create mode 100644 libs/research/src/mcp/server.ts create mode 100644 libs/research/src/mcp/stdio.ts create mode 100644 libs/research/src/mcp/tools/query-data.ts create mode 100644 libs/research/test/mcp-protocol.test.ts create mode 100644 libs/research/test/mcp-query-data.test.ts create mode 100644 libs/research/test/mcp-stdio.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index 919c2b6d..fd8e76ad 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -196,3 +196,24 @@ Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3 - **Command:** `bun run libs/research/scripts/benchmark-event-panel.ts` - **Observed (Bun 1.2.16):** `elapsedMs = 731.06 ms`, `barsPerSec = 20,682,279 bars/s`, `eventsPerSec = 328,290 events/s` (`5,020` pre-Vault sessions, `240,000` anchored events, `20` Vault-excluded dates, pinned checksum `01b356d3`) + +## MCP Copilot Core + +Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported via the `@stock-bot/research/mcp` subpath (`libs/research/src/mcp/index.ts`). It is intentionally **not** re-exported from the browser-safe `@stock-bot/research` default entrypoint. + +### Registering Tools & Running Stdio Framing + +- **`defineMcpTool({ name, description, inputSchema, jsonSchema?, handler })`** — Registers a strict Zod-validated tool, converts `inputSchema` into a strict JSON Schema (`additionalProperties: false`, or uses an explicit `jsonSchema` override), returns `isError: true` on invalid arguments without calling the handler, and sanitizes thrown handler errors so stack traces never leak. +- **`createMcpServer({ name, version, tools })`** — Transport-agnostic JSON-RPC 2.0 dispatcher implementing `initialize`, `notifications/initialized`, `ping`, `tools/list`, and `tools/call` via `handleMessage(raw: string): Promise`. Rejects duplicate tool names at creation time. +- **`runStdioServer(server, { input?, output?, maxLineBytes? })`** — Newline-delimited JSON-RPC stdio transport over injectable streams (defaulting to `process.stdin` / `process.stdout`), with streaming UTF-8 decoding across arbitrary chunk boundaries, strict sequential dispatch in arrival order, `maxLineBytes` frame-size protection (default `4 MiB`), and zero non-protocol bytes on `output`. + +### `query_data` Tool (Vault-Fenced) + +- **`createQueryDataTool({ store, vaultContext })`** — Wraps an injected `MarketDataStore` for explicit `listingIds` (max `QUERY_DATA_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref, with bounded output rows (`QUERY_DATA_DEFAULT_LIMIT = 500`, hard max `QUERY_DATA_MAX_LIMIT = 5_000`). +- Always enforces `scope: 'vault_fenced'` via `applyVaultFence` before any store call, omits `scope` / `vault_evaluation_only` from the strict schema (rejecting unknown keys with zero store calls), drops any post-cutoff row (`ts >= vaultCutoffTs` or `knownAt >= vaultCutoffTs`) as defense in depth, and maps `VaultHoldoutFenceError`, `VaultScopeNotAuthorizedError`, `MarketDataStoreValidationError`, `MarketDataStoreNotImplementedError`, and `AdjFactorsSnapshotError` to `isError: true` responses naming the error class. + +### Remaining M2 MCP Items (Later Tasks) + +- Additional research tools: `search_symbols`, `analyze_signal`, `event_study`, `file_finding`, and `read_knowledge`. +- SSE/HTTP transport wrapper in `apps/stock/web-api`. +- Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters. diff --git a/libs/research/package.json b/libs/research/package.json index 89c29140..fb865726 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -13,6 +13,7 @@ "./event-panel": "./src/event-panel.ts", "./market-data-store": "./src/market-data-store.ts", "./market-data-store-duckdb": "./src/market-data-store-duckdb.ts", + "./mcp": "./src/mcp/index.ts", "./results": "./src/results.ts", "./signal-panel": "./src/signal-panel.ts", "./signal-study": "./src/signal-study.ts", diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts new file mode 100644 index 00000000..8b021dbe --- /dev/null +++ b/libs/research/src/mcp/index.ts @@ -0,0 +1,4 @@ +export * from './protocol'; +export * from './server'; +export * from './stdio'; +export * from './tools/query-data'; diff --git a/libs/research/src/mcp/protocol.ts b/libs/research/src/mcp/protocol.ts new file mode 100644 index 00000000..f3d66d8c --- /dev/null +++ b/libs/research/src/mcp/protocol.ts @@ -0,0 +1,245 @@ +import { z } from 'zod'; + +/** Supported Model Context Protocol revision. */ +export const MCP_PROTOCOL_VERSION = '2025-03-26'; + +/** Standard JSON-RPC 2.0 error codes. */ +export const JSON_RPC_ERROR_CODES = { + PARSE_ERROR: -32700, + INVALID_REQUEST: -32600, + METHOD_NOT_FOUND: -32601, + INVALID_PARAMS: -32602, + INTERNAL_ERROR: -32603, +} as const; + +export type JsonRpcErrorCode = (typeof JSON_RPC_ERROR_CODES)[keyof typeof JSON_RPC_ERROR_CODES]; + +/** Valid JSON-RPC 2.0 request identifier (string or finite number). */ +export const jsonRpcIdSchema = z.union([z.string(), z.number().finite()]); +export type JsonRpcId = z.infer; + +/** Strict JSON-RPC 2.0 request envelope (must carry a valid `id`). */ +export const jsonRpcRequestSchema = z + .object({ + jsonrpc: z.literal('2.0'), + id: jsonRpcIdSchema, + method: z.string().min(1), + params: z.unknown().optional(), + }) + .strict(); + +export type JsonRpcRequest = z.infer; + +/** Strict JSON-RPC 2.0 notification envelope (must NOT carry an `id`). */ +export const jsonRpcNotificationSchema = z + .object({ + jsonrpc: z.literal('2.0'), + method: z.string().min(1), + params: z.unknown().optional(), + }) + .strict(); + +export type JsonRpcNotification = z.infer; + +export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification; + +export interface JsonRpcSuccessResponse { + readonly jsonrpc: '2.0'; + readonly id: JsonRpcId; + readonly result: unknown; +} + +export interface JsonRpcErrorObject { + readonly code: number; + readonly message: string; + readonly data?: unknown; +} + +export interface JsonRpcErrorResponse { + readonly jsonrpc: '2.0'; + readonly id: JsonRpcId | null; + readonly error: JsonRpcErrorObject; +} + +export type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse; + +/** MCP text content block returned inside `tools/call` results. */ +export interface McpTextContent { + readonly type: 'text'; + readonly text: string; +} + +/** MCP `tools/call` result envelope. */ +export interface McpToolCallResult { + readonly content: readonly McpTextContent[]; + readonly isError?: boolean; +} + +/** Minimal JSON Schema Draft 7/2020-12 property definition for MCP tool inputs. */ +export interface JsonSchemaProperty { + readonly type?: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null'; + readonly description?: string; + readonly enum?: readonly (string | number | boolean | null)[]; + readonly const?: string | number | boolean | null; + readonly minimum?: number; + readonly maximum?: number; + readonly exclusiveMinimum?: number; + readonly exclusiveMaximum?: number; + readonly minLength?: number; + readonly maxLength?: number; + readonly minItems?: number; + readonly maxItems?: number; + readonly items?: JsonSchemaProperty; + readonly properties?: Readonly>; + readonly required?: readonly string[]; + readonly additionalProperties?: boolean; + readonly anyOf?: readonly JsonSchemaProperty[]; + readonly default?: unknown; +} + +/** Strict top-level JSON Schema object emitted by `tools/list`. */ +export interface JsonSchemaObject { + readonly type: 'object'; + readonly properties: Readonly>; + readonly required?: readonly string[]; + readonly additionalProperties: false; + readonly description?: string; +} + +/** Tool metadata returned in `tools/list`. */ +export interface McpToolDescriptor { + readonly name: string; + readonly description: string; + readonly inputSchema: JsonSchemaObject; +} + +/** Strict MCP `initialize` params schema. */ +export const mcpInitializeParamsSchema = z + .object({ + protocolVersion: z.string().min(1).optional(), + capabilities: z.record(z.unknown()).optional(), + clientInfo: z + .object({ + name: z.string().min(1), + version: z.string().min(1), + }) + .strict() + .optional(), + }) + .strict(); + +/** Strict MCP `notifications/initialized` params schema. */ +export const mcpInitializedNotificationParamsSchema = z.object({}).strict(); + +/** Strict MCP `ping` params schema. */ +export const mcpPingParamsSchema = z.object({}).strict(); + +/** Strict MCP `tools/list` params schema. */ +export const mcpToolsListParamsSchema = z + .object({ + cursor: z.string().min(1).optional(), + }) + .strict(); + +/** Strict MCP `tools/call` params schema. */ +export const mcpToolsCallParamsSchema = z + .object({ + name: z.string().min(1), + arguments: z.record(z.unknown()).optional(), + }) + .strict(); + +export type ParsedJsonRpcMessage = + | { readonly ok: true; readonly kind: 'request'; readonly message: JsonRpcRequest } + | { readonly ok: true; readonly kind: 'notification'; readonly message: JsonRpcNotification } + | { + readonly ok: false; + readonly errorCode: JsonRpcErrorCode; + readonly message: string; + }; + +/** + * Parses a raw JSON-RPC 2.0 message string. + * + * - Malformed JSON returns `PARSE_ERROR` (-32700). + * - Non-object payloads or invalid envelopes (including an explicit invalid `id` + * such as `id: null` or `id: true`) return `INVALID_REQUEST` (-32600). + * - Objects without an `id` property are parsed as notifications. + */ +export function parseJsonRpcMessage(raw: string): ParsedJsonRpcMessage { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return { + ok: false, + errorCode: JSON_RPC_ERROR_CODES.PARSE_ERROR, + message: 'Parse error: invalid JSON.', + }; + } + + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { + ok: false, + errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST, + message: 'Invalid Request: expected a JSON-RPC 2.0 object.', + }; + } + + const hasId = Object.prototype.hasOwnProperty.call(parsed, 'id'); + if (hasId) { + const requestResult = jsonRpcRequestSchema.safeParse(parsed); + if (!requestResult.success) { + return { + ok: false, + errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST, + message: 'Invalid Request: malformed JSON-RPC 2.0 request envelope.', + }; + } + return { + ok: true, + kind: 'request', + message: requestResult.data, + }; + } + + const notificationResult = jsonRpcNotificationSchema.safeParse(parsed); + if (!notificationResult.success) { + return { + ok: false, + errorCode: JSON_RPC_ERROR_CODES.INVALID_REQUEST, + message: 'Invalid Request: malformed JSON-RPC 2.0 notification envelope.', + }; + } + + return { + ok: true, + kind: 'notification', + message: notificationResult.data, + }; +} + +/** Builds a JSON-RPC 2.0 success response object. */ +export function jsonRpcSuccess(id: JsonRpcId, result: unknown): JsonRpcSuccessResponse { + return { + jsonrpc: '2.0', + id, + result, + }; +} + +/** Builds a JSON-RPC 2.0 error response object. */ +export function jsonRpcError( + id: JsonRpcId | null, + code: number, + message: string, + data?: unknown +): JsonRpcErrorResponse { + const error: JsonRpcErrorObject = + data !== undefined ? { code, message, data } : { code, message }; + return { + jsonrpc: '2.0', + id, + error, + }; +} diff --git a/libs/research/src/mcp/server.ts b/libs/research/src/mcp/server.ts new file mode 100644 index 00000000..08a80b73 --- /dev/null +++ b/libs/research/src/mcp/server.ts @@ -0,0 +1,540 @@ +import { z } from 'zod'; +import { + JSON_RPC_ERROR_CODES, + type JsonSchemaObject, + type JsonSchemaProperty, + MCP_PROTOCOL_VERSION, + type McpToolCallResult, + type McpToolDescriptor, + jsonRpcError, + jsonRpcSuccess, + mcpInitializeParamsSchema, + mcpPingParamsSchema, + mcpToolsCallParamsSchema, + mcpToolsListParamsSchema, + parseJsonRpcMessage, +} from './protocol'; + +/** Configuration for defining a strongly typed MCP tool. */ +export interface McpToolDefinition { + readonly name: string; + readonly description: string; + readonly inputSchema: z.ZodType; + readonly jsonSchema?: JsonSchemaObject; + readonly handler: (input: TInput) => Promise | McpToolCallResult; +} + +/** Type-erased tool entry registered on an {@link McpServer}. */ +export interface McpToolEntry { + readonly name: string; + readonly description: string; + readonly inputSchema: JsonSchemaObject; + readonly execute: (rawArguments: Record) => Promise; +} + +/** Options for {@link createMcpServer}. */ +export interface McpServerOptions { + readonly name: string; + readonly version: string; + readonly tools?: readonly McpToolEntry[]; +} + +/** Transport-agnostic MCP JSON-RPC 2.0 server interface. */ +export interface McpServer { + readonly name: string; + readonly version: string; + listTools(): readonly McpToolDescriptor[]; + handleMessage(raw: string): Promise; +} + +function isOptionalSchema(schema: z.ZodTypeAny): boolean { + if (schema instanceof z.ZodOptional || schema instanceof z.ZodDefault) { + return true; + } + if (schema instanceof z.ZodEffects) { + return isOptionalSchema(schema._def.schema); + } + return false; +} + +function withDescription( + prop: JsonSchemaProperty, + description: string | undefined +): JsonSchemaProperty { + if (description !== undefined && prop.description === undefined) { + return { ...prop, description }; + } + return prop; +} + +function convertZodType(schema: z.ZodTypeAny): JsonSchemaProperty { + const outerDescription = schema.description; + + if (schema instanceof z.ZodEffects) { + return withDescription(convertZodType(schema._def.schema), outerDescription); + } + + if (schema instanceof z.ZodOptional) { + return withDescription(convertZodType(schema.unwrap()), outerDescription); + } + + if (schema instanceof z.ZodDefault) { + const inner = convertZodType(schema._def.innerType); + const defaultValue: unknown = schema._def.defaultValue(); + return withDescription({ ...inner, default: defaultValue }, outerDescription); + } + + if (schema instanceof z.ZodNullable) { + const inner = convertZodType(schema.unwrap()); + return withDescription({ anyOf: [inner, { type: 'null' }] }, outerDescription); + } + + if (schema instanceof z.ZodString) { + let minLength: number | undefined; + let maxLength: number | undefined; + for (const check of schema._def.checks) { + if (check.kind === 'min') { + minLength = check.value; + } else if (check.kind === 'max') { + maxLength = check.value; + } else if (check.kind === 'length') { + minLength = check.value; + maxLength = check.value; + } + } + const result: { + type: 'string'; + description?: string; + minLength?: number; + maxLength?: number; + } = { type: 'string' }; + if (outerDescription !== undefined) { + result.description = outerDescription; + } + if (minLength !== undefined) { + result.minLength = minLength; + } + if (maxLength !== undefined) { + result.maxLength = maxLength; + } + return result; + } + + if (schema instanceof z.ZodNumber) { + let isInt = false; + let minimum: number | undefined; + let maximum: number | undefined; + let exclusiveMinimum: number | undefined; + let exclusiveMaximum: number | undefined; + for (const check of schema._def.checks) { + if (check.kind === 'int') { + isInt = true; + } else if (check.kind === 'min') { + if (check.inclusive) { + minimum = check.value; + } else { + exclusiveMinimum = check.value; + } + } else if (check.kind === 'max') { + if (check.inclusive) { + maximum = check.value; + } else { + exclusiveMaximum = check.value; + } + } + } + const result: { + type: 'integer' | 'number'; + description?: string; + minimum?: number; + maximum?: number; + exclusiveMinimum?: number; + exclusiveMaximum?: number; + } = { type: isInt ? 'integer' : 'number' }; + if (outerDescription !== undefined) { + result.description = outerDescription; + } + if (minimum !== undefined) { + result.minimum = minimum; + } + if (maximum !== undefined) { + result.maximum = maximum; + } + if (exclusiveMinimum !== undefined) { + result.exclusiveMinimum = exclusiveMinimum; + } + if (exclusiveMaximum !== undefined) { + result.exclusiveMaximum = exclusiveMaximum; + } + return result; + } + + if (schema instanceof z.ZodBoolean) { + return outerDescription !== undefined + ? { type: 'boolean', description: outerDescription } + : { type: 'boolean' }; + } + + if (schema instanceof z.ZodEnum) { + const values = [...schema._def.values] as readonly string[]; + return outerDescription !== undefined + ? { type: 'string', enum: values, description: outerDescription } + : { type: 'string', enum: values }; + } + + if (schema instanceof z.ZodLiteral) { + const literalValue: unknown = schema._def.value; + if ( + typeof literalValue === 'string' || + typeof literalValue === 'number' || + typeof literalValue === 'boolean' || + literalValue === null + ) { + const literalType: JsonSchemaProperty['type'] = + literalValue === null + ? 'null' + : typeof literalValue === 'string' + ? 'string' + : typeof literalValue === 'number' + ? 'number' + : 'boolean'; + return outerDescription !== undefined + ? { type: literalType, const: literalValue, description: outerDescription } + : { type: literalType, const: literalValue }; + } + throw new Error('Unsupported ZodLiteral value type in MCP tool input schema.'); + } + + if (schema instanceof z.ZodArray) { + const items = convertZodType(schema._def.type); + const result: { + type: 'array'; + items: JsonSchemaProperty; + description?: string; + minItems?: number; + maxItems?: number; + } = { type: 'array', items }; + if (outerDescription !== undefined) { + result.description = outerDescription; + } + if (schema._def.minLength !== null) { + result.minItems = schema._def.minLength.value; + } + if (schema._def.maxLength !== null) { + result.maxItems = schema._def.maxLength.value; + } + if (schema._def.exactLength !== null) { + result.minItems = schema._def.exactLength.value; + result.maxItems = schema._def.exactLength.value; + } + return result; + } + + if (schema instanceof z.ZodUnion) { + const options = (schema._def.options as readonly z.ZodTypeAny[]).map(option => + convertZodType(option) + ); + return outerDescription !== undefined + ? { anyOf: options, description: outerDescription } + : { anyOf: options }; + } + + if (schema instanceof z.ZodObject) { + return convertZodObject(schema, outerDescription); + } + + const typeName = + typeof (schema._def as { typeName?: unknown }).typeName === 'string' + ? (schema._def as { typeName: string }).typeName + : 'unknown'; + throw new Error(`Unsupported Zod schema type "${typeName}" in MCP tool input schema.`); +} + +function convertZodObject( + schema: z.ZodObject, + outerDescription: string | undefined +): JsonSchemaObject { + const shape = schema.shape; + const properties: Record = {}; + const required: string[] = []; + + for (const [key, fieldSchema] of Object.entries(shape)) { + properties[key] = convertZodType(fieldSchema); + if (!isOptionalSchema(fieldSchema)) { + required.push(key); + } + } + + const description = outerDescription ?? schema.description; + const result: { + type: 'object'; + properties: Record; + required?: string[]; + additionalProperties: false; + description?: string; + } = { + type: 'object', + properties, + additionalProperties: false, + }; + + if (required.length > 0) { + result.required = required; + } + if (description !== undefined) { + result.description = description; + } + return result; +} + +/** + * Converts a Zod v3 object schema (including `.refine()` / `.superRefine()` + * `ZodEffects` wrappers) into a strict {@link JsonSchemaObject}. + * + * Fails fast on unsupported Zod schema types so misconfigured tools are caught + * at registration time rather than at `tools/list` time. + */ +export function zodObjectToJsonSchema(schema: z.ZodTypeAny): JsonSchemaObject { + let current: z.ZodTypeAny = schema; + let description = schema.description; + + while (current instanceof z.ZodEffects) { + current = current._def.schema; + if (description === undefined && current.description !== undefined) { + description = current.description; + } + } + + if (!(current instanceof z.ZodObject)) { + throw new Error('MCP tool inputSchema must be a ZodObject (optionally wrapped in ZodEffects).'); + } + + return convertZodObject(current, description); +} + +function formatZodIssues(error: z.ZodError): string { + const parts = error.issues.map(issue => { + const path = issue.path.length > 0 ? `${issue.path.join('.')}: ` : ''; + return `${path}${issue.message}`; + }); + return parts.join('; '); +} + +function sanitizeToolError(err: unknown): string { + if (err instanceof Error) { + const rawName = typeof err.name === 'string' && err.name.trim().length > 0 ? err.name.trim() : 'Error'; + const firstLine = (typeof err.message === 'string' ? err.message : '') + .split(/\r?\n/, 1)[0] + ?.replace(/\s+at\s+\S.*$/u, '') + .trim(); + if (firstLine !== undefined && firstLine.length > 0) { + return `${rawName}: ${firstLine}`; + } + return `${rawName}: Tool execution failed.`; + } + return 'Error: Tool execution failed.'; +} + +/** + * Defines a type-erased MCP tool entry with eager JSON Schema generation, + * strict argument validation, and sanitized error handling. + */ +export function defineMcpTool(definition: McpToolDefinition): McpToolEntry { + if (typeof definition.name !== 'string' || definition.name.trim().length === 0) { + throw new Error('MCP tool name must be a non-empty string.'); + } + if (typeof definition.description !== 'string' || definition.description.trim().length === 0) { + throw new Error(`MCP tool "${definition.name}" description must be a non-empty string.`); + } + + const resolvedSchema: JsonSchemaObject = + definition.jsonSchema ?? zodObjectToJsonSchema(definition.inputSchema); + + return { + name: definition.name, + description: definition.description, + inputSchema: resolvedSchema, + async execute(rawArguments: Record): Promise { + const parsed = definition.inputSchema.safeParse(rawArguments); + if (!parsed.success) { + return { + content: [ + { + type: 'text', + text: `Invalid arguments for tool "${definition.name}": ${formatZodIssues(parsed.error)}`, + }, + ], + isError: true, + }; + } + + try { + return await definition.handler(parsed.data); + } catch (err: unknown) { + return { + content: [ + { + type: 'text', + text: sanitizeToolError(err), + }, + ], + isError: true, + }; + } + }, + }; +} + +/** + * Creates a transport-agnostic MCP JSON-RPC 2.0 server with a validated tool + * registry. + */ +export function createMcpServer(options: McpServerOptions): McpServer { + if (typeof options.name !== 'string' || options.name.trim().length === 0) { + throw new Error('MCP server name must be a non-empty string.'); + } + if (typeof options.version !== 'string' || options.version.trim().length === 0) { + throw new Error('MCP server version must be a non-empty string.'); + } + + const toolMap = new Map(); + const toolDescriptors: McpToolDescriptor[] = []; + + for (const tool of options.tools ?? []) { + if (toolMap.has(tool.name)) { + throw new Error(`Duplicate MCP tool name: "${tool.name}".`); + } + toolMap.set(tool.name, tool); + toolDescriptors.push({ + name: tool.name, + description: tool.description, + inputSchema: tool.inputSchema, + }); + } + + const frozenDescriptors: readonly McpToolDescriptor[] = Object.freeze([...toolDescriptors]); + + return { + name: options.name, + version: options.version, + + listTools(): readonly McpToolDescriptor[] { + return frozenDescriptors; + }, + + async handleMessage(raw: string): Promise { + const parsed = parseJsonRpcMessage(raw); + if (!parsed.ok) { + return JSON.stringify(jsonRpcError(null, parsed.errorCode, parsed.message)); + } + + if (parsed.kind === 'notification') { + return null; + } + + const { id, method, params } = parsed.message; + + switch (method) { + case 'initialize': { + if (params !== undefined) { + const initParams = mcpInitializeParamsSchema.safeParse(params); + if (!initParams.success) { + return JSON.stringify( + jsonRpcError( + id, + JSON_RPC_ERROR_CODES.INVALID_PARAMS, + `Invalid params for initialize: ${formatZodIssues(initParams.error)}` + ) + ); + } + } + return JSON.stringify( + jsonRpcSuccess(id, { + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: { + tools: {}, + }, + serverInfo: { + name: options.name, + version: options.version, + }, + }) + ); + } + + case 'ping': { + if (params !== undefined) { + const pingParams = mcpPingParamsSchema.safeParse(params); + if (!pingParams.success) { + return JSON.stringify( + jsonRpcError( + id, + JSON_RPC_ERROR_CODES.INVALID_PARAMS, + `Invalid params for ping: ${formatZodIssues(pingParams.error)}` + ) + ); + } + } + return JSON.stringify(jsonRpcSuccess(id, {})); + } + + case 'tools/list': { + if (params !== undefined) { + const listParams = mcpToolsListParamsSchema.safeParse(params); + if (!listParams.success) { + return JSON.stringify( + jsonRpcError( + id, + JSON_RPC_ERROR_CODES.INVALID_PARAMS, + `Invalid params for tools/list: ${formatZodIssues(listParams.error)}` + ) + ); + } + } + return JSON.stringify( + jsonRpcSuccess(id, { + tools: frozenDescriptors, + }) + ); + } + + case 'tools/call': { + const callParams = mcpToolsCallParamsSchema.safeParse(params); + if (!callParams.success) { + return JSON.stringify( + jsonRpcError( + id, + JSON_RPC_ERROR_CODES.INVALID_PARAMS, + `Invalid params for tools/call: ${formatZodIssues(callParams.error)}` + ) + ); + } + + const tool = toolMap.get(callParams.data.name); + if (tool === undefined) { + return JSON.stringify( + jsonRpcError( + id, + JSON_RPC_ERROR_CODES.INVALID_PARAMS, + `Unknown tool: "${callParams.data.name}".` + ) + ); + } + + const result = await tool.execute(callParams.data.arguments ?? {}); + return JSON.stringify(jsonRpcSuccess(id, result)); + } + + default: { + return JSON.stringify( + jsonRpcError( + id, + JSON_RPC_ERROR_CODES.METHOD_NOT_FOUND, + `Method not found: "${method}".` + ) + ); + } + } + }, + }; +} diff --git a/libs/research/src/mcp/stdio.ts b/libs/research/src/mcp/stdio.ts new file mode 100644 index 00000000..580c3b6e --- /dev/null +++ b/libs/research/src/mcp/stdio.ts @@ -0,0 +1,147 @@ +import { JSON_RPC_ERROR_CODES, jsonRpcError } from './protocol'; +import type { McpServer } from './server'; + +/** Default maximum allowed line frame size in UTF-8 bytes (4 MiB). */ +export const DEFAULT_STDIO_MAX_LINE_BYTES = 4 * 1024 * 1024; + +/** Readable byte/string stream accepted by {@link runStdioServer}. */ +export type StdioInput = AsyncIterable; + +/** Minimal writable stream interface accepted by {@link runStdioServer}. */ +export interface StdioOutput { + write(chunk: string): boolean; + once?(event: 'drain', listener: () => void): unknown; +} + +/** Options for {@link runStdioServer}. */ +export interface StdioServerOptions { + readonly input?: StdioInput; + readonly output?: StdioOutput; + readonly maxLineBytes?: number; +} + +async function writeLine(output: StdioOutput, line: string): Promise { + const ok = output.write(`${line}\n`); + if (!ok && typeof output.once === 'function') { + await new Promise(resolve => { + output.once?.('drain', () => { + resolve(); + }); + }); + } +} + +/** + * Runs a newline-delimited JSON-RPC 2.0 stdio transport loop for an + * {@link McpServer}. + * + * - Decodes binary chunks with streaming UTF-8 (`TextDecoder`) so multi-byte + * characters split across chunk boundaries are never corrupted. + * - Dispatches lines strictly sequentially in arrival order. + * - Writes only compact newline-terminated JSON-RPC responses to `output` + * (skipping `null` notification results and blank lines). + * - Guards against oversized unterminated frames via `maxLineBytes`. + */ +export async function runStdioServer( + server: McpServer, + options?: StdioServerOptions +): Promise { + const input: StdioInput = options?.input ?? process.stdin; + const output: StdioOutput = options?.output ?? process.stdout; + const maxLineBytes = options?.maxLineBytes ?? DEFAULT_STDIO_MAX_LINE_BYTES; + + if (!Number.isSafeInteger(maxLineBytes) || maxLineBytes < 1) { + throw new Error(`Invalid maxLineBytes (${String(maxLineBytes)}): expected a positive integer.`); + } + + const decoder = new TextDecoder('utf-8'); + const encoder = new TextEncoder(); + let buffer = ''; + let droppingOversizedLine = false; + + const processLine = async (rawLine: string): Promise => { + const trimmed = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine; + if (trimmed.trim().length === 0) { + return; + } + const response = await server.handleMessage(trimmed); + if (response !== null) { + await writeLine(output, response); + } + }; + + const emitOversizedError = async (): Promise => { + const errorPayload = JSON.stringify( + jsonRpcError( + null, + JSON_RPC_ERROR_CODES.PARSE_ERROR, + `Parse error: message exceeds maximum frame size of ${maxLineBytes} bytes.` + ) + ); + await writeLine(output, errorPayload); + }; + + const drainBuffer = async (): Promise => { + while (true) { + const newlineIdx = buffer.indexOf('\n'); + if (newlineIdx === -1) { + if (!droppingOversizedLine && encoder.encode(buffer).byteLength > maxLineBytes) { + droppingOversizedLine = true; + buffer = ''; + await emitOversizedError(); + } + return; + } + + const rawLine = buffer.slice(0, newlineIdx); + buffer = buffer.slice(newlineIdx + 1); + + if (droppingOversizedLine) { + droppingOversizedLine = false; + continue; + } + + if (encoder.encode(rawLine).byteLength > maxLineBytes) { + await emitOversizedError(); + continue; + } + + await processLine(rawLine); + } + }; + + for await (const chunk of input) { + const text = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true }); + if (text.length === 0) { + continue; + } + + if (droppingOversizedLine) { + const newlineIdx = text.indexOf('\n'); + if (newlineIdx === -1) { + continue; + } + droppingOversizedLine = false; + buffer = text.slice(newlineIdx + 1); + } else { + buffer += text; + } + + await drainBuffer(); + } + + const tail = decoder.decode(); + if (tail.length > 0 && !droppingOversizedLine) { + buffer += tail; + } + + await drainBuffer(); + + if (!droppingOversizedLine && buffer.length > 0) { + if (encoder.encode(buffer).byteLength > maxLineBytes) { + await emitOversizedError(); + } else { + await processLine(buffer); + } + } +} diff --git a/libs/research/src/mcp/tools/query-data.ts b/libs/research/src/mcp/tools/query-data.ts new file mode 100644 index 00000000..a336985e --- /dev/null +++ b/libs/research/src/mcp/tools/query-data.ts @@ -0,0 +1,307 @@ +import { z } from 'zod'; +import { + type BarRecord, + type MarketDataStore, + MarketDataStoreValidationError, + type VaultFenceContext, + VaultHoldoutFenceError, + VaultScopeNotAuthorizedError, + applyVaultFence, +} from '../../market-data-store'; +import { + AdjFactorsSnapshotError, + MarketDataStoreNotImplementedError, +} from '../../market-data-store-duckdb'; +import type { McpToolCallResult } from '../protocol'; +import { type McpToolEntry, defineMcpTool } from '../server'; + +const INT32_MIN = -2_147_483_648; +const INT32_MAX = 2_147_483_647; +const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; + +/** Default maximum number of bar rows returned by `query_data`. */ +export const QUERY_DATA_DEFAULT_LIMIT = 500; + +/** Hard maximum number of bar rows returned by `query_data`. */ +export const QUERY_DATA_MAX_LIMIT = 5_000; + +/** Hard maximum number of explicit `listingIds` accepted by `query_data`. */ +export const QUERY_DATA_MAX_LISTING_IDS = 500; + +/** + * Strict Zod input schema for the `query_data` MCP tool. + * + * Intentionally omits `scope` and `vault_evaluation_only`; `.strict()` rejects + * any caller attempt to supply them or any other unknown key. + */ +export const queryDataInputSchema = z + .object({ + listingIds: z + .array(z.number().int().min(INT32_MIN).max(INT32_MAX)) + .min(1) + .max(QUERY_DATA_MAX_LISTING_IDS) + .optional() + .describe('Explicit INT32 listing IDs to query (mutually exclusive with universe).'), + universe: z + .string() + .min(1) + .optional() + .describe('Universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).'), + from: z + .string() + .min(1) + .describe('Inclusive start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.'), + to: z + .string() + .min(1) + .describe('Inclusive end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.'), + timeframe: z + .enum(['1m', '5m', '1h', '1d']) + .default('1d') + .describe('Bar timeframe (default 1d).'), + adjustment: z + .enum(['raw', 'split', 'total']) + .default('raw') + .describe('Price/volume adjustment mode (default raw).'), + asOf: z + .string() + .min(1) + .optional() + .describe('Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.'), + limit: z + .number() + .int() + .min(1) + .max(QUERY_DATA_MAX_LIMIT) + .default(QUERY_DATA_DEFAULT_LIMIT) + .describe( + `Maximum number of bar rows to return (default ${QUERY_DATA_DEFAULT_LIMIT}, max ${QUERY_DATA_MAX_LIMIT}).` + ), + }) + .strict() + .refine( + data => (data.listingIds !== undefined) !== (data.universe !== undefined), + 'Exactly one of "listingIds" or "universe" must be provided.' + ); + +export type QueryDataInput = z.infer; + +/** Configuration for {@link createQueryDataTool}. */ +export interface QueryDataToolOptions { + readonly store: MarketDataStore; + readonly vaultContext: Pick; +} + +/** Structured JSON payload serialized into the `query_data` MCP text result. */ +export interface QueryDataResultPayload { + readonly scope: 'vault_fenced'; + readonly vaultCutoffTs: number; + readonly timeframe: '1m' | '5m' | '1h' | '1d'; + readonly adjustment: 'raw' | 'split' | 'total'; + readonly fromMs: number; + readonly toMs: number; + readonly asOfMs: number; + readonly clampedTo: boolean; + readonly clampedAsOf: boolean; + readonly limit: number; + readonly rowCount: number; + readonly truncated: boolean; + readonly rows: readonly BarRecord[]; +} + +function utcDateOf(epochMs: number): string { + return new Date(epochMs).toISOString().slice(0, 10); +} + +function formatUtcIsoMs(epochMs: number): string { + return new Date(epochMs).toISOString(); +} + +function formatDomainError(err: Error): McpToolCallResult { + const firstLine = err.message + .split(/\r?\n/, 1)[0] + ?.replace(/\s+at\s+\S.*$/u, '') + .trim(); + const detail = firstLine !== undefined && firstLine.length > 0 ? firstLine : 'Query failed.'; + return { + content: [ + { + type: 'text', + text: `${err.name}: ${detail}`, + }, + ], + isError: true, + }; +} + +function isMappedStoreError(err: unknown): err is Error { + return ( + err instanceof VaultHoldoutFenceError || + err instanceof VaultScopeNotAuthorizedError || + err instanceof MarketDataStoreValidationError || + err instanceof MarketDataStoreNotImplementedError || + err instanceof AdjFactorsSnapshotError + ); +} + +function validateFactoryOptions(options: QueryDataToolOptions): void { + if ( + typeof options.store !== 'object' || + options.store === null || + typeof options.store.bars !== 'function' || + typeof options.store.universe !== 'function' + ) { + throw new MarketDataStoreValidationError( + 'Invalid `store`: expected a MarketDataStore implementing `bars` and `universe`.', + 'store' + ); + } + + const cutoffTs = options.vaultContext?.vaultCutoffTs; + if ( + typeof cutoffTs !== 'number' || + !Number.isFinite(cutoffTs) || + !Number.isSafeInteger(cutoffTs) || + Math.abs(cutoffTs) >= MAX_ECMASCRIPT_EPOCH_MS + ) { + throw new MarketDataStoreValidationError( + `Invalid \`vaultContext.vaultCutoffTs\`: ${String(cutoffTs)}.`, + 'vaultCutoffTs' + ); + } +} + +/** + * Creates the Vault-fenced `query_data` MCP tool backed by an injected + * {@link MarketDataStore}. + * + * Always enforces `scope: 'vault_fenced'`, runs {@link applyVaultFence} before + * any store call, drops any post-cutoff row yielded by a store as defense in + * depth, and bounds output rows by `limit` (default {@link QUERY_DATA_DEFAULT_LIMIT}, + * hard max {@link QUERY_DATA_MAX_LIMIT}). + */ +export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry { + validateFactoryOptions(options); + const { store } = options; + const vaultCutoffTs = options.vaultContext.vaultCutoffTs; + + return defineMcpTool({ + name: 'query_data', + description: + 'Query Vault-fenced OHLCV market bars for explicit listing IDs or a survivorship-free universe.', + inputSchema: queryDataInputSchema, + async handler(input: QueryDataInput): Promise { + try { + const fenced = applyVaultFence( + { + from: input.from, + to: input.to, + asOf: input.asOf, + scope: 'vault_fenced', + }, + { + vaultCutoffTs, + vaultOperatorAuthorized: false, + } + ); + + const effectiveLimit = input.limit; + let listingIds: number[]; + + if (input.universe !== undefined) { + const resolved = await store.universe({ + ref: input.universe, + date: utcDateOf(fenced.toMs), + }); + if (resolved.length === 0) { + const emptyPayload: QueryDataResultPayload = { + scope: 'vault_fenced', + vaultCutoffTs, + timeframe: input.timeframe, + adjustment: input.adjustment, + fromMs: fenced.fromMs, + toMs: fenced.toMs, + asOfMs: fenced.asOfMs, + clampedTo: fenced.clampedTo, + clampedAsOf: fenced.clampedAsOf, + limit: effectiveLimit, + rowCount: 0, + truncated: false, + rows: [], + }; + return { + content: [{ type: 'text', text: JSON.stringify(emptyPayload) }], + }; + } + listingIds = [...resolved]; + } else { + listingIds = [...(input.listingIds ?? [])]; + } + + const effectiveFencedTo = fenced.clampedTo ? formatUtcIsoMs(fenced.toMs) : input.to; + const effectiveFencedAsOf = + fenced.clampedAsOf || input.asOf === undefined + ? formatUtcIsoMs(fenced.asOfMs) + : input.asOf; + + const stream = store.bars({ + listingIds, + timeframe: input.timeframe, + from: input.from, + to: effectiveFencedTo, + adjustment: input.adjustment, + asOf: effectiveFencedAsOf, + scope: 'vault_fenced', + }); + + const rows: BarRecord[] = []; + let truncated = false; + + outer: for await (const batch of stream) { + for (const row of batch.rows) { + if ( + !Number.isFinite(row.ts) || + !Number.isFinite(row.knownAt) || + row.ts >= vaultCutoffTs || + row.knownAt >= vaultCutoffTs + ) { + continue; + } + + if (rows.length >= effectiveLimit) { + truncated = true; + break outer; + } + + rows.push(row); + } + } + + const payload: QueryDataResultPayload = { + scope: 'vault_fenced', + vaultCutoffTs, + timeframe: input.timeframe, + adjustment: input.adjustment, + fromMs: fenced.fromMs, + toMs: fenced.toMs, + asOfMs: fenced.asOfMs, + clampedTo: fenced.clampedTo, + clampedAsOf: fenced.clampedAsOf, + limit: effectiveLimit, + rowCount: rows.length, + truncated, + rows, + }; + + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } catch (err: unknown) { + if (isMappedStoreError(err)) { + return formatDomainError(err); + } + throw err; + } + }, + }); +} diff --git a/libs/research/test/mcp-protocol.test.ts b/libs/research/test/mcp-protocol.test.ts new file mode 100644 index 00000000..eb312d45 --- /dev/null +++ b/libs/research/test/mcp-protocol.test.ts @@ -0,0 +1,324 @@ +import { describe, expect, test } from 'bun:test'; +import { z } from 'zod'; +import * as rootResearchExports from '../src/index'; +import { + JSON_RPC_ERROR_CODES, + MCP_PROTOCOL_VERSION, + createMcpServer, + defineMcpTool, + zodObjectToJsonSchema, +} from '../src/mcp/index'; + +interface JsonRpcParsedResponse { + jsonrpc: string; + id: string | number | null; + result?: Record; + error?: { + code: number; + message: string; + data?: unknown; + }; +} + +function parseResponse(raw: string | null): JsonRpcParsedResponse { + expect(raw).not.toBeNull(); + return JSON.parse(raw as string) as JsonRpcParsedResponse; +} + +describe('MCP protocol & server core', () => { + test('initialize returns protocolVersion, serverInfo, and capabilities.tools', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [], + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: 'test-client', version: '1.0.0' }, + }, + }) + ); + + const response = parseResponse(raw); + expect(response.jsonrpc).toBe('2.0'); + expect(response.id).toBe(1); + expect(response.error).toBeUndefined(); + expect(response.result).toEqual({ + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: { tools: {} }, + serverInfo: { + name: 'stock-bot-research', + version: '0.1.0', + }, + }); + }); + + test('notifications/initialized returns null (no response)', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + method: 'notifications/initialized', + }) + ); + + expect(raw).toBeNull(); + }); + + test('ping returns empty object result', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'ping-1', + method: 'ping', + }) + ); + + const response = parseResponse(raw); + expect(response.id).toBe('ping-1'); + expect(response.result).toEqual({}); + }); + + test('echoes string and numeric request ids verbatim (including 0 and negative integers)', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const ids: readonly (string | number)[] = ['req-abc', '', 0, -42, 9007199254740991]; + for (const id of ids) { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'ping', + }) + ); + const response = parseResponse(raw); + expect(response.id).toBe(id); + } + }); + + test('malformed JSON returns -32700 with id: null', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const raw = await server.handleMessage('{not valid json'); + const response = parseResponse(raw); + expect(response.id).toBeNull(); + expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); + }); + + test('non-JSON-RPC objects and explicit invalid id return -32600', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const badPayloads = [ + '42', + '"hello"', + 'null', + '[]', + JSON.stringify({ foo: 'bar' }), + JSON.stringify({ jsonrpc: '1.0', id: 1, method: 'ping' }), + JSON.stringify({ jsonrpc: '2.0', id: null, method: 'ping' }), + JSON.stringify({ jsonrpc: '2.0', id: true, method: 'ping' }), + JSON.stringify({ jsonrpc: '2.0', id: { nested: 1 }, method: 'ping' }), + JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping', extra: true }), + ]; + + for (const payload of badPayloads) { + const raw = await server.handleMessage(payload); + const response = parseResponse(raw); + expect(response.id).toBeNull(); + expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_REQUEST); + } + }); + + test('unknown method returns -32601 echoing request id', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'unknown-1', + method: 'resources/list', + }) + ); + + const response = parseResponse(raw); + expect(response.id).toBe('unknown-1'); + expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.METHOD_NOT_FOUND); + }); + + test('tools/call rejects unknown tool name and malformed params with -32602', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [], + }); + + const unknownToolRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 10, + method: 'tools/call', + params: { name: 'does_not_exist', arguments: {} }, + }) + ); + const unknownToolResp = parseResponse(unknownToolRaw); + expect(unknownToolResp.id).toBe(10); + expect(unknownToolResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); + + const badParamsRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 11, + method: 'tools/call', + params: { name: 123, arguments: 'not-an-object' }, + }) + ); + const badParamsResp = parseResponse(badParamsRaw); + expect(badParamsResp.id).toBe(11); + expect(badParamsResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); + }); + + test('invalid tool arguments return isError: true with readable message and zero handler calls', async () => { + let handlerCalls = 0; + const echoTool = defineMcpTool({ + name: 'echo_count', + description: 'Echoes a positive integer count.', + inputSchema: z.object({ count: z.number().int().min(1) }).strict(), + handler(input) { + handlerCalls += 1; + return { + content: [{ type: 'text', text: String(input.count) }], + }; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [echoTool], + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 20, + method: 'tools/call', + params: { + name: 'echo_count', + arguments: { count: 0, unexpected: true }, + }, + }) + ); + + expect(handlerCalls).toBe(0); + const response = parseResponse(raw); + expect(response.id).toBe(20); + expect(response.error).toBeUndefined(); + const result = response.result as { + isError?: boolean; + content: { type: string; text: string }[]; + }; + expect(result.isError).toBe(true); + expect(result.content[0]?.type).toBe('text'); + expect(result.content[0]?.text).toContain('Invalid arguments for tool "echo_count"'); + }); + + test('throwing tool handler returns isError: true with sanitized error and zero stack trace', async () => { + const boomTool = defineMcpTool({ + name: 'explode', + description: 'Always throws an error.', + inputSchema: z.object({}).strict(), + handler() { + const err = new Error('Simulated backend failure\n at secretInternal (/srv/app/secret.ts:42:9)'); + err.name = 'BackendFailureError'; + throw err; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [boomTool], + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 30, + method: 'tools/call', + params: { name: 'explode', arguments: {} }, + }) + ); + + const response = parseResponse(raw); + expect(response.id).toBe(30); + expect(response.error).toBeUndefined(); + const result = response.result as { + isError?: boolean; + content: { type: string; text: string }[]; + }; + expect(result.isError).toBe(true); + const text = result.content[0]?.text ?? ''; + expect(text).toBe('BackendFailureError: Simulated backend failure'); + expect(text).not.toContain('at '); + expect(text).not.toContain('/srv/app/secret.ts'); + expect(text).not.toContain('\n'); + }); + + test('duplicate tool names throw at createMcpServer time and unsupported schemas fail fast', () => { + const makeTool = () => + defineMcpTool({ + name: 'dup_tool', + description: 'Duplicate tool test.', + inputSchema: z.object({ x: z.string() }).strict(), + handler: () => ({ content: [{ type: 'text', text: 'ok' }] }), + }); + + expect(() => + createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [makeTool(), makeTool()], + }) + ).toThrow(/Duplicate MCP tool name/i); + + expect(() => + zodObjectToJsonSchema(z.object({ bad: z.date() }).strict()) + ).toThrow(/Unsupported Zod schema type/i); + }); + + test('browser-safe root entrypoint does not re-export MCP symbols', () => { + const exportedKeys = Object.keys(rootResearchExports); + expect(exportedKeys).not.toContain('createMcpServer'); + expect(exportedKeys).not.toContain('defineMcpTool'); + expect(exportedKeys).not.toContain('runStdioServer'); + expect(exportedKeys).not.toContain('createQueryDataTool'); + }); +}); diff --git a/libs/research/test/mcp-query-data.test.ts b/libs/research/test/mcp-query-data.test.ts new file mode 100644 index 00000000..03722117 --- /dev/null +++ b/libs/research/test/mcp-query-data.test.ts @@ -0,0 +1,482 @@ +import { describe, expect, test } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + type MarketDataStore, + MarketDataStoreValidationError, + VaultScopeNotAuthorizedError, +} from '../src/market-data-store'; +import { + AdjFactorsSnapshotError, + type BarsQuery, + MarketDataStoreNotImplementedError, + type UniverseQuery, +} from '../src/market-data-store-duckdb'; +import { + QUERY_DATA_DEFAULT_LIMIT, + QUERY_DATA_MAX_LIMIT, + type QueryDataResultPayload, + createMcpServer, + createQueryDataTool, +} from '../src/mcp/index'; + +const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); // 2025-03-31T00:00:00.000Z + +function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { + return { + listingId, + ts, + open: close - 1, + high: close + 1, + low: close - 2, + close, + volume: 1_000, + vwap: close, + knownAt, + }; +} + +interface FakeStoreState { + readonly barsCalls: BarsQuery[]; + readonly universeCalls: UniverseQuery[]; + readonly store: MarketDataStore; +} + +function createFakeStore(options?: { + batches?: readonly BarBatch[]; + universeIds?: readonly number[]; + barsError?: Error; + universeError?: Error; +}): FakeStoreState { + const barsCalls: BarsQuery[] = []; + const universeCalls: UniverseQuery[] = []; + + const batches = options?.batches ?? []; + const universeIds = options?.universeIds ?? []; + + const store: MarketDataStore = { + bars(q: BarsQuery): AsyncIterable { + barsCalls.push(q); + if (options?.barsError !== undefined) { + const err = options.barsError; + return { + [Symbol.asyncIterator]() { + return { + next() { + return Promise.reject(err); + }, + }; + }, + }; + } + return { + async *[Symbol.asyncIterator]() { + for (const batch of batches) { + yield batch; + } + }, + }; + }, + async universe(q: UniverseQuery): Promise { + universeCalls.push(q); + if (options?.universeError !== undefined) { + throw options.universeError; + } + return [...universeIds]; + }, + crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; + + return { barsCalls, universeCalls, store }; +} + +async function callQueryData( + fake: FakeStoreState, + args: Record +): Promise<{ + rawResponse: string; + isError: boolean; + text: string; +}> { + const tool = createQueryDataTool({ + store: fake.store, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [tool], + }); + + const rawResponse = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'q1', + method: 'tools/call', + params: { + name: 'query_data', + arguments: args, + }, + }) + ); + + expect(rawResponse).not.toBeNull(); + const parsed = JSON.parse(rawResponse as string) as { + result: { + isError?: boolean; + content: { type: string; text: string }[]; + }; + }; + return { + rawResponse: rawResponse as string, + isError: parsed.result.isError === true, + text: parsed.result.content[0]?.text ?? '', + }; +} + +describe('MCP query_data tool', () => { + test('tools/list exposes query_data with strict inputSchema and omits scope / vault_evaluation_only', async () => { + const fake = createFakeStore(); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: fake.store, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + ], + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/list', + }) + ); + + const parsed = JSON.parse(raw as string) as { + result: { + tools: { + name: string; + description: string; + inputSchema: { + type: string; + properties: Record; + required?: string[]; + additionalProperties: boolean; + }; + }[]; + }; + }; + + expect(parsed.result.tools).toHaveLength(1); + const tool = parsed.result.tools[0]; + expect(tool?.name).toBe('query_data'); + expect(tool?.inputSchema.type).toBe('object'); + expect(tool?.inputSchema.additionalProperties).toBe(false); + expect(tool?.inputSchema.required).toEqual(['from', 'to']); + + const propKeys = Object.keys(tool?.inputSchema.properties ?? {}); + expect(propKeys).toContain('listingIds'); + expect(propKeys).toContain('universe'); + expect(propKeys).toContain('from'); + expect(propKeys).toContain('to'); + expect(propKeys).toContain('limit'); + expect(propKeys).not.toContain('scope'); + expect(propKeys).not.toContain('vault_evaluation_only'); + expect(tool?.inputSchema.required).not.toContain('scope'); + expect(tool?.inputSchema.required).not.toContain('vault_evaluation_only'); + }); + + test('returns pre-cutoff rows and records scope === vault_fenced on every bars() call', async () => { + const bar1 = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150.5); + const bar2 = makeBar(101, Date.UTC(2025, 2, 30, 20, 0, 0), 152.0); + const fake = createFakeStore({ + batches: [{ rows: [bar1, bar2] }], + }); + + const { isError, text } = await callQueryData(fake, { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + }); + + expect(isError).toBe(false); + expect(fake.barsCalls).toHaveLength(1); + expect(fake.barsCalls[0]?.scope).toBe('vault_fenced'); + + const payload = JSON.parse(text) as QueryDataResultPayload; + expect(payload.scope).toBe('vault_fenced'); + expect(payload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS); + expect(payload.clampedTo).toBe(false); + expect(payload.rowCount).toBe(2); + expect(payload.truncated).toBe(false); + expect(payload.rows).toEqual([bar1, bar2]); + }); + + test('enforces default limit, explicit limit, max limit, and rejects out-of-bounds limits with zero store calls', async () => { + const totalRows = QUERY_DATA_MAX_LIMIT + 5; + const allRows: BarRecord[] = []; + for (let i = 0; i < totalRows; i += 1) { + allRows.push(makeBar(101, Date.UTC(2024, 0, 1, 0, 0, 0) + i * 60_000, 100 + i * 0.01)); + } + + // Omitted limit -> caps at QUERY_DATA_DEFAULT_LIMIT with truncated: true + const defaultFake = createFakeStore({ batches: [{ rows: allRows }] }); + const defaultRes = await callQueryData(defaultFake, { + listingIds: [101], + from: '2024-01-01', + to: '2025-03-01', + }); + expect(defaultRes.isError).toBe(false); + const defaultPayload = JSON.parse(defaultRes.text) as QueryDataResultPayload; + expect(defaultPayload.limit).toBe(QUERY_DATA_DEFAULT_LIMIT); + expect(defaultPayload.rowCount).toBe(QUERY_DATA_DEFAULT_LIMIT); + expect(defaultPayload.truncated).toBe(true); + + // Explicit limit -> caps at requested value + const explicitFake = createFakeStore({ batches: [{ rows: allRows }] }); + const explicitRes = await callQueryData(explicitFake, { + listingIds: [101], + from: '2024-01-01', + to: '2025-03-01', + limit: 3, + }); + expect(explicitRes.isError).toBe(false); + const explicitPayload = JSON.parse(explicitRes.text) as QueryDataResultPayload; + expect(explicitPayload.limit).toBe(3); + expect(explicitPayload.rowCount).toBe(3); + expect(explicitPayload.truncated).toBe(true); + + // Exact QUERY_DATA_MAX_LIMIT -> succeeds + const maxFake = createFakeStore({ batches: [{ rows: allRows }] }); + const maxRes = await callQueryData(maxFake, { + listingIds: [101], + from: '2024-01-01', + to: '2025-03-01', + limit: QUERY_DATA_MAX_LIMIT, + }); + expect(maxRes.isError).toBe(false); + const maxPayload = JSON.parse(maxRes.text) as QueryDataResultPayload; + expect(maxPayload.rowCount).toBe(QUERY_DATA_MAX_LIMIT); + expect(maxPayload.truncated).toBe(true); + + // limit > QUERY_DATA_MAX_LIMIT or <= 0 -> isError: true with zero store calls + for (const badLimit of [QUERY_DATA_MAX_LIMIT + 1, 0, -5]) { + const badFake = createFakeStore({ batches: [{ rows: allRows }] }); + const badRes = await callQueryData(badFake, { + listingIds: [101], + from: '2024-01-01', + to: '2025-03-01', + limit: badLimit, + }); + expect(badRes.isError).toBe(true); + expect(badFake.barsCalls).toHaveLength(0); + expect(badFake.universeCalls).toHaveLength(0); + } + }); + + test('rejects scope, vault_evaluation_only, or unknown keys with isError: true and zero store calls', async () => { + const injectedPayloads: Record[] = [ + { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + scope: 'vault_evaluation_only', + }, + { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + scope: 'vault_fenced', + }, + { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + vault_evaluation_only: true, + }, + { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + unknownFlag: 'x', + }, + ]; + + for (const args of injectedPayloads) { + const fake = createFakeStore({ + batches: [{ rows: [makeBar(101, Date.UTC(2025, 2, 20, 20, 0, 0), 100)] }], + }); + const res = await callQueryData(fake, args); + expect(res.isError).toBe(true); + expect(fake.barsCalls).toHaveLength(0); + expect(fake.universeCalls).toHaveLength(0); + } + }); + + test('range starting at or after vaultCutoffTs returns isError: true naming VaultHoldoutFenceError with zero store calls', async () => { + const fake = createFakeStore({ + batches: [{ rows: [makeBar(101, Date.UTC(2025, 3, 5, 20, 0, 0), 200)] }], + }); + + const res = await callQueryData(fake, { + listingIds: [101], + from: '2025-03-31', + to: '2025-04-15', + }); + + expect(res.isError).toBe(true); + expect(res.text).toContain('VaultHoldoutFenceError'); + expect(fake.barsCalls).toHaveLength(0); + expect(fake.universeCalls).toHaveLength(0); + }); + + test('range straddling vaultCutoffTs clamps to/asOf strictly below cutoff', async () => { + const preBar = makeBar(101, Date.UTC(2025, 2, 30, 20, 0, 0), 150); + const fake = createFakeStore({ + batches: [{ rows: [preBar] }], + }); + + const res = await callQueryData(fake, { + listingIds: [101], + from: '2025-03-01', + to: '2025-04-30', + asOf: '2025-05-01', + }); + + expect(res.isError).toBe(false); + expect(fake.barsCalls).toHaveLength(1); + expect(fake.barsCalls[0]?.scope).toBe('vault_fenced'); + expect(Date.parse(fake.barsCalls[0]?.to ?? '')).toBe(VAULT_CUTOFF_TS - 1); + expect(Date.parse(fake.barsCalls[0]?.asOf ?? '')).toBe(VAULT_CUTOFF_TS - 1); + + const payload = JSON.parse(res.text) as QueryDataResultPayload; + expect(payload.clampedTo).toBe(true); + expect(payload.clampedAsOf).toBe(true); + expect(payload.toMs).toBe(VAULT_CUTOFF_TS - 1); + expect(payload.asOfMs).toBe(VAULT_CUTOFF_TS - 1); + expect(payload.rows).toEqual([preBar]); + }); + + test('defense-in-depth drops post-cutoff rows (ts >= cutoff or knownAt >= cutoff) from a leaky store', async () => { + const preBar = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150); + const leakyTsBar = makeBar(101, VAULT_CUTOFF_TS, 999); + const leakyFutureTsBar = makeBar(101, Date.UTC(2025, 3, 2, 20, 0, 0), 1000); + const leakyKnownAtBar = makeBar( + 101, + Date.UTC(2025, 2, 25, 20, 0, 0), + 148, + VAULT_CUTOFF_TS + ); + + const fake = createFakeStore({ + batches: [{ rows: [preBar, leakyTsBar, leakyFutureTsBar, leakyKnownAtBar] }], + }); + + const res = await callQueryData(fake, { + listingIds: [101], + from: '2025-03-01', + to: '2025-04-15', + }); + + expect(res.isError).toBe(false); + const payload = JSON.parse(res.text) as QueryDataResultPayload; + expect(payload.rowCount).toBe(1); + expect(payload.rows).toEqual([preBar]); + }); + + test('universe path resolves strictly pre-cutoff date and handles empty universe cleanly', async () => { + const preBar = makeBar(202, Date.UTC(2025, 2, 28, 20, 0, 0), 50); + const populatedFake = createFakeStore({ + universeIds: [202], + batches: [{ rows: [preBar] }], + }); + + const res = await callQueryData(populatedFake, { + universe: 'US_EQ', + from: '2025-03-01', + to: '2025-04-30', + }); + + expect(res.isError).toBe(false); + expect(populatedFake.universeCalls).toEqual([{ ref: 'US_EQ', date: '2025-03-30' }]); + expect(populatedFake.barsCalls).toHaveLength(1); + expect(populatedFake.barsCalls[0]?.listingIds).toEqual([202]); + expect(populatedFake.barsCalls[0]?.scope).toBe('vault_fenced'); + + // Empty universe -> zero bars() calls + const emptyFake = createFakeStore({ universeIds: [] }); + const emptyRes = await callQueryData(emptyFake, { + universe: 'CA_EQ', + from: '2025-03-01', + to: '2025-03-30', + }); + expect(emptyRes.isError).toBe(false); + expect(emptyFake.universeCalls).toHaveLength(1); + expect(emptyFake.barsCalls).toHaveLength(0); + const emptyPayload = JSON.parse(emptyRes.text) as QueryDataResultPayload; + expect(emptyPayload.rowCount).toBe(0); + expect(emptyPayload.rows).toEqual([]); + }); + + test('maps store domain errors to isError: true naming the exact error class without stack traces', async () => { + const domainErrors: readonly [Error, string][] = [ + [new VaultScopeNotAuthorizedError(), 'VaultScopeNotAuthorizedError'], + [new MarketDataStoreValidationError('Bad timeframe bound', 'from'), 'MarketDataStoreValidationError'], + [new MarketDataStoreNotImplementedError('bars', '1m not supported'), 'MarketDataStoreNotImplementedError'], + [new AdjFactorsSnapshotError('retrospective_rejected', 'Retrospective snapshot rejected'), 'AdjFactorsSnapshotError'], + ]; + + for (const [err, expectedName] of domainErrors) { + const fake = createFakeStore({ barsError: err }); + const res = await callQueryData(fake, { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + }); + expect(res.isError).toBe(true); + expect(res.text).toContain(expectedName); + expect(res.text).not.toContain('\n'); + expect(res.text).not.toContain('at '); + } + }); + + test('repeated identical calls produce byte-identical JSON output', async () => { + const bar = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150.25); + const fake1 = createFakeStore({ batches: [{ rows: [bar] }] }); + const fake2 = createFakeStore({ batches: [{ rows: [bar] }] }); + + const args = { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + timeframe: '1d', + adjustment: 'raw', + limit: 10, + }; + + const res1 = await callQueryData(fake1, args); + const res2 = await callQueryData(fake2, args); + expect(res1.rawResponse).toBe(res2.rawResponse); + }); +}); diff --git a/libs/research/test/mcp-stdio.test.ts b/libs/research/test/mcp-stdio.test.ts new file mode 100644 index 00000000..08d38bd5 --- /dev/null +++ b/libs/research/test/mcp-stdio.test.ts @@ -0,0 +1,195 @@ +import { describe, expect, test } from 'bun:test'; +import { z } from 'zod'; +import { + JSON_RPC_ERROR_CODES, + type StdioOutput, + createMcpServer, + defineMcpTool, + runStdioServer, +} from '../src/mcp/index'; + +function createMemoryOutput(): { output: StdioOutput; chunks: string[]; text: () => string } { + const chunks: string[] = []; + const output: StdioOutput = { + write(chunk: string): boolean { + chunks.push(chunk); + return true; + }, + }; + return { + output, + chunks, + text: () => chunks.join(''), + }; +} + +async function* yieldChunks(chunks: readonly (Uint8Array | string)[]): AsyncGenerator { + for (const chunk of chunks) { + yield chunk; + } +} + +describe('MCP stdio transport', () => { + test('processes 3 messages (1 notification + 1 chunk-split multi-byte UTF-8 request) into exactly 2 newline-terminated responses', async () => { + const echoTool = defineMcpTool({ + name: 'echo_label', + description: 'Echoes a UTF-8 label.', + inputSchema: z.object({ label: z.string() }).strict(), + handler(input) { + return { + content: [{ type: 'text', text: input.label }], + }; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [echoTool], + }); + + const encoder = new TextEncoder(); + const msg1 = `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\n`; + const msg2 = `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`; + const msg3Bytes = encoder.encode( + `${JSON.stringify({ + jsonrpc: '2.0', + id: 'utf8-2', + method: 'tools/call', + params: { name: 'echo_label', arguments: { label: 'café-🚀-αβγ' } }, + })}\n` + ); + + // Split right in the middle of the multi-byte UTF-8 emoji sequence. + const rocketStart = msg3Bytes.indexOf(0xf0); + expect(rocketStart).toBeGreaterThan(0); + const splitPoint = rocketStart + 2; + + const input = yieldChunks([ + encoder.encode(msg1), + encoder.encode(msg2), + msg3Bytes.slice(0, splitPoint), + msg3Bytes.slice(splitPoint), + ]); + + const sink = createMemoryOutput(); + await runStdioServer(server, { input, output: sink.output }); + + const rawOut = sink.text(); + expect(rawOut.endsWith('\n')).toBe(true); + const lines = rawOut.slice(0, -1).split('\n'); + expect(lines).toHaveLength(2); + + const resp1 = JSON.parse(lines[0] ?? '') as { id: number; result: Record }; + const resp2 = JSON.parse(lines[1] ?? '') as { + id: string; + result: { content: { type: string; text: string }[] }; + }; + + expect(resp1.id).toBe(1); + expect(resp1.result).toEqual({}); + expect(resp2.id).toBe('utf8-2'); + expect(resp2.result.content[0]?.text).toBe('café-🚀-αβγ'); + }); + + test('preserves strict arrival order even when earlier async handler takes longer than later handler', async () => { + const delayedTool = defineMcpTool({ + name: 'delayed', + description: 'Resolves after deterministic microtask/timer delay.', + inputSchema: z.object({ tag: z.string(), delayMs: z.number().int().min(0) }).strict(), + async handler(input) { + await new Promise(resolve => { + setTimeout(resolve, input.delayMs); + }); + return { + content: [{ type: 'text', text: input.tag }], + }; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [delayedTool], + }); + + const payload = [ + JSON.stringify({ + jsonrpc: '2.0', + id: 'first-slow', + method: 'tools/call', + params: { name: 'delayed', arguments: { tag: 'first', delayMs: 25 } }, + }), + JSON.stringify({ + jsonrpc: '2.0', + id: 'second-fast', + method: 'tools/call', + params: { name: 'delayed', arguments: { tag: 'second', delayMs: 0 } }, + }), + ].join('\n'); + + const sink = createMemoryOutput(); + await runStdioServer(server, { + input: yieldChunks([`${payload}\n`]), + output: sink.output, + }); + + const lines = sink.text().trimEnd().split('\n'); + expect(lines).toHaveLength(2); + const first = JSON.parse(lines[0] ?? '') as { id: string }; + const second = JSON.parse(lines[1] ?? '') as { id: string }; + expect(first.id).toBe('first-slow'); + expect(second.id).toBe('second-fast'); + }); + + test('ignores blank lines, handles CRLF, and flushes a final non-newline-terminated line on EOF', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const input = yieldChunks([ + '\n \r\n', + `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\r\n`, + '\n', + JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' }), + ]); + + const sink = createMemoryOutput(); + await runStdioServer(server, { input, output: sink.output }); + + const lines = sink.text().trimEnd().split('\n'); + expect(lines).toHaveLength(2); + expect((JSON.parse(lines[0] ?? '') as { id: number }).id).toBe(1); + expect((JSON.parse(lines[1] ?? '') as { id: number }).id).toBe(2); + }); + + test('rejects oversized frames exceeding maxLineBytes with -32700 and recovers on the next line', async () => { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + }); + + const hugeLine = `{"jsonrpc":"2.0","id":1,"method":"ping","pad":"${'x'.repeat(300)}"}\n`; + const nextLine = `${JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' })}\n`; + + const sink = createMemoryOutput(); + await runStdioServer(server, { + input: yieldChunks([hugeLine, nextLine]), + output: sink.output, + maxLineBytes: 128, + }); + + const lines = sink.text().trimEnd().split('\n'); + expect(lines).toHaveLength(2); + const errResp = JSON.parse(lines[0] ?? '') as { + id: null; + error: { code: number }; + }; + const okResp = JSON.parse(lines[1] ?? '') as { id: number; result: Record }; + expect(errResp.id).toBeNull(); + expect(errResp.error.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); + expect(okResp.id).toBe(2); + expect(okResp.result).toEqual({}); + }); +}); From c48781811c6fa522ef85d2370d24dc97b050de33 Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 23:29:51 -0500 Subject: [PATCH 05/21] T-129: edits made in the worktree --- libs/research/src/mcp/protocol.ts | 37 +++++++++++++++++++++++++++---- libs/research/src/mcp/server.ts | 14 +++++------- 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/libs/research/src/mcp/protocol.ts b/libs/research/src/mcp/protocol.ts index f3d66d8c..fe7efcd6 100644 --- a/libs/research/src/mcp/protocol.ts +++ b/libs/research/src/mcp/protocol.ts @@ -113,6 +113,24 @@ export interface McpToolDescriptor { readonly inputSchema: JsonSchemaObject; } +/** Valid MCP progress token (`string | finite number`). */ +export const mcpProgressTokenSchema = z.union([z.string(), z.number().finite()]); +export type McpProgressToken = z.infer; + +/** Standard optional MCP `_meta` request/notification metadata bag. */ +export const mcpRequestMetaSchema = z + .object({ + progressToken: mcpProgressTokenSchema.optional(), + }) + .passthrough(); +export type McpRequestMeta = z.infer; + +const jsonObjectSchema = z.custom>( + (value): value is Record => + typeof value === 'object' && value !== null && !Array.isArray(value), + { message: 'Expected a JSON object.' } +); + /** Strict MCP `initialize` params schema. */ export const mcpInitializeParamsSchema = z .object({ @@ -125,27 +143,38 @@ export const mcpInitializeParamsSchema = z }) .strict() .optional(), + _meta: mcpRequestMetaSchema.optional(), }) .strict(); /** Strict MCP `notifications/initialized` params schema. */ -export const mcpInitializedNotificationParamsSchema = z.object({}).strict(); +export const mcpInitializedNotificationParamsSchema = z + .object({ + _meta: mcpRequestMetaSchema.optional(), + }) + .strict(); /** Strict MCP `ping` params schema. */ -export const mcpPingParamsSchema = z.object({}).strict(); +export const mcpPingParamsSchema = z + .object({ + _meta: mcpRequestMetaSchema.optional(), + }) + .strict(); /** Strict MCP `tools/list` params schema. */ export const mcpToolsListParamsSchema = z .object({ cursor: z.string().min(1).optional(), + _meta: mcpRequestMetaSchema.optional(), }) .strict(); -/** Strict MCP `tools/call` params schema. */ +/** Strict MCP `tools/call` params schema (preserves own keys on `arguments`). */ export const mcpToolsCallParamsSchema = z .object({ name: z.string().min(1), - arguments: z.record(z.unknown()).optional(), + arguments: jsonObjectSchema.optional(), + _meta: mcpRequestMetaSchema.optional(), }) .strict(); diff --git a/libs/research/src/mcp/server.ts b/libs/research/src/mcp/server.ts index 08a80b73..dec43185 100644 --- a/libs/research/src/mcp/server.ts +++ b/libs/research/src/mcp/server.ts @@ -320,17 +320,13 @@ function formatZodIssues(error: z.ZodError): string { return parts.join('; '); } +const SAFE_ERROR_NAME_RE = /^[A-Za-z][A-Za-z0-9_]{0,63}$/; + function sanitizeToolError(err: unknown): string { if (err instanceof Error) { - const rawName = typeof err.name === 'string' && err.name.trim().length > 0 ? err.name.trim() : 'Error'; - const firstLine = (typeof err.message === 'string' ? err.message : '') - .split(/\r?\n/, 1)[0] - ?.replace(/\s+at\s+\S.*$/u, '') - .trim(); - if (firstLine !== undefined && firstLine.length > 0) { - return `${rawName}: ${firstLine}`; - } - return `${rawName}: Tool execution failed.`; + const rawName = typeof err.name === 'string' ? err.name.trim() : ''; + const safeName = SAFE_ERROR_NAME_RE.test(rawName) ? rawName : 'Error'; + return `${safeName}: Tool execution failed.`; } return 'Error: Tool execution failed.'; } From 8d706b1039d7395aec5d3dbad0772059fafba57f Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 23:34:44 -0500 Subject: [PATCH 06/21] =?UTF-8?q?T-129:=20M2.1a=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20core:=20dependency-free=20JSON-RPC/MCP=20stdio=20server=20+?= =?UTF-8?q?=20tool=20registry=20+=20vault-fenced=20`query=5Fdata`=20in=20`?= =?UTF-8?q?libs/research/src/mcp/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/query-data.ts | 199 +++++++++++--- libs/research/test/mcp-protocol.test.ts | 136 +++++++++- libs/research/test/mcp-query-data.test.ts | 309 +++++++++++++++++++++- 3 files changed, 607 insertions(+), 37 deletions(-) diff --git a/libs/research/src/mcp/tools/query-data.ts b/libs/research/src/mcp/tools/query-data.ts index a336985e..5cfdc92a 100644 --- a/libs/research/src/mcp/tools/query-data.ts +++ b/libs/research/src/mcp/tools/query-data.ts @@ -10,6 +10,7 @@ import { } from '../../market-data-store'; import { AdjFactorsSnapshotError, + type AdjFactorsSnapshotErrorCode, MarketDataStoreNotImplementedError, } from '../../market-data-store-duckdb'; import type { McpToolCallResult } from '../protocol'; @@ -18,6 +19,9 @@ import { type McpToolEntry, defineMcpTool } from '../server'; const INT32_MIN = -2_147_483_648; const INT32_MAX = 2_147_483_647; const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; +const MS_PER_DAY = 86_400_000; +const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; +const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/; /** Default maximum number of bar rows returned by `query_data`. */ export const QUERY_DATA_DEFAULT_LIMIT = 500; @@ -109,39 +113,163 @@ export interface QueryDataResultPayload { readonly rows: readonly BarRecord[]; } +const SAFE_VALIDATION_FIELDS: ReadonlySet = new Set([ + 'from', + 'to', + 'asOf', + 'date', + 'ref', + 'listingIds', + 'timeframe', + 'adjustment', + 'scope', + 'limit', +]); + +const SAFE_STORE_METHODS: ReadonlySet = new Set([ + 'bars', + 'crossSection', + 'fundamentalsAsOf', + 'events', + 'shortsAsOf', + 'macroAsOf', + 'fx', + 'universe', +]); + +const ADJ_SNAPSHOT_ERROR_MESSAGES: Readonly> = { + missing_snapshot: + 'Adjusted bars require a verified point-in-time fenced adj_factors snapshot.', + missing_metadata: 'Required adj_factors snapshot metadata is missing.', + invalid_metadata: 'adj_factors snapshot metadata is invalid.', + unsupported_version: 'adj_factors snapshot metadata version is unsupported.', + retrospective_rejected: + 'Retrospective adj_factors snapshots are rejected for point-in-time queries.', + incompatible_fence: + 'adj_factors snapshot fence does not match the query asOf or Vault cutoff.', + path_mismatch: 'adj_factors snapshot metadata does not match the configured artifact.', + unpinned_mutable_path: + 'Adjusted bars require a pinned or immutable adj_factors snapshot artifact.', +}; + function utcDateOf(epochMs: number): string { return new Date(epochMs).toISOString().slice(0, 10); } -function formatUtcIsoMs(epochMs: number): string { - return new Date(epochMs).toISOString(); +function extractExplicitSubMsMicros(raw: string): number { + const match = ISO_FRACTIONAL_RE.exec(raw); + if (match === null) { + return 0; + } + const frac = match[1] ?? ''; + if (frac.length <= 3) { + return 0; + } + const microDigits = frac.slice(3, 6).padEnd(3, '0'); + return Number(microDigits); } -function formatDomainError(err: Error): McpToolCallResult { - const firstLine = err.message - .split(/\r?\n/, 1)[0] - ?.replace(/\s+at\s+\S.*$/u, '') - .trim(); - const detail = firstLine !== undefined && firstLine.length > 0 ? firstLine : 'Query failed.'; - return { - content: [ - { - type: 'text', - text: `${err.name}: ${detail}`, - }, - ], - isError: true, - }; +function resolveToSubMsMicros(rawTo: string, clampedTo: boolean): number { + if (clampedTo || DATE_ONLY_RE.test(rawTo)) { + return 999; + } + return extractExplicitSubMsMicros(rawTo); } -function isMappedStoreError(err: unknown): err is Error { - return ( - err instanceof VaultHoldoutFenceError || - err instanceof VaultScopeNotAuthorizedError || - err instanceof MarketDataStoreValidationError || - err instanceof MarketDataStoreNotImplementedError || - err instanceof AdjFactorsSnapshotError - ); +function resolveAsOfSubMsMicros(rawAsOf: string | undefined, clampedAsOf: boolean): number { + if (clampedAsOf || rawAsOf === undefined || DATE_ONLY_RE.test(rawAsOf)) { + return 999; + } + return extractExplicitSubMsMicros(rawAsOf); +} + +function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { + const isoMs = new Date(epochMs).toISOString(); + if (subMsMicros === 0) { + return isoMs; + } + const extra = String(subMsMicros).padStart(3, '0'); + return `${isoMs.slice(0, -1)}${extra}Z`; +} + +function resolveCompletedUtcDate(epochMs: number, subMsMicros: number): string { + const dayStartMs = Math.floor(epochMs / MS_PER_DAY) * MS_PER_DAY; + const dayEndMs = dayStartMs + MS_PER_DAY - 1; + if (epochMs === dayEndMs && subMsMicros === 999) { + return utcDateOf(dayStartMs); + } + return utcDateOf(dayStartMs - MS_PER_DAY); +} + +function resolveUniverseDate( + toMs: number, + toSubMs: number, + asOfMs: number, + asOfSubMs: number +): string { + if (asOfMs < toMs || (asOfMs === toMs && asOfSubMs < toSubMs)) { + return resolveCompletedUtcDate(asOfMs, asOfSubMs); + } + return resolveCompletedUtcDate(toMs, toSubMs); +} + +function formatMappedStoreError(err: unknown): McpToolCallResult | null { + if (err instanceof VaultHoldoutFenceError) { + return { + content: [ + { + type: 'text', + text: 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.', + }, + ], + isError: true, + }; + } + + if (err instanceof VaultScopeNotAuthorizedError) { + return { + content: [ + { + type: 'text', + text: "VaultScopeNotAuthorizedError: Data scope 'vault_evaluation_only' is not permitted through MCP.", + }, + ], + isError: true, + }; + } + + if (err instanceof MarketDataStoreValidationError) { + const text = + err.field !== undefined && SAFE_VALIDATION_FIELDS.has(err.field) + ? `MarketDataStoreValidationError: Invalid query parameter "${err.field}".` + : 'MarketDataStoreValidationError: Query parameters failed store validation.'; + return { + content: [{ type: 'text', text }], + isError: true, + }; + } + + if (err instanceof MarketDataStoreNotImplementedError) { + const text = SAFE_STORE_METHODS.has(err.method) + ? `MarketDataStoreNotImplementedError: Store operation "${err.method}" is not supported for this query.` + : 'MarketDataStoreNotImplementedError: Requested store operation is not supported.'; + return { + content: [{ type: 'text', text }], + isError: true, + }; + } + + if (err instanceof AdjFactorsSnapshotError) { + const detail = Object.prototype.hasOwnProperty.call(ADJ_SNAPSHOT_ERROR_MESSAGES, err.code) + ? ADJ_SNAPSHOT_ERROR_MESSAGES[err.code] + : 'Adjusted bars snapshot verification failed.'; + return { + content: [{ type: 'text', text: `AdjFactorsSnapshotError: ${detail}` }], + isError: true, + }; + } + + return null; } function validateFactoryOptions(options: QueryDataToolOptions): void { @@ -206,12 +334,20 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry ); const effectiveLimit = input.limit; + const toSubMs = resolveToSubMsMicros(input.to, fenced.clampedTo); + const asOfSubMs = resolveAsOfSubMsMicros(input.asOf, fenced.clampedAsOf); let listingIds: number[]; if (input.universe !== undefined) { + const universeDate = resolveUniverseDate( + fenced.toMs, + toSubMs, + fenced.asOfMs, + asOfSubMs + ); const resolved = await store.universe({ ref: input.universe, - date: utcDateOf(fenced.toMs), + date: universeDate, }); if (resolved.length === 0) { const emptyPayload: QueryDataResultPayload = { @@ -238,10 +374,12 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry listingIds = [...(input.listingIds ?? [])]; } - const effectiveFencedTo = fenced.clampedTo ? formatUtcIsoMs(fenced.toMs) : input.to; + const effectiveFencedTo = fenced.clampedTo + ? formatUtcIsoWithMicros(fenced.toMs, 999) + : input.to; const effectiveFencedAsOf = fenced.clampedAsOf || input.asOf === undefined - ? formatUtcIsoMs(fenced.asOfMs) + ? formatUtcIsoWithMicros(fenced.asOfMs, 999) : input.asOf; const stream = store.bars({ @@ -297,8 +435,9 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry content: [{ type: 'text', text: JSON.stringify(payload) }], }; } catch (err: unknown) { - if (isMappedStoreError(err)) { - return formatDomainError(err); + const mapped = formatMappedStoreError(err); + if (mapped !== null) { + return mapped; } throw err; } diff --git a/libs/research/test/mcp-protocol.test.ts b/libs/research/test/mcp-protocol.test.ts index eb312d45..511a8f7e 100644 --- a/libs/research/test/mcp-protocol.test.ts +++ b/libs/research/test/mcp-protocol.test.ts @@ -250,13 +250,15 @@ describe('MCP protocol & server core', () => { expect(result.content[0]?.text).toContain('Invalid arguments for tool "echo_count"'); }); - test('throwing tool handler returns isError: true with sanitized error and zero stack trace', async () => { + test('throwing tool handler returns isError: true with sanitized error and zero stack trace or paths', async () => { const boomTool = defineMcpTool({ name: 'explode', description: 'Always throws an error.', inputSchema: z.object({}).strict(), handler() { - const err = new Error('Simulated backend failure\n at secretInternal (/srv/app/secret.ts:42:9)'); + const err = new Error( + 'Failed reading /mnt/data/stockbot/secret.parquet\n at secretInternal (/srv/app/secret.ts:42:9)' + ); err.name = 'BackendFailureError'; throw err; }, @@ -286,12 +288,140 @@ describe('MCP protocol & server core', () => { }; expect(result.isError).toBe(true); const text = result.content[0]?.text ?? ''; - expect(text).toBe('BackendFailureError: Simulated backend failure'); + expect(text).toBe('BackendFailureError: Tool execution failed.'); + expect(text).not.toContain('/mnt/data/stockbot'); expect(text).not.toContain('at '); expect(text).not.toContain('/srv/app/secret.ts'); expect(text).not.toContain('\n'); }); + test('accepts standard MCP _meta.progressToken on requests and rejects malformed _meta', async () => { + let calls = 0; + const echoTool = defineMcpTool({ + name: 'echo_msg', + description: 'Echoes a message.', + inputSchema: z.object({ msg: z.string() }).strict(), + handler(input) { + calls += 1; + return { content: [{ type: 'text', text: input.msg }] }; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [echoTool], + }); + + const initResp = parseResponse( + await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'm1', + method: 'initialize', + params: { + protocolVersion: MCP_PROTOCOL_VERSION, + _meta: { progressToken: 'init-tok' }, + }, + }) + ) + ); + expect(initResp.error).toBeUndefined(); + + const pingResp = parseResponse( + await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'm2', + method: 'ping', + params: { _meta: { progressToken: 42 } }, + }) + ) + ); + expect(pingResp.result).toEqual({}); + + const listResp = parseResponse( + await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'm3', + method: 'tools/list', + params: { _meta: { progressToken: 'list-tok', customFlag: true } }, + }) + ) + ); + expect(listResp.error).toBeUndefined(); + + const callResp = parseResponse( + await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'm4', + method: 'tools/call', + params: { + name: 'echo_msg', + arguments: { msg: 'hello' }, + _meta: { progressToken: 'call-tok-1' }, + }, + }) + ) + ); + expect(calls).toBe(1); + expect(callResp.error).toBeUndefined(); + const callResult = callResp.result as { + isError?: boolean; + content: { type: string; text: string }[]; + }; + expect(callResult.isError).toBeUndefined(); + expect(callResult.content[0]?.text).toBe('hello'); + + // Invalid progressToken type -> -32602 before handler runs + const badMetaResp = parseResponse( + await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'm5', + method: 'tools/call', + params: { + name: 'echo_msg', + arguments: { msg: 'hello' }, + _meta: { progressToken: true }, + }, + }) + ) + ); + expect(calls).toBe(1); + expect(badMetaResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); + }); + + test('raw JSON own __proto__ key in tools/call arguments is preserved and rejected by strict tool schema', async () => { + let calls = 0; + const strictTool = defineMcpTool({ + name: 'strict_tool', + description: 'Accepts only x.', + inputSchema: z.object({ x: z.number() }).strict(), + handler(input) { + calls += 1; + return { content: [{ type: 'text', text: String(input.x) }] }; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [strictTool], + }); + + const rawRequest = + '{"jsonrpc":"2.0","id":"proto-check","method":"tools/call","params":{"name":"strict_tool","arguments":{"x":1,"__proto__":{"injected":true}}}}'; + const response = parseResponse(await server.handleMessage(rawRequest)); + expect(calls).toBe(0); + expect(response.error).toBeUndefined(); + const result = response.result as { isError?: boolean; content: { type: string; text: string }[] }; + expect(result.isError).toBe(true); + expect(result.content[0]?.text).toContain('Invalid arguments for tool "strict_tool"'); + }); + test('duplicate tool names throw at createMcpServer time and unsupported schemas fail fast', () => { const makeTool = () => defineMcpTool({ diff --git a/libs/research/test/mcp-query-data.test.ts b/libs/research/test/mcp-query-data.test.ts index 03722117..664e5c13 100644 --- a/libs/research/test/mcp-query-data.test.ts +++ b/libs/research/test/mcp-query-data.test.ts @@ -7,10 +7,15 @@ import { VaultScopeNotAuthorizedError, } from '../src/market-data-store'; import { + ADJ_SNAPSHOT_FORMAT_VERSION, + ADJ_SNAPSHOT_KV_PREFIX, AdjFactorsSnapshotError, type BarsQuery, + type DuckDbExecutor, + type DuckDbParam, MarketDataStoreNotImplementedError, type UniverseQuery, + createDuckDbMarketDataStore, } from '../src/market-data-store-duckdb'; import { QUERY_DATA_DEFAULT_LIMIT, @@ -439,12 +444,32 @@ describe('MCP query_data tool', () => { expect(emptyPayload.rows).toEqual([]); }); - test('maps store domain errors to isError: true naming the exact error class without stack traces', async () => { + test('maps store domain errors and unexpected errors without leaking paths or stack traces', async () => { const domainErrors: readonly [Error, string][] = [ [new VaultScopeNotAuthorizedError(), 'VaultScopeNotAuthorizedError'], - [new MarketDataStoreValidationError('Bad timeframe bound', 'from'), 'MarketDataStoreValidationError'], - [new MarketDataStoreNotImplementedError('bars', '1m not supported'), 'MarketDataStoreNotImplementedError'], - [new AdjFactorsSnapshotError('retrospective_rejected', 'Retrospective snapshot rejected'), 'AdjFactorsSnapshotError'], + [ + new MarketDataStoreValidationError( + 'Invalid curatedRoot "/mnt/data/stockbot/curated"', + 'curatedRoot' + ), + 'MarketDataStoreValidationError', + ], + [ + new MarketDataStoreValidationError('Bad from timestamp "/etc/passwd"', 'from'), + 'MarketDataStoreValidationError', + ], + [ + new MarketDataStoreNotImplementedError('bars', '1m not supported at /srv/secret/bars.parquet'), + 'MarketDataStoreNotImplementedError', + ], + [ + new AdjFactorsSnapshotError( + 'unpinned_mutable_path', + 'Refusing unpinned mutable adj_factors path "/mnt/data/stockbot/curated/adj_factors/part.parquet"', + '/mnt/data/stockbot/curated/adj_factors/part.parquet' + ), + 'AdjFactorsSnapshotError', + ], ]; for (const [err, expectedName] of domainErrors) { @@ -456,9 +481,285 @@ describe('MCP query_data tool', () => { }); expect(res.isError).toBe(true); expect(res.text).toContain(expectedName); + expect(res.text).not.toContain('/mnt/data/stockbot'); + expect(res.text).not.toContain('/srv/secret'); + expect(res.text).not.toContain('/etc/passwd'); + expect(res.text).not.toContain('part.parquet'); expect(res.text).not.toContain('\n'); expect(res.text).not.toContain('at '); } + + // Unexpected non-domain error containing a filesystem path on the first line + const unexpectedErr = new Error( + 'EACCES: permission denied, open /mnt/data/stockbot/curated/bars_1d/year=2025/part.parquet\n at open (/srv/app/store.ts:12:3)' + ); + const unexpectedFake = createFakeStore({ barsError: unexpectedErr }); + const unexpectedRes = await callQueryData(unexpectedFake, { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + }); + expect(unexpectedRes.isError).toBe(true); + expect(unexpectedRes.text).toBe('Error: Tool execution failed.'); + expect(unexpectedRes.text).not.toContain('/mnt/data/stockbot'); + expect(unexpectedRes.text).not.toContain('/srv/app/store.ts'); + }); + + test('universe lookup uses min(to, asOf) and completed UTC date so later trading cannot leak into earlier asOf', async () => { + const janBar101 = makeBar(101, Date.UTC(2025, 0, 15, 20, 0, 0), 100); + const janBar202 = makeBar(202, Date.UTC(2025, 0, 15, 20, 0, 0), 50); + const allBarsByListing = new Map([ + [101, [janBar101]], + [202, [janBar202]], + ]); + + const universeDates: string[] = []; + const store: MarketDataStore = { + async universe(q: UniverseQuery): Promise { + universeDates.push(q.date); + // Listing 202 resumed trading on 2025-03-26, so it is NOT active on 2025-03-03 + return q.date >= '2025-03-26' ? [101, 202] : [101]; + }, + bars(q: BarsQuery): AsyncIterable { + const rows = q.listingIds.flatMap(id => [...(allBarsByListing.get(id) ?? [])]); + return { + async *[Symbol.asyncIterator]() { + yield { rows }; + }, + }; + }, + crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; + + const fake: FakeStoreState = { barsCalls: [], universeCalls: [], store }; + + // Date-only asOf earlier than to -> universe queried on 2025-03-03, excluding listing 202 + const dateOnlyRes = await callQueryData(fake, { + universe: 'US_EQ', + from: '2025-01-01', + to: '2025-03-28', + asOf: '2025-03-03', + }); + expect(dateOnlyRes.isError).toBe(false); + expect(universeDates).toEqual(['2025-03-03']); + const payload = JSON.parse(dateOnlyRes.text) as QueryDataResultPayload; + expect(payload.rows).toEqual([janBar101]); + + // Intraday asOf on 2025-03-03 -> uses completed UTC date 2025-03-02 + const intradayRes = await callQueryData(fake, { + universe: 'US_EQ', + from: '2025-01-01', + to: '2025-03-28', + asOf: '2025-03-03T12:00:00Z', + }); + expect(intradayRes.isError).toBe(false); + expect(universeDates).toEqual(['2025-03-03', '2025-03-02']); + }); + + test('DuckDB planner integration preserves microsecond bounds, accepts matching fenced adj_factors snapshot, and sanitizes snapshot errors', async () => { + const recordedQueries: { sql: string; params: readonly DuckDbParam[] }[] = []; + const expectedVaultCeilingMicros = VAULT_CUTOFF_TS * 1000 - 1; + const barTs = Date.UTC(2025, 2, 20, 20, 0, 0); + + const executor: DuckDbExecutor = { + async run() { + // no-op in memory + }, + async query(sql, params) { + recordedQueries.push({ sql, params }); + if (sql.includes('parquet_kv_metadata')) { + return [ + { key: `${ADJ_SNAPSHOT_KV_PREFIX}format_version`, value: String(ADJ_SNAPSHOT_FORMAT_VERSION) }, + { key: `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_kind`, value: 'point_in_time_fenced' }, + { key: `${ADJ_SNAPSHOT_KV_PREFIX}as_of_micros`, value: 'none' }, + { key: `${ADJ_SNAPSHOT_KV_PREFIX}vault_cutoff_micros`, value: String(VAULT_CUTOFF_TS * 1000) }, + { key: `${ADJ_SNAPSHOT_KV_PREFIX}rows_written`, value: '10' }, + { key: `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_checksum`, value: '0x0123456789abcdef' }, + ]; + } + return [ + { + listing_id: 101, + ts: barTs, + open: 99, + high: 101, + low: 98, + close: 100, + volume: 2_000, + vwap: 100, + known_at: barTs, + }, + ]; + }, + }; + + const duckStore = createDuckDbMarketDataStore({ + curatedRoot: '/mnt/data/stockbot/curated', + vaultCutoffTs: VAULT_CUTOFF_TS, + immutableAdjFactorsPath: '/mnt/data/stockbot/curated/snapshots/adj_2025_03_30.parquet', + executor, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: duckStore, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + ], + }); + + // 1. Split-adjusted bars with omitted asOf and clamped to -> forwards .999999Z matching snapshot ceiling + const splitRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'duck-1', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [101], + from: '2025-03-01', + to: '2025-04-15', + adjustment: 'split', + }, + }, + }) + ); + const splitResp = JSON.parse(splitRaw as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(splitResp.result.isError).toBeUndefined(); + const splitPayload = JSON.parse(splitResp.result.content[0]?.text ?? '{}') as QueryDataResultPayload; + expect(splitPayload.rowCount).toBe(1); + expect(expectedVaultCeilingMicros).toBe(Date.UTC(2025, 2, 30, 23, 59, 59, 999) * 1000 + 999); + const barsQuery1 = recordedQueries.find(q => q.sql.includes('bars_1d')); + expect(barsQuery1).toBeDefined(); + expect(barsQuery1?.params).toEqual([ + 101, + '2025-03-30T23:59:59.999999Z', + 101, + '2025-03-01T00:00:00.000Z', + '2025-03-30T23:59:59.999999Z', + '2025-03-30T23:59:59.999999Z', + ]); + + // 2. Caller-supplied sub-millisecond bounds within the fence are preserved verbatim + recordedQueries.length = 0; + const preciseRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'duck-2', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [101], + from: '2025-03-01T00:00:00.000123Z', + to: '2025-03-20T12:34:56.123456Z', + asOf: '2025-03-25T08:09:10.654321Z', + adjustment: 'raw', + }, + }, + }) + ); + const preciseResp = JSON.parse(preciseRaw as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(preciseResp.result.isError).toBeUndefined(); + const barsQuery2 = recordedQueries.find(q => q.sql.includes('bars_1d')); + expect(barsQuery2?.params).toEqual([ + 101, + '2025-03-01T00:00:00.000123Z', + '2025-03-20T12:34:56.123456Z', + '2025-03-25T08:09:10.654321Z', + ]); + + // 3. Unpinned mutable adj_factors path fails closed without leaking internal filesystem path + const unpinnedStore = createDuckDbMarketDataStore({ + curatedRoot: '/mnt/data/stockbot/curated', + vaultCutoffTs: VAULT_CUTOFF_TS, + executor, + }); + const unpinnedServer = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: unpinnedStore, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + ], + }); + const unpinnedRaw = await unpinnedServer.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'duck-3', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + adjustment: 'split', + }, + }, + }) + ); + const unpinnedResp = JSON.parse(unpinnedRaw as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(unpinnedResp.result.isError).toBe(true); + const unpinnedText = unpinnedResp.result.content[0]?.text ?? ''; + expect(unpinnedText).toContain('AdjFactorsSnapshotError'); + expect(unpinnedText).not.toContain('/mnt/data/stockbot'); + expect(unpinnedText).not.toContain('part.parquet'); + }); + + test('raw JSON own __proto__ key in query_data arguments returns isError: true with zero store calls', async () => { + const fake = createFakeStore({ + batches: [{ rows: [makeBar(101, Date.UTC(2025, 2, 20, 20, 0, 0), 100)] }], + }); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: fake.store, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + ], + }); + + const rawRequest = + '{"jsonrpc":"2.0","id":"proto-q","method":"tools/call","params":{"name":"query_data","arguments":{"listingIds":[101],"from":"2025-03-01","to":"2025-03-30","__proto__":{"scope":"vault_evaluation_only"}}}}'; + const rawResponse = await server.handleMessage(rawRequest); + const parsed = JSON.parse(rawResponse as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(parsed.result.isError).toBe(true); + expect(fake.barsCalls).toHaveLength(0); + expect(fake.universeCalls).toHaveLength(0); }); test('repeated identical calls produce byte-identical JSON output', async () => { From 79b260aec5bd86a7f03d8621de8fd7fcc6f908c0 Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 23:42:15 -0500 Subject: [PATCH 07/21] T-129: tests --- libs/research/test/mcp-edge-cases.test.ts | 595 ++++++++++++++++++++++ 1 file changed, 595 insertions(+) create mode 100644 libs/research/test/mcp-edge-cases.test.ts diff --git a/libs/research/test/mcp-edge-cases.test.ts b/libs/research/test/mcp-edge-cases.test.ts new file mode 100644 index 00000000..c20ec3c5 --- /dev/null +++ b/libs/research/test/mcp-edge-cases.test.ts @@ -0,0 +1,595 @@ +import { describe, expect, test } from 'bun:test'; +import { z } from 'zod'; +import { + type BarBatch, + type BarRecord, + type MarketDataStore, + VaultHoldoutFenceError, +} from '../src/market-data-store'; +import { + type BarsQuery, + MarketDataStoreNotImplementedError, + type UniverseQuery, +} from '../src/market-data-store-duckdb'; +import { + JSON_RPC_ERROR_CODES, + type JsonSchemaObject, + QUERY_DATA_MAX_LISTING_IDS, + type QueryDataResultPayload, + type StdioOutput, + createMcpServer, + createQueryDataTool, + defineMcpTool, + runStdioServer, + zodObjectToJsonSchema, +} from '../src/mcp/index'; + +// QA edge cases for T-129 (M2.1a MCP core) not covered by the programmer's suites. + +const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); + +interface ToolResult { + isError?: boolean; + content: { type: string; text: string }[]; +} + +interface RpcResponse { + id: string | number | null; + result?: unknown; + error?: { code: number; message: string }; +} + +function rpc(id: string | number, method: string, params?: unknown): string { + return JSON.stringify( + params === undefined ? { jsonrpc: '2.0', id, method } : { jsonrpc: '2.0', id, method, params } + ); +} + +function parse(raw: string | null): RpcResponse { + expect(raw).not.toBeNull(); + return JSON.parse(raw as string) as RpcResponse; +} + +function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { + return { + listingId, + ts, + open: close, + high: close, + low: close, + close, + volume: 1, + vwap: close, + knownAt, + }; +} + +interface RecordingStore { + readonly store: MarketDataStore; + readonly barsCalls: BarsQuery[]; + readonly universeCalls: UniverseQuery[]; + readonly iteratorClosed: () => boolean; +} + +function createRecordingStore(options: { + batches?: readonly BarBatch[]; + universeIds?: readonly number[]; + universeError?: Error; +}): RecordingStore { + const barsCalls: BarsQuery[] = []; + const universeCalls: UniverseQuery[] = []; + let closed = false; + const store: MarketDataStore = { + bars(q: BarsQuery): AsyncIterable { + barsCalls.push(q); + const batches = options.batches ?? []; + return { + async *[Symbol.asyncIterator]() { + try { + for (const batch of batches) { + yield batch; + } + } finally { + closed = true; + } + }, + }; + }, + async universe(q: UniverseQuery): Promise { + universeCalls.push(q); + if (options.universeError !== undefined) { + throw options.universeError; + } + return [...(options.universeIds ?? [])]; + }, + crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; + return { store, barsCalls, universeCalls, iteratorClosed: () => closed }; +} + +async function callQueryData( + rec: RecordingStore, + args: Record, + vaultCutoffTs = VAULT_CUTOFF_TS +): Promise<{ isError: boolean; text: string }> { + const server = createMcpServer({ + name: 'qa', + version: '0.0.0', + tools: [createQueryDataTool({ store: rec.store, vaultContext: { vaultCutoffTs } })], + }); + const resp = parse( + await server.handleMessage(rpc('q', 'tools/call', { name: 'query_data', arguments: args })) + ); + expect(resp.error).toBeUndefined(); + const result = resp.result as ToolResult; + return { isError: result.isError === true, text: result.content[0]?.text ?? '' }; +} + +function memoryOutput(): { output: StdioOutput; chunks: string[] } { + const chunks: string[] = []; + return { + chunks, + output: { + write(chunk: string): boolean { + chunks.push(chunk); + return true; + }, + }, + }; +} + +async function* chunksOf(chunks: readonly (string | Uint8Array)[]): AsyncGenerator { + for (const c of chunks) { + yield c; + } +} + +describe('MCP server edge cases (QA)', () => { + test('tools/call sent as a notification returns null and never runs the handler', async () => { + let calls = 0; + const tool = defineMcpTool({ + name: 'side_effect', + description: 'Counts invocations.', + inputSchema: z.object({}).strict(), + handler() { + calls += 1; + return { content: [{ type: 'text', text: 'ran' }] }; + }, + }); + const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + method: 'tools/call', + params: { name: 'side_effect', arguments: {} }, + }) + ); + + expect(raw).toBeNull(); + expect(calls).toBe(0); + }); + + test('tools/call with missing or array params returns -32602 echoing the id', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + for (const [id, params] of [ + [7, undefined], + ['arr', [{ name: 'x' }]], + [8, { arguments: {} }], + [9, { name: 'x', arguments: [1, 2] }], + ] as const) { + const resp = parse(await server.handleMessage(rpc(id, 'tools/call', params))); + expect(resp.id).toBe(id); + expect(resp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); + } + }); + + test('initialize with invalid params returns -32602 and does not crash', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const resp = parse( + await server.handleMessage(rpc('init', 'initialize', { clientInfo: { name: 5 } })) + ); + expect(resp.id).toBe('init'); + expect(resp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); + }); + + test('non-Error throws and errors with unsafe names are sanitized to a fixed message', async () => { + const throwString = defineMcpTool({ + name: 'throw_string', + description: 'Throws a string.', + inputSchema: z.object({}).strict(), + handler() { + throw '/srv/secret/path leaked'; + }, + }); + const throwBadName = defineMcpTool({ + name: 'throw_bad_name', + description: 'Throws an error whose name contains a path.', + inputSchema: z.object({}).strict(), + async handler() { + const err = new Error('boom /srv/secret/x.ts'); + err.name = '/srv/secret/x.ts'; + throw err; + }, + }); + const server = createMcpServer({ + name: 'qa', + version: '0.0.0', + tools: [throwString, throwBadName], + }); + + for (const [name, expected] of [ + ['throw_string', 'Error: Tool execution failed.'], + ['throw_bad_name', 'Error: Tool execution failed.'], + ] as const) { + const resp = parse(await server.handleMessage(rpc(name, 'tools/call', { name, arguments: {} }))); + const result = resp.result as ToolResult; + expect(result.isError).toBe(true); + expect(result.content[0]?.text).toBe(expected); + expect(result.content[0]?.text).not.toContain('/srv/secret'); + } + }); + + test('responses are single-line JSON even when tool text contains newlines', async () => { + const tool = defineMcpTool({ + name: 'multiline', + description: 'Returns multi-line text.', + inputSchema: z.object({}).strict(), + handler: () => ({ content: [{ type: 'text', text: 'line1\nline2\r\nline3' }] }), + }); + const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); + const raw = await server.handleMessage( + rpc(1, 'tools/call', { name: 'multiline', arguments: {} }) + ); + expect(raw).not.toContain('\n'); + expect(raw).not.toContain('\r'); + expect((parse(raw).result as ToolResult).content[0]?.text).toBe('line1\nline2\r\nline3'); + }); + + test('explicit jsonSchema override is emitted verbatim by tools/list', async () => { + const override: JsonSchemaObject = { + type: 'object', + properties: { q: { type: 'string', description: 'custom' } }, + required: ['q'], + additionalProperties: false, + }; + const tool = defineMcpTool({ + name: 'with_override', + description: 'Has a hand-written schema.', + inputSchema: z.object({ q: z.string() }).strict(), + jsonSchema: override, + handler: () => ({ content: [{ type: 'text', text: 'ok' }] }), + }); + const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); + const resp = parse(await server.handleMessage(rpc(1, 'tools/list'))); + const tools = (resp.result as { tools: { inputSchema: unknown }[] }).tools; + expect(tools[0]?.inputSchema).toEqual(override); + }); + + test('zod converter maps nullable, union, literal, exclusive bounds, defaults, arrays and refinements', () => { + const schema = z + .object({ + n: z.number().gt(0).lt(10).describe('open interval'), + s: z.string().length(3), + maybe: z.string().nullable(), + either: z.union([z.string(), z.number().int()]), + lit: z.literal('fixed'), + flag: z.boolean().default(false), + tags: z.array(z.string()).min(1).max(4).optional(), + }) + .strict() + .refine(() => true) + .describe('root'); + + const json = zodObjectToJsonSchema(schema); + + expect(json.type).toBe('object'); + expect(json.additionalProperties).toBe(false); + expect(json.description).toBe('root'); + expect(json.required).toEqual(['n', 's', 'maybe', 'either', 'lit']); + expect(json.properties.n).toEqual({ + type: 'number', + description: 'open interval', + exclusiveMinimum: 0, + exclusiveMaximum: 10, + }); + expect(json.properties.s).toEqual({ type: 'string', minLength: 3, maxLength: 3 }); + expect(json.properties.maybe).toEqual({ anyOf: [{ type: 'string' }, { type: 'null' }] }); + expect(json.properties.either).toEqual({ + anyOf: [{ type: 'string' }, { type: 'integer' }], + }); + expect(json.properties.lit).toEqual({ type: 'string', const: 'fixed' }); + expect(json.properties.flag).toEqual({ type: 'boolean', default: false }); + expect(json.properties.tags).toEqual({ + type: 'array', + items: { type: 'string' }, + minItems: 1, + maxItems: 4, + }); + + expect(() => zodObjectToJsonSchema(z.string())).toThrow(/must be a ZodObject/); + }); + + test('defineMcpTool and createMcpServer reject empty names/descriptions/versions', () => { + const base = { + inputSchema: z.object({}).strict(), + handler: () => ({ content: [{ type: 'text' as const, text: '' }] }), + }; + expect(() => defineMcpTool({ ...base, name: ' ', description: 'd' })).toThrow(); + expect(() => defineMcpTool({ ...base, name: 'n', description: '' })).toThrow(); + expect(() => createMcpServer({ name: '', version: '1' })).toThrow(); + expect(() => createMcpServer({ name: 'n', version: ' ' })).toThrow(); + }); +}); + +describe('MCP stdio edge cases (QA)', () => { + test('oversized frame spread across many chunks yields exactly one -32700 and recovers', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const pad = 'x'.repeat(100); + const sink = memoryOutput(); + + await runStdioServer(server, { + input: chunksOf([ + `{"jsonrpc":"2.0","id":1,"method":"ping","pad":"${pad}`, + pad, + pad, + `${pad}"}\n${rpc(2, 'ping')}\n`, + ]), + output: sink.output, + maxLineBytes: 64, + }); + + const lines = sink.chunks.join('').trimEnd().split('\n'); + expect(lines).toHaveLength(2); + const first = JSON.parse(lines[0] ?? '') as RpcResponse; + const second = JSON.parse(lines[1] ?? '') as RpcResponse; + expect(first.id).toBeNull(); + expect(first.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); + expect(second.id).toBe(2); + expect(second.result).toEqual({}); + }); + + test('oversized unterminated tail at EOF yields one -32700 and never dispatches it', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const sink = memoryOutput(); + await runStdioServer(server, { + input: chunksOf([`${rpc(1, 'ping')}\n`, `{"jsonrpc":"2.0","id":2,"method":"ping","p":"${'y'.repeat(200)}"}`]), + output: sink.output, + maxLineBytes: 128, + }); + const lines = sink.chunks.join('').trimEnd().split('\n'); + expect(lines).toHaveLength(2); + expect((JSON.parse(lines[0] ?? '') as RpcResponse).id).toBe(1); + const err = JSON.parse(lines[1] ?? '') as RpcResponse; + expect(err.id).toBeNull(); + expect(err.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); + }); + + test('malformed line between valid requests yields -32700 and processing continues in order', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const sink = memoryOutput(); + await runStdioServer(server, { + input: chunksOf([`${rpc('a', 'ping')}\n{oops\n${rpc('b', 'ping')}\n`]), + output: sink.output, + }); + const lines = sink.chunks.join('').trimEnd().split('\n').map(l => JSON.parse(l) as RpcResponse); + expect(lines.map(l => l.id)).toEqual(['a', null, 'b']); + expect(lines[1]?.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); + }); + + test('a stream of only notifications writes zero bytes', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const sink = memoryOutput(); + await runStdioServer(server, { + input: chunksOf([ + `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`, + `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: 1 } })}\n`, + ]), + output: sink.output, + }); + expect(sink.chunks).toEqual([]); + }); + + test('waits for drain when output.write signals backpressure before writing the next response', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + const events: string[] = []; + const output: StdioOutput = { + write(chunk: string): boolean { + events.push(`write:${(JSON.parse(chunk) as RpcResponse).id}`); + return false; + }, + once(_event: 'drain', listener: () => void) { + events.push('await-drain'); + queueMicrotask(() => { + events.push('drain'); + listener(); + }); + }, + }; + + await runStdioServer(server, { + input: chunksOf([`${rpc(1, 'ping')}\n${rpc(2, 'ping')}\n`]), + output, + }); + + expect(events).toEqual(['write:1', 'await-drain', 'drain', 'write:2', 'await-drain', 'drain']); + }); + + test('rejects non-positive or non-integer maxLineBytes', async () => { + const server = createMcpServer({ name: 'qa', version: '0.0.0' }); + for (const bad of [0, -1, 1.5, Number.NaN]) { + await expect( + runStdioServer(server, { input: chunksOf([]), output: memoryOutput().output, maxLineBytes: bad }) + ).rejects.toThrow(/maxLineBytes/); + } + }); +}); + +describe('MCP query_data edge cases (QA)', () => { + test('selector rules: both, neither, too many, or non-integer listingIds are rejected with zero store calls', async () => { + const tooMany = Array.from({ length: QUERY_DATA_MAX_LISTING_IDS + 1 }, (_, i) => i + 1); + const cases: Record[] = [ + { listingIds: [1], universe: 'US_EQ', from: '2025-03-01', to: '2025-03-10' }, + { from: '2025-03-01', to: '2025-03-10' }, + { listingIds: [], from: '2025-03-01', to: '2025-03-10' }, + { listingIds: tooMany, from: '2025-03-01', to: '2025-03-10' }, + { listingIds: [1.5], from: '2025-03-01', to: '2025-03-10' }, + { listingIds: [2_147_483_648], from: '2025-03-01', to: '2025-03-10' }, + { listingIds: [1], from: '2025-03-01', to: '2025-03-10', timeframe: '1w' }, + { listingIds: [1], from: '2025-03-01', to: '2025-03-10', limit: 2.5 }, + ]; + for (const args of cases) { + const rec = createRecordingStore({}); + const res = await callQueryData(rec, args); + expect(res.isError).toBe(true); + expect(res.text).toContain('Invalid arguments for tool "query_data"'); + expect(rec.barsCalls).toHaveLength(0); + expect(rec.universeCalls).toHaveLength(0); + } + + const okRec = createRecordingStore({}); + const ok = await callQueryData(okRec, { + listingIds: tooMany.slice(0, QUERY_DATA_MAX_LISTING_IDS), + from: '2025-03-01', + to: '2025-03-10', + }); + expect(ok.isError).toBe(false); + expect(okRec.barsCalls[0]?.listingIds).toHaveLength(QUERY_DATA_MAX_LISTING_IDS); + }); + + test('from after to maps to MarketDataStoreValidationError with zero store calls', async () => { + const rec = createRecordingStore({}); + const res = await callQueryData(rec, { listingIds: [1], from: '2025-03-10', to: '2025-03-01' }); + expect(res.isError).toBe(true); + expect(res.text).toBe('MarketDataStoreValidationError: Invalid query parameter "from".'); + expect(rec.barsCalls).toHaveLength(0); + }); + + test('exactly limit eligible rows across batches is not truncated; one more is truncated and closes the store stream', async () => { + const base = Date.UTC(2025, 0, 2); + const rowsA = [makeBar(1, base, 1), makeBar(1, base + 1, 2)]; + const rowsB = [makeBar(1, base + 2, 3)]; + + const exact = createRecordingStore({ batches: [{ rows: rowsA }, { rows: rowsB }] }); + const exactRes = await callQueryData(exact, { + listingIds: [1], + from: '2025-01-01', + to: '2025-03-01', + limit: 3, + }); + const exactPayload = JSON.parse(exactRes.text) as QueryDataResultPayload; + expect(exactPayload.rowCount).toBe(3); + expect(exactPayload.truncated).toBe(false); + + const more = createRecordingStore({ + batches: [{ rows: rowsA }, { rows: rowsB }, { rows: [makeBar(1, base + 3, 4)] }, { rows: [makeBar(1, base + 4, 5)] }], + }); + const moreRes = await callQueryData(more, { + listingIds: [1], + from: '2025-01-01', + to: '2025-03-01', + limit: 3, + }); + const morePayload = JSON.parse(moreRes.text) as QueryDataResultPayload; + expect(morePayload.rowCount).toBe(3); + expect(morePayload.truncated).toBe(true); + expect(morePayload.rows.map(r => r.close)).toEqual([1, 2, 3]); + expect(more.iteratorClosed()).toBe(true); + }); + + test('post-cutoff rows dropped by the fence do not count toward the limit or the truncated flag', async () => { + const pre = makeBar(1, Date.UTC(2025, 2, 10), 1); + const leaks = [ + makeBar(1, VAULT_CUTOFF_TS, 9), + makeBar(1, Date.UTC(2025, 2, 11), 9, VAULT_CUTOFF_TS + 5), + makeBar(1, Number.NaN, 9), + ]; + const rec = createRecordingStore({ batches: [{ rows: [pre, ...leaks] }] }); + const res = await callQueryData(rec, { listingIds: [1], from: '2025-03-01', to: '2025-04-30', limit: 1 }); + const payload = JSON.parse(res.text) as QueryDataResultPayload; + expect(payload.rows).toEqual([pre]); + expect(payload.truncated).toBe(false); + expect(res.text).not.toContain('"close":9'); + }); + + test('mid-day Vault cutoff: universe date is the last completed UTC day and bars bounds stay below the cutoff', async () => { + const midDayCutoff = Date.UTC(2025, 2, 31, 12, 0, 0, 0); + const rec = createRecordingStore({ + universeIds: [5], + batches: [{ rows: [makeBar(5, Date.UTC(2025, 2, 31, 11, 0), 1), makeBar(5, midDayCutoff, 2)] }], + }); + const res = await callQueryData( + rec, + { universe: 'US_EQ', from: '2025-03-01', to: '2025-04-30' }, + midDayCutoff + ); + expect(res.isError).toBe(false); + expect(rec.universeCalls).toEqual([{ ref: 'US_EQ', date: '2025-03-30' }]); + const q = rec.barsCalls[0]; + expect(q?.scope).toBe('vault_fenced'); + expect(q?.to).toBe('2025-03-31T11:59:59.999999Z'); + expect(q?.asOf).toBe('2025-03-31T11:59:59.999999Z'); + const payload = JSON.parse(res.text) as QueryDataResultPayload; + expect(payload.rows.every(r => r.ts < midDayCutoff && r.knownAt < midDayCutoff)).toBe(true); + expect(payload.rowCount).toBe(1); + }); + + test('in-fence date-only to with omitted asOf resolves universe on the to date', async () => { + const rec = createRecordingStore({ universeIds: [] }); + const res = await callQueryData(rec, { universe: 'CA_EQ', from: '2025-02-01', to: '2025-03-20' }); + expect(res.isError).toBe(false); + expect(rec.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2025-03-20' }]); + expect(rec.barsCalls).toHaveLength(0); + }); + + test('errors thrown by store.universe are mapped or sanitized and bars is never called', async () => { + const fenceRec = createRecordingStore({ + universeError: new VaultHoldoutFenceError('2025-04-01', VAULT_CUTOFF_TS + 1, VAULT_CUTOFF_TS), + }); + const fenceRes = await callQueryData(fenceRec, { universe: 'US_EQ', from: '2025-03-01', to: '2025-03-20' }); + expect(fenceRes.isError).toBe(true); + expect(fenceRes.text).toContain('VaultHoldoutFenceError'); + expect(fenceRec.barsCalls).toHaveLength(0); + + const crashRec = createRecordingStore({ + universeError: new Error('connect ECONNREFUSED postgres://user:pw@10.0.0.51:5432/trading_bot'), + }); + const crashRes = await callQueryData(crashRec, { universe: 'US_EQ', from: '2025-03-01', to: '2025-03-20' }); + expect(crashRes.isError).toBe(true); + expect(crashRes.text).toBe('Error: Tool execution failed.'); + expect(crashRes.text).not.toContain('postgres://'); + expect(crashRec.barsCalls).toHaveLength(0); + }); + + test('factory rejects invalid store and vault cutoff values eagerly', () => { + const rec = createRecordingStore({}); + for (const bad of [Number.NaN, Number.POSITIVE_INFINITY, 1.5, 8_640_000_000_000_000]) { + expect(() => createQueryDataTool({ store: rec.store, vaultContext: { vaultCutoffTs: bad } })).toThrow( + /vaultCutoffTs/ + ); + } + expect(() => + createQueryDataTool({ + store: {} as MarketDataStore, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }) + ).toThrow(/store/); + }); +}); From 58658ff163ff91b0559742ad8a0af952622abf75 Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 15:49:29 -0500 Subject: [PATCH 08/21] =?UTF-8?q?T-130:=20M2.3a=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20`bars=5F1m`=20builder=20(`eodIntraday1M`=20ful?= =?UTF-8?q?l-bar=20split=20un-adjustment=20+=20PRE/RTH/POST=20session=20ta?= =?UTF-8?q?gging=20+=20session-close=20vs=20`bars=5F1d`=20cross-check)=20w?= =?UTF-8?q?ith=20tests=20and=20local=20benchmark=20(no=20new=20crates)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/bars_1m.rs | 711 ++++++++++++++++++ tools/curate-etl/src/bars_1m_tests.rs | 687 +++++++++++++++++ tools/curate-etl/src/bench.rs | 437 +++++++++++ tools/curate-etl/src/cli.rs | 32 +- tools/curate-etl/src/lib.rs | 14 +- tools/curate-etl/src/main.rs | 47 +- tools/curate-etl/src/session_close.rs | 292 ++++++- .../tests/session_close_qa_contract.rs | 5 +- 8 files changed, 2218 insertions(+), 7 deletions(-) create mode 100644 tools/curate-etl/src/bars_1m.rs create mode 100644 tools/curate-etl/src/bars_1m_tests.rs diff --git a/tools/curate-etl/src/bars_1m.rs b/tools/curate-etl/src/bars_1m.rs new file mode 100644 index 00000000..5161aa20 --- /dev/null +++ b/tools/curate-etl/src/bars_1m.rs @@ -0,0 +1,711 @@ +//! Pure, in-memory `bars_1m` intraday 1-minute bar builder (`eodIntraday1M` + `SplitTable`) +//! and `bars_1d` session-close cross-check. +//! +//! Produces sorted, unique per-`(key, ts)` rows with full OHLCV un-adjusted via +//! [`crate::split::unadjust_ohlcv`] using the cumulative split factor for each bar's **Eastern +//! Time session date** (strict `ex_date > session_date` boundary, matching +//! [`SplitTable::cum_factor_after`] bitwise), plus `PRE`/`RTH`/`POST` session tagging. +//! +//! Aligned with `design/DATA-CONTRACTS.md` (§1 `eodIntraday1M` and §B `bars_1m`): +//! - `eodIntraday1M` has both OHLC and volume retroactively split-adjusted, so +//! `raw_price = adj_price * factor` and `raw_volume = adj_volume / factor` (preserving dollar +//! volume `close * volume`). +//! - Session classification uses Eastern Time (`America/New_York` / `America/Toronto`) derived +//! from UTC microseconds via [`crate::session_close::utc_micros_to_et_local`]: +//! `PRE` (`< 09:30 ET`), `RTH` (`09:30..=15:59 ET`), `POST` (`>= 16:00 ET`). +//! - `vwap` and `known_at` are intentionally left to the downstream writer stage (ILP v2 / +//! QuestDB writer), keeping this module pure and I/O-free. +//! - Bad single rows never panic or abort the build; each failure category is dropped and counted +//! separately in [`Bars1mStats`]. + +use std::cmp::Ordering; +use std::collections::BinaryHeap; +use std::error::Error; +use std::fmt; +use std::hash::Hash; + +use crate::bars::{Bar1dRow, MAX_MISMATCH_SAMPLES}; +use crate::session_close::utc_micros_to_et_local; +use crate::split::{unadjust_ohlcv, OhlcvBar, SplitTable}; + +/// Canonical provenance label written to [`Bar1mRow::source`] for un-adjusted `eodIntraday1M` bars. +pub const BARS_1M_SOURCE_EOD: &str = "eod_unadj"; + +/// Regular Trading Hours start minute in Eastern Time (`09:30 ET` = `570`). +pub const RTH_START_MINUTE_ET: u16 = 9 * 60 + 30; + +/// Regular Trading Hours exclusive end minute in Eastern Time (`16:00 ET` = `960`). +pub const RTH_END_MINUTE_ET: u16 = 16 * 60; + +/// Intraday market session classification in Eastern Time (`America/New_York` / `America/Toronto`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum IntradaySession { + /// Pre-market (`00:00..09:30 ET`, i.e., `minute_of_day < 570`). + Pre, + /// Regular trading hours (`09:30..16:00 ET`, i.e., `570 <= minute_of_day < 960`). + Rth, + /// Post-market / after-hours (`16:00..24:00 ET`, i.e., `minute_of_day >= 960`). + Post, +} + +impl IntradaySession { + /// Returns the canonical `bars_1m.session` string tag (`"PRE"`, `"RTH"`, or `"POST"`). + #[inline] + pub const fn as_str(self) -> &'static str { + match self { + Self::Pre => "PRE", + Self::Rth => "RTH", + Self::Post => "POST", + } + } + + /// Classifies an Eastern Time minute-of-day (`0..=1439`) into [`IntradaySession`]. + #[inline] + pub const fn from_et_minute(minute_of_day: u16) -> Self { + if minute_of_day < RTH_START_MINUTE_ET { + Self::Pre + } else if minute_of_day < RTH_END_MINUTE_ET { + Self::Rth + } else { + Self::Post + } + } +} + +/// A single raw `eodIntraday1M` 1-minute bar input. +/// +/// Per `design/DATA-CONTRACTS.md` §1, both OHLC and `volume` are retroactively split-adjusted. +#[derive(Debug, Clone, PartialEq)] +pub struct EodIntradayBar { + pub key: K, + /// Bar start timestamp in UTC microseconds since the Unix epoch. + pub ts: i64, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + pub volume: f64, +} + +/// A single curated `bars_1m` row, sorted and unique by `(key, ts)`. +/// +/// Carries the `bars_1m` contract columns from `design/DATA-CONTRACTS.md` §B (`key`, `ts`, +/// raw un-adjusted OHLCV, `session`, `source`) plus the derived Eastern Time `session_date`. +/// Downstream writer columns (`vwap`, `known_at`) are intentionally left to the writer stage. +#[derive(Debug, Clone, PartialEq)] +pub struct Bar1mRow { + pub key: K, + /// Bar start timestamp in UTC microseconds since the Unix epoch. + pub ts: i64, + /// Local Eastern Time calendar date as days since `1970-01-01`. + pub session_date: i32, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + pub volume: f64, + pub session: IntradaySession, + pub source: &'static str, +} + +/// Summary counters produced alongside [`Bars1mBuild::rows`]. +/// +/// Conservation invariants: +/// - `bars_in == rows_out + dropped_invalid_ohlc + dropped_inconsistent_ohlc + dropped_invalid_volume + dropped_ts_out_of_range + duplicate_collapsed + duplicate_conflict_dropped` +/// - `pre_rows_out + rth_rows_out + post_rows_out == rows_out` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Bars1mStats { + pub bars_in: usize, + pub rows_out: usize, + pub keys_out: usize, + pub pre_rows_out: usize, + pub rth_rows_out: usize, + pub post_rows_out: usize, + pub dropped_invalid_ohlc: usize, + pub dropped_inconsistent_ohlc: usize, + pub dropped_invalid_volume: usize, + pub dropped_ts_out_of_range: usize, + pub duplicate_collapsed: usize, + pub duplicate_conflict_dropped: usize, +} + +/// Output of [`build_bars_1m`]: sorted, unique 1m rows and build statistics. +#[derive(Debug, Clone, PartialEq)] +pub struct Bars1mBuild { + pub rows: Vec>, + pub stats: Bars1mStats, +} + +/// Typed caller errors returned by [`check_session_closes`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Bars1mError { + /// Caller-supplied `rel_tolerance` was non-finite (`NaN`, `+/-inf`) or `< 0.0`. + InvalidTolerance { rel_tolerance: f64 }, +} + +impl fmt::Display for Bars1mError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::InvalidTolerance { rel_tolerance } => write!( + f, + "invalid relative tolerance {rel_tolerance}: must be finite and >= 0" + ), + } + } +} + +impl Error for Bars1mError {} + +/// Daily raw close reference used by [`check_session_closes`]. +#[derive(Debug, Clone, PartialEq)] +pub struct DailySessionClose { + pub key: K, + /// Session date as days since `1970-01-01` (Eastern / trading calendar date). + pub session_date: i32, + pub close: f64, +} + +impl From> for DailySessionClose { + #[inline] + fn from(row: Bar1dRow) -> Self { + Self { + key: row.key, + session_date: row.session_date, + close: row.close, + } + } +} + +impl From<&Bar1dRow> for DailySessionClose { + #[inline] + fn from(row: &Bar1dRow) -> Self { + Self { + key: row.key.clone(), + session_date: row.session_date, + close: row.close, + } + } +} + +/// A single session-close cross-check mismatch sample retained for downstream reporting. +#[derive(Debug, Clone, PartialEq)] +pub struct SessionCloseMismatchSample { + pub key: K, + pub session_date: i32, + pub last_rth_ts: i64, + pub close_1m: f64, + pub close_1d: f64, + pub rel: f64, +} + +/// Summary counters and mismatch metrics produced by [`check_session_closes`]. +/// +/// Conservation invariants: +/// - `checked + unchecked == rth_sessions` +/// - `within_tolerance + mismatched == checked` +/// - `daily_rows_in == daily_unique_partners + daily_invalid_close_dropped + daily_duplicate_collapsed + daily_duplicate_conflict_dropped` +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct SessionCloseStats { + pub rth_sessions: usize, + pub checked: usize, + pub within_tolerance: usize, + pub mismatched: usize, + pub unchecked: usize, + pub max_rel_diff: f64, + pub daily_rows_in: usize, + pub daily_unique_partners: usize, + pub daily_invalid_close_dropped: usize, + pub daily_duplicate_collapsed: usize, + pub daily_duplicate_conflict_dropped: usize, +} + +/// Output of [`check_session_closes`]: summary statistics and capped worst mismatch samples. +#[derive(Debug, Clone, PartialEq)] +pub struct SessionCloseCheck { + pub stats: SessionCloseStats, + pub mismatch_samples: Vec>, +} + +#[inline] +fn is_valid_price(price: f64) -> bool { + price.is_finite() && price > 0.0 +} + +#[inline] +fn is_consistent_ohlc(open: f64, high: f64, low: f64, close: f64) -> bool { + high >= low && open >= low && open <= high && close >= low && close <= high +} + +struct ValidatedIntradayBar { + key: K, + ts: i64, + session_date: i32, + session: IntradaySession, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +} + +#[inline] +fn validated_bar_values_bit_eq( + a: &ValidatedIntradayBar, + b: &ValidatedIntradayBar, +) -> bool { + a.open.to_bits() == b.open.to_bits() + && a.high.to_bits() == b.high.to_bits() + && a.low.to_bits() == b.low.to_bits() + && a.close.to_bits() == b.close.to_bits() + && a.volume.to_bits() == b.volume.to_bits() +} + +/// Builds sorted, unique `bars_1m` rows from split-adjusted `eodIntraday1M` bars. +/// +/// - Validates each input bar without panicking in strict priority order: +/// `dropped_invalid_ohlc` -> `dropped_inconsistent_ohlc` -> `dropped_invalid_volume` -> +/// `dropped_ts_out_of_range`. +/// - Normalizes `-0.0` volume to `+0.0`, sorts surviving bars by `(key, ts)`, collapses +/// bitwise-identical `(key, ts)` duplicates (`duplicate_collapsed`), and drops conflicting +/// duplicate groups (`duplicate_conflict_dropped`). +/// - Looks up the cumulative split factor on the strict `ex_date > session_date` boundary using +/// each bar's **Eastern Time** `session_date`, un-adjusts full OHLCV via [`unadjust_ohlcv`], +/// and re-validates post-unadjust values against floating-point overflow/underflow. +/// - Tags each emitted row with [`IntradaySession`] (`PRE`/`RTH`/`POST`) and +/// [`BARS_1M_SOURCE_EOD`]. +pub fn build_bars_1m(bars: B, splits: &SplitTable) -> Bars1mBuild +where + K: Ord + Eq + Hash + Clone, + B: IntoIterator>, +{ + let bars_iter = bars.into_iter(); + let mut valid_bars: Vec> = Vec::with_capacity(bars_iter.size_hint().0); + let mut stats = Bars1mStats::default(); + + for bar in bars_iter { + stats.bars_in += 1; + + if !is_valid_price(bar.open) + || !is_valid_price(bar.high) + || !is_valid_price(bar.low) + || !is_valid_price(bar.close) + { + stats.dropped_invalid_ohlc += 1; + continue; + } + if !is_consistent_ohlc(bar.open, bar.high, bar.low, bar.close) { + stats.dropped_inconsistent_ohlc += 1; + continue; + } + if !bar.volume.is_finite() || bar.volume < 0.0 { + stats.dropped_invalid_volume += 1; + continue; + } + let Ok(et_local) = utc_micros_to_et_local(bar.ts) else { + stats.dropped_ts_out_of_range += 1; + continue; + }; + + let volume = if bar.volume == 0.0 { 0.0 } else { bar.volume }; + valid_bars.push(ValidatedIntradayBar { + key: bar.key, + ts: bar.ts, + session_date: et_local.session_date, + session: IntradaySession::from_et_minute(et_local.minute_of_day), + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume, + }); + } + + valid_bars.sort_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.ts.cmp(&b.ts))); + + let mut rows: Vec> = Vec::with_capacity(valid_bars.len()); + let total_valid = valid_bars.len(); + let mut idx = 0usize; + + while idx < total_valid { + let key_start = idx; + let key = valid_bars[key_start].key.clone(); + while idx < total_valid && valid_bars[idx].key == key { + idx += 1; + } + let key_end = idx; + + let key_splits = splits.splits_for(&key); + let mut split_idx = 0usize; + let key_rows_start = rows.len(); + + let mut bar_idx = key_start; + while bar_idx < key_end { + let ts = valid_bars[bar_idx].ts; + let group_start = bar_idx; + while bar_idx < key_end && valid_bars[bar_idx].ts == ts { + bar_idx += 1; + } + let group_end = bar_idx; + let group_len = group_end - group_start; + + let first = &valid_bars[group_start]; + let all_identical = valid_bars[group_start + 1..group_end] + .iter() + .all(|other| validated_bar_values_bit_eq(first, other)); + + if !all_identical { + stats.duplicate_conflict_dropped += group_len; + continue; + } + + stats.duplicate_collapsed += group_len - 1; + + // `session_date` is monotonically non-decreasing with UTC `ts` (DST transitions + // happen at 02:00 local, never crossing midnight), so this two-pointer scan matches + // `SplitTable::cum_factor_after(&key, first.session_date)` bitwise. + while split_idx < key_splits.len() + && key_splits[split_idx].ex_date <= first.session_date + { + split_idx += 1; + } + + let factor = key_splits.get(split_idx).map_or(1.0, |e| e.suffix_factor); + let mut unadj = unadjust_ohlcv( + OhlcvBar { + open: first.open, + high: first.high, + low: first.low, + close: first.close, + volume: first.volume, + }, + factor, + ); + + if !is_valid_price(unadj.open) + || !is_valid_price(unadj.high) + || !is_valid_price(unadj.low) + || !is_valid_price(unadj.close) + { + stats.dropped_invalid_ohlc += 1; + continue; + } + if !is_consistent_ohlc(unadj.open, unadj.high, unadj.low, unadj.close) { + stats.dropped_inconsistent_ohlc += 1; + continue; + } + if !unadj.volume.is_finite() || unadj.volume < 0.0 { + stats.dropped_invalid_volume += 1; + continue; + } + if unadj.volume == 0.0 { + unadj.volume = 0.0; + } + + match first.session { + IntradaySession::Pre => stats.pre_rows_out += 1, + IntradaySession::Rth => stats.rth_rows_out += 1, + IntradaySession::Post => stats.post_rows_out += 1, + } + + rows.push(Bar1mRow { + key: key.clone(), + ts, + session_date: first.session_date, + open: unadj.open, + high: unadj.high, + low: unadj.low, + close: unadj.close, + volume: unadj.volume, + session: first.session, + source: BARS_1M_SOURCE_EOD, + }); + } + + if rows.len() > key_rows_start { + stats.keys_out += 1; + } + } + + stats.rows_out = rows.len(); + Bars1mBuild { rows, stats } +} + +/// Wrapper ordering [`SessionCloseMismatchSample`] by desired output order: +/// `(rel DESC, key ASC, session_date ASC)`. +/// +/// In a max-heap ([`BinaryHeap`]), the *largest* element (smallest `rel`, or latest `(key, date)` +/// tie) sits at the top and is evicted when the heap exceeds [`MAX_MISMATCH_SAMPLES`]. Calling +/// [`BinaryHeap::into_sorted_vec`] then returns samples in ascending `Ord` order (worst mismatch +/// first). +struct HeapSessionCloseMismatch(SessionCloseMismatchSample); + +impl Ord for HeapSessionCloseMismatch { + #[inline] + fn cmp(&self, other: &Self) -> Ordering { + other + .0 + .rel + .total_cmp(&self.0.rel) + .then_with(|| self.0.key.cmp(&other.0.key)) + .then_with(|| self.0.session_date.cmp(&other.0.session_date)) + } +} + +impl PartialOrd for HeapSessionCloseMismatch { + #[inline] + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl PartialEq for HeapSessionCloseMismatch { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.cmp(other) == Ordering::Equal + } +} + +impl Eq for HeapSessionCloseMismatch {} + +struct LastRthBar<'a, K> { + key: &'a K, + session_date: i32, + ts: i64, + close: f64, +} + +fn collect_last_rth_bars(rows_1m: &[Bar1mRow]) -> Vec> { + let is_sorted = rows_1m.windows(2).all(|w| { + w[0].key + .cmp(&w[1].key) + .then_with(|| w[0].session_date.cmp(&w[1].session_date)) + .then_with(|| w[0].ts.cmp(&w[1].ts)) + != Ordering::Greater + }); + + if is_sorted { + let mut last_rth: Vec> = Vec::new(); + for row in rows_1m { + if row.session != IntradaySession::Rth { + continue; + } + if let Some(prev) = last_rth.last_mut() { + if prev.key == &row.key && prev.session_date == row.session_date { + prev.ts = row.ts; + prev.close = row.close; + continue; + } + } + last_rth.push(LastRthBar { + key: &row.key, + session_date: row.session_date, + ts: row.ts, + close: row.close, + }); + } + return last_rth; + } + + let mut rth_rows: Vec> = rows_1m + .iter() + .filter(|row| row.session == IntradaySession::Rth) + .map(|row| LastRthBar { + key: &row.key, + session_date: row.session_date, + ts: row.ts, + close: row.close, + }) + .collect(); + + rth_rows.sort_by(|a, b| { + a.key + .cmp(b.key) + .then_with(|| a.session_date.cmp(&b.session_date)) + .then_with(|| a.ts.cmp(&b.ts)) + }); + + let mut write_idx = 0usize; + let mut read_idx = 0usize; + while read_idx < rth_rows.len() { + let mut group_end = read_idx + 1; + while group_end < rth_rows.len() + && rth_rows[group_end].key == rth_rows[read_idx].key + && rth_rows[group_end].session_date == rth_rows[read_idx].session_date + { + group_end += 1; + } + let last_idx = group_end - 1; + if write_idx != last_idx { + rth_rows.swap(write_idx, last_idx); + } + write_idx += 1; + read_idx = group_end; + } + rth_rows.truncate(write_idx); + rth_rows +} + +/// Cross-checks the close of the last [`IntradaySession::Rth`] 1-minute bar per +/// `(key, session_date)` against raw daily `bars_1d` closes. +/// +/// - Returns [`Bars1mError::InvalidTolerance`] if `rel_tolerance` is non-finite or `< 0.0`. +/// - Selects the last `RTH` bar by max `ts` per `(key, session_date)` (handling early-close half +/// days cleanly while ignoring `PRE`/`POST` bars and excluding `PRE`/`POST`-only sessions). +/// - Uses an `O(N)` single-pass scan when `rows_1m` is already sorted by `(key, session_date, ts)` +/// and falls back to a deterministic sort otherwise. +/// - Filters invalid (`<= 0`, non-finite), collapses bitwise-identical duplicate, and drops +/// conflicting duplicate `bars_1d_closes` partners. +/// - Retains up to [`MAX_MISMATCH_SAMPLES`] worst mismatches ordered by +/// `(rel DESC, key ASC, session_date ASC)`. +pub fn check_session_closes( + rows_1m: &[Bar1mRow], + bars_1d_closes: I, + rel_tolerance: f64, +) -> Result, Bars1mError> +where + K: Ord + Clone, + D: Into>, + I: IntoIterator, +{ + if !rel_tolerance.is_finite() || rel_tolerance < 0.0 { + return Err(Bars1mError::InvalidTolerance { rel_tolerance }); + } + + let mut stats = SessionCloseStats::default(); + let last_rth = collect_last_rth_bars(rows_1m); + stats.rth_sessions = last_rth.len(); + + let daily_iter = bars_1d_closes.into_iter(); + let mut valid_daily: Vec> = Vec::with_capacity(daily_iter.size_hint().0); + for item in daily_iter { + let daily: DailySessionClose = item.into(); + stats.daily_rows_in += 1; + if !is_valid_price(daily.close) { + stats.daily_invalid_close_dropped += 1; + continue; + } + valid_daily.push(daily); + } + + valid_daily.sort_unstable_by(|a, b| { + a.key + .cmp(&b.key) + .then_with(|| a.session_date.cmp(&b.session_date)) + }); + + let mut write_idx = 0usize; + let mut read_idx = 0usize; + let daily_valid_len = valid_daily.len(); + while read_idx < daily_valid_len { + let mut group_end = read_idx + 1; + while group_end < daily_valid_len + && valid_daily[group_end].key == valid_daily[read_idx].key + && valid_daily[group_end].session_date == valid_daily[read_idx].session_date + { + group_end += 1; + } + let group_len = group_end - read_idx; + let first_bits = valid_daily[read_idx].close.to_bits(); + let all_identical = valid_daily[read_idx + 1..group_end] + .iter() + .all(|other| other.close.to_bits() == first_bits); + + if all_identical { + stats.daily_duplicate_collapsed += group_len - 1; + if write_idx != read_idx { + valid_daily.swap(write_idx, read_idx); + } + write_idx += 1; + } else { + stats.daily_duplicate_conflict_dropped += group_len; + } + read_idx = group_end; + } + valid_daily.truncate(write_idx); + stats.daily_unique_partners = valid_daily.len(); + + let mut daily_idx = 0usize; + let mut heap: BinaryHeap> = + BinaryHeap::with_capacity(MAX_MISMATCH_SAMPLES + 1); + + for rth in &last_rth { + while daily_idx < valid_daily.len() { + match valid_daily[daily_idx] + .key + .cmp(rth.key) + .then_with(|| valid_daily[daily_idx].session_date.cmp(&rth.session_date)) + { + Ordering::Less => daily_idx += 1, + Ordering::Equal | Ordering::Greater => break, + } + } + + if daily_idx < valid_daily.len() + && &valid_daily[daily_idx].key == rth.key + && valid_daily[daily_idx].session_date == rth.session_date + { + let close_1d = valid_daily[daily_idx].close; + daily_idx += 1; + stats.checked += 1; + + let rel = if is_valid_price(rth.close) { + (rth.close - close_1d).abs() / close_1d + } else { + f64::INFINITY + }; + let within = rel.is_finite() && rel <= rel_tolerance; + + if rel > stats.max_rel_diff { + stats.max_rel_diff = rel; + } + + if within { + stats.within_tolerance += 1; + } else { + stats.mismatched += 1; + + let should_insert = if heap.len() < MAX_MISMATCH_SAMPLES { + true + } else if let Some(worst_kept) = heap.peek() { + worst_kept + .0 + .rel + .total_cmp(&rel) + .then_with(|| rth.key.cmp(&worst_kept.0.key)) + .then_with(|| rth.session_date.cmp(&worst_kept.0.session_date)) + == Ordering::Less + } else { + false + }; + + if should_insert { + heap.push(HeapSessionCloseMismatch(SessionCloseMismatchSample { + key: rth.key.clone(), + session_date: rth.session_date, + last_rth_ts: rth.ts, + close_1m: rth.close, + close_1d, + rel, + })); + if heap.len() > MAX_MISMATCH_SAMPLES { + heap.pop(); + } + } + } + } else { + stats.unchecked += 1; + } + } + + let mismatch_samples: Vec> = + heap.into_sorted_vec().into_iter().map(|w| w.0).collect(); + + Ok(SessionCloseCheck { + stats, + mismatch_samples, + }) +} + +#[cfg(test)] +#[path = "bars_1m_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/bars_1m_tests.rs b/tools/curate-etl/src/bars_1m_tests.rs new file mode 100644 index 00000000..73d44e27 --- /dev/null +++ b/tools/curate-etl/src/bars_1m_tests.rs @@ -0,0 +1,687 @@ +use super::*; +use crate::bars::Bar1dRow; +use crate::session_close::{SESSION_MAX_SUPPORTED_UTC_MICROS, SESSION_MIN_SUPPORTED_UTC_MICROS}; +use crate::shorts::et_to_utc_micros; +use crate::split::{ymd_to_epoch_days, SplitEvent}; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn et_ts(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { + et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp") +} + +fn utc_ts(y: i32, m: u32, d: u32, hour: i64, minute: i64) -> i64 { + (i64::from(day(y, m, d)) * 86_400 + hour * 3_600 + minute * 60) * 1_000_000 +} + +fn bar_1m( + key: K, + ts: i64, + open: f64, + high: f64, + low: f64, + close: f64, + volume: f64, +) -> EodIntradayBar { + EodIntradayBar { + key, + ts, + open, + high, + low, + close, + volume, + } +} + +fn daily_row(key: K, session_date: i32, close: f64) -> Bar1dRow { + Bar1dRow { + key, + session_date, + open: close, + high: close, + low: close, + close, + volume: 100_000.0, + } +} + +fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { + let diff = (actual - expected).abs(); + let scale = expected.abs().max(1.0); + assert!( + diff <= rel_tol * scale, + "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" + ); +} + +fn assert_bars_1m_invariants(stats: &Bars1mStats) { + assert_eq!( + stats.bars_in, + stats.rows_out + + stats.dropped_invalid_ohlc + + stats.dropped_inconsistent_ohlc + + stats.dropped_invalid_volume + + stats.dropped_ts_out_of_range + + stats.duplicate_collapsed + + stats.duplicate_conflict_dropped, + "bars_1m conservation invariant failed: {stats:?}" + ); + assert_eq!( + stats.rows_out, + stats.pre_rows_out + stats.rth_rows_out + stats.post_rows_out, + "session breakdown != rows_out: {stats:?}" + ); +} + +fn assert_close_check_invariants(stats: &SessionCloseStats) { + assert_eq!( + stats.checked + stats.unchecked, + stats.rth_sessions, + "checked + unchecked != rth_sessions: {stats:?}" + ); + assert_eq!( + stats.within_tolerance + stats.mismatched, + stats.checked, + "within_tolerance + mismatched != checked: {stats:?}" + ); + assert_eq!( + stats.daily_rows_in, + stats.daily_unique_partners + + stats.daily_invalid_close_dropped + + stats.daily_duplicate_collapsed + + stats.daily_duplicate_conflict_dropped, + "daily partner conservation failed: {stats:?}" + ); +} + +#[test] +fn nexm_reverse_split_1_for_20_unadjusts_pre_split_preserves_ex_date_and_matches_bars_1d() { + let pre_day = day(2025, 6, 17); + let ex_date = day(2025, 6, 18); + let post_day = day(2025, 6, 19); + + let splits = SplitTable::from_events([( + "NEXM.V".to_string(), + SplitEvent { + ex_date, + ratio: 0.05, + }, + )]) + .unwrap(); + + // Adjusted 1m bars from eodIntraday1M: + // Pre-split close = 24.29 -> un-adjusted = 24.29 * 0.05 = 1.2145, volume = 5000 / 0.05 = 100_000. + let pre_open_bar = bar_1m( + "NEXM.V".to_string(), + et_ts(2025, 6, 17, 9, 30), + 24.00, + 24.60, + 23.80, + 24.20, + 2_000.0, + ); + let pre_close_bar = bar_1m( + "NEXM.V".to_string(), + et_ts(2025, 6, 17, 15, 59), + 24.20, + 24.40, + 24.10, + 24.29, + 5_000.0, + ); + let ex_bar = bar_1m( + "NEXM.V".to_string(), + et_ts(2025, 6, 18, 15, 59), + 24.10, + 24.50, + 23.90, + 24.30, + 12_500.0, + ); + let post_bar = bar_1m( + "NEXM.V".to_string(), + et_ts(2025, 6, 19, 15, 59), + 24.30, + 24.80, + 24.00, + 24.65, + 9_800.0, + ); + + let built = build_bars_1m( + [ + pre_open_bar.clone(), + pre_close_bar.clone(), + ex_bar.clone(), + post_bar.clone(), + ], + &splits, + ); + assert_bars_1m_invariants(&built.stats); + assert_eq!(built.rows.len(), 4); + assert_eq!(built.stats.keys_out, 1); + assert_eq!(built.stats.rth_rows_out, 4); + + // Pre-split close bar un-adjusted: price * 0.05, volume / 0.05, dollar volume invariant. + let pre_close_out = &built.rows[1]; + assert_eq!(pre_close_out.session_date, pre_day); + assert_eq!(pre_close_out.session, IntradaySession::Rth); + assert_eq!(pre_close_out.source, BARS_1M_SOURCE_EOD); + assert_rel_eq(pre_close_out.open, 1.21, 1e-12); + assert_rel_eq(pre_close_out.high, 1.22, 1e-12); + assert_rel_eq(pre_close_out.low, 1.205, 1e-12); + assert_rel_eq(pre_close_out.close, 1.2145, 1e-12); + assert_rel_eq(pre_close_out.volume, 100_000.0, 1e-12); + assert_rel_eq( + pre_close_out.close * pre_close_out.volume, + pre_close_bar.close * pre_close_bar.volume, + 1e-12, + ); + + // Ex-date and post-split bars must be bit-for-bit unchanged. + for (actual, expected) in [(&built.rows[2], &ex_bar), (&built.rows[3], &post_bar)] { + assert_eq!(actual.open.to_bits(), expected.open.to_bits()); + assert_eq!(actual.high.to_bits(), expected.high.to_bits()); + assert_eq!(actual.low.to_bits(), expected.low.to_bits()); + assert_eq!(actual.close.to_bits(), expected.close.to_bits()); + assert_eq!(actual.volume.to_bits(), expected.volume.to_bits()); + } + + // Raw bars_1d closes match within 0.5% (0 mismatches). + let daily_closes = [ + daily_row("NEXM.V".to_string(), pre_day, 1.215), // ~0.041% diff vs 1.2145 + daily_row("NEXM.V".to_string(), ex_date, 24.30), + daily_row("NEXM.V".to_string(), post_day, 24.65), + ]; + let check = check_session_closes(&built.rows, &daily_closes, 0.005).unwrap(); + assert_close_check_invariants(&check.stats); + assert_eq!(check.stats.rth_sessions, 3); + assert_eq!(check.stats.checked, 3); + assert_eq!(check.stats.within_tolerance, 3); + assert_eq!(check.stats.mismatched, 0); + assert_eq!(check.stats.unchecked, 0); + assert!(check.stats.max_rel_diff < 0.005); + assert!(check.mismatch_samples.is_empty()); +} + +#[test] +fn nvda_forward_split_10_for_1_unadjusts_pre_split_and_matches_bars_1d() { + let pre_day = day(2024, 6, 7); + let ex_date = day(2024, 6, 10); + let post_day = day(2024, 6, 11); + + let splits = SplitTable::from_events([( + "NVDA.US".to_string(), + SplitEvent { + ex_date, + ratio: 10.0, + }, + )]) + .unwrap(); + + // Pre-split adjusted 1m close = 120.888 -> raw = 1208.88; volume = 412_390 -> raw = 41_239. + let pre_bar = bar_1m( + "NVDA.US".to_string(), + et_ts(2024, 6, 7, 15, 59), + 120.50, + 121.00, + 120.40, + 120.888, + 412_390.0, + ); + let ex_bar = bar_1m( + "NVDA.US".to_string(), + et_ts(2024, 6, 10, 15, 59), + 121.50, + 121.95, + 121.40, + 121.79, + 350_000.0, + ); + let post_bar = bar_1m( + "NVDA.US".to_string(), + et_ts(2024, 6, 11, 15, 59), + 120.80, + 121.10, + 120.70, + 120.91, + 290_000.0, + ); + + let built = build_bars_1m([pre_bar.clone(), ex_bar.clone(), post_bar.clone()], &splits); + assert_bars_1m_invariants(&built.stats); + assert_eq!(built.rows.len(), 3); + + let pre_out = &built.rows[0]; + assert_rel_eq(pre_out.open, 1_205.0, 1e-12); + assert_rel_eq(pre_out.high, 1_210.0, 1e-12); + assert_rel_eq(pre_out.low, 1_204.0, 1e-12); + assert_rel_eq(pre_out.close, 1_208.88, 1e-12); + assert_rel_eq(pre_out.volume, 41_239.0, 1e-12); + assert_rel_eq( + pre_out.close * pre_out.volume, + pre_bar.close * pre_bar.volume, + 1e-12, + ); + + // Post-split unchanged bit-for-bit. + assert_eq!(built.rows[1].close.to_bits(), ex_bar.close.to_bits()); + assert_eq!(built.rows[1].volume.to_bits(), ex_bar.volume.to_bits()); + assert_eq!(built.rows[2].close.to_bits(), post_bar.close.to_bits()); + assert_eq!(built.rows[2].volume.to_bits(), post_bar.volume.to_bits()); + + let daily_closes = [ + daily_row("NVDA.US".to_string(), pre_day, 1_208.88), + daily_row("NVDA.US".to_string(), ex_date, 121.79), + daily_row("NVDA.US".to_string(), post_day, 120.91), + ]; + let check = check_session_closes(&built.rows, daily_closes, 0.005).unwrap(); + assert_close_check_invariants(&check.stats); + assert_eq!(check.stats.checked, 3); + assert_eq!(check.stats.within_tolerance, 3); + assert_eq!(check.stats.mismatched, 0); + assert!(check.mismatch_samples.is_empty()); +} + +#[test] +fn negative_non_vacuity_still_adjusted_pre_split_bars_fail_session_close_check() { + let pre_day = day(2025, 6, 17); + let ex_date = day(2025, 6, 18); + let empty_splits: SplitTable = SplitTable::default(); + + // Build with an empty split table so pre-split bar stays retroactively adjusted (24.29). + let built = build_bars_1m( + [ + bar_1m( + "NEXM.V".to_string(), + et_ts(2025, 6, 17, 15, 59), + 24.20, + 24.40, + 24.10, + 24.29, + 5_000.0, + ), + bar_1m( + "NEXM.V".to_string(), + et_ts(2025, 6, 18, 15, 59), + 24.10, + 24.50, + 23.90, + 24.30, + 12_500.0, + ), + ], + &empty_splits, + ); + + let daily_closes = [ + daily_row("NEXM.V".to_string(), pre_day, 1.2145), + daily_row("NEXM.V".to_string(), ex_date, 24.30), + ]; + let check = check_session_closes(&built.rows, daily_closes, 0.005).unwrap(); + assert_close_check_invariants(&check.stats); + assert_eq!(check.stats.checked, 2); + assert_eq!(check.stats.within_tolerance, 1); + assert_eq!(check.stats.mismatched, 1); + assert!( + check.stats.max_rel_diff > 0.005, + "expected max_rel_diff > 0.005, got {}", + check.stats.max_rel_diff + ); + assert_eq!(check.mismatch_samples.len(), 1); + assert_eq!(check.mismatch_samples[0].key, "NEXM.V"); + assert_eq!(check.mismatch_samples[0].session_date, pre_day); + assert_rel_eq(check.mismatch_samples[0].rel, 19.0, 1e-6); +} + +#[test] +fn session_tagging_boundaries_in_est_and_edt_and_utc_date_rollover_split_lookup() { + assert_eq!(IntradaySession::Pre.as_str(), "PRE"); + assert_eq!(IntradaySession::Rth.as_str(), "RTH"); + assert_eq!(IntradaySession::Post.as_str(), "POST"); + + // 1. EST (winter: 2025-01-15) and EDT (summer: 2024-06-10) session boundaries. + let splits_empty: SplitTable<&'static str> = SplitTable::default(); + let boundary_bars = [ + // EST (UTC-5): 09:29 ET = 14:29 UTC, 09:30 = 14:30, 15:59 = 20:59, 16:00 = 21:00 + bar_1m("EST", utc_ts(2025, 1, 15, 14, 29), 10.0, 10.5, 9.5, 10.1, 100.0), + bar_1m("EST", utc_ts(2025, 1, 15, 14, 30), 10.0, 10.5, 9.5, 10.2, 100.0), + bar_1m("EST", utc_ts(2025, 1, 15, 20, 59), 10.0, 10.5, 9.5, 10.3, 100.0), + bar_1m("EST", utc_ts(2025, 1, 15, 21, 0), 10.0, 10.5, 9.5, 10.4, 100.0), + // EDT (UTC-4): 09:29 ET = 13:29 UTC, 09:30 = 13:30, 15:59 = 19:59, 16:00 = 20:00 + bar_1m("EDT", utc_ts(2024, 6, 10, 13, 29), 10.0, 10.5, 9.5, 10.1, 100.0), + bar_1m("EDT", utc_ts(2024, 6, 10, 13, 30), 10.0, 10.5, 9.5, 10.2, 100.0), + bar_1m("EDT", utc_ts(2024, 6, 10, 19, 59), 10.0, 10.5, 9.5, 10.3, 100.0), + bar_1m("EDT", utc_ts(2024, 6, 10, 20, 0), 10.0, 10.5, 9.5, 10.4, 100.0), + ]; + let built = build_bars_1m(boundary_bars, &splits_empty); + assert_bars_1m_invariants(&built.stats); + assert_eq!(built.stats.pre_rows_out, 2); + assert_eq!(built.stats.rth_rows_out, 4); + assert_eq!(built.stats.post_rows_out, 2); + + let expected_sessions = [ + IntradaySession::Pre, + IntradaySession::Rth, + IntradaySession::Rth, + IntradaySession::Post, + ]; + for (idx, row) in built.rows.iter().enumerate() { + assert_eq!(row.session, expected_sessions[idx % 4], "row {idx}"); + } + + // 2. UTC date == ex_date while ET session_date == ex_date - 1 (both EDT and EST): + // must use ET session_date so the pre-split factor IS applied. + let edt_ex = day(2024, 6, 10); + let est_ex = day(2025, 1, 16); + let splits = SplitTable::from_events([ + ( + "EDT_ROLL".to_string(), + SplitEvent { + ex_date: edt_ex, + ratio: 10.0, + }, + ), + ( + "EST_ROLL".to_string(), + SplitEvent { + ex_date: est_ex, + ratio: 2.0, + }, + ), + ]) + .unwrap(); + + // 2024-06-10 00:30 UTC == 2024-06-09 20:30 EDT (POST, session_date = edt_ex - 1) + let edt_evening_ts = utc_ts(2024, 6, 10, 0, 30); + // 2025-01-16 00:30 UTC == 2025-01-15 19:30 EST (POST, session_date = est_ex - 1) + let est_evening_ts = utc_ts(2025, 1, 16, 0, 30); + + let rollover = build_bars_1m( + [ + bar_1m("EDT_ROLL".to_string(), edt_evening_ts, 12.0, 12.5, 11.5, 12.2, 1_000.0), + bar_1m("EST_ROLL".to_string(), est_evening_ts, 50.0, 51.0, 49.0, 50.5, 400.0), + ], + &splits, + ); + assert_bars_1m_invariants(&rollover.stats); + assert_eq!(rollover.rows.len(), 2); + + assert_eq!(rollover.rows[0].key, "EDT_ROLL"); + assert_eq!(rollover.rows[0].session_date, edt_ex - 1); + assert_eq!(rollover.rows[0].session, IntradaySession::Post); + assert_rel_eq(rollover.rows[0].close, 122.0, 1e-12); + assert_rel_eq(rollover.rows[0].volume, 100.0, 1e-12); + + assert_eq!(rollover.rows[1].key, "EST_ROLL"); + assert_eq!(rollover.rows[1].session_date, est_ex - 1); + assert_eq!(rollover.rows[1].session, IntradaySession::Post); + assert_rel_eq(rollover.rows[1].close, 101.0, 1e-12); + assert_rel_eq(rollover.rows[1].volume, 200.0, 1e-12); + + // 3. Fall-back DST repeated 01:30 ET hour (EDT 05:30 UTC vs EST 06:30 UTC on 2024-11-03): + // distinct UTC timestamps must NOT collide as duplicates. + let fall_edt = utc_ts(2024, 11, 3, 5, 30); + let fall_est = utc_ts(2024, 11, 3, 6, 30); + let fall_built = build_bars_1m( + [ + bar_1m("FALL", fall_est, 10.0, 10.2, 9.9, 10.1, 20.0), + bar_1m("FALL", fall_edt, 10.0, 10.3, 9.8, 10.2, 10.0), + ], + &splits_empty, + ); + assert_bars_1m_invariants(&fall_built.stats); + assert_eq!(fall_built.rows.len(), 2); + assert_eq!(fall_built.rows[0].ts, fall_edt); + assert_eq!(fall_built.rows[1].ts, fall_est); + assert_eq!(fall_built.rows[0].session_date, day(2024, 11, 3)); + assert_eq!(fall_built.rows[1].session_date, day(2024, 11, 3)); +} + +#[test] +fn drops_bad_rows_by_priority_handles_post_unadjust_overflow_underflow_and_duplicates() { + let base_ts = et_ts(2024, 5, 1, 10, 0); + let ex_date = day(2024, 6, 1); + + let splits = SplitTable::from_events([ + ( + 1_i32, + SplitEvent { + ex_date, + ratio: 1e-200, + }, + ), + ( + 2_i32, + SplitEvent { + ex_date, + ratio: 1e200, + }, + ), + ]) + .unwrap(); + + let minute = 60_000_000_i64; + let built = build_bars_1m( + [ + // Priority 1: invalid OHLC (also inconsistent / bad vol / bad ts to verify priority) + bar_1m(1, i64::MIN, f64::NAN, 10.0, 5.0, 8.0, -1.0), + bar_1m(1, base_ts + minute, 10.0, f64::INFINITY, 5.0, 8.0, 10.0), + bar_1m(1, base_ts + 2 * minute, 10.0, 12.0, 0.0, 8.0, 10.0), + bar_1m(1, base_ts + 3 * minute, 10.0, 12.0, 5.0, -1.0, 10.0), + // Priority 2: inconsistent OHLC (high < low, open/close out of [low, high]) + bar_1m(1, base_ts + 4 * minute, 10.0, 8.0, 9.0, 8.5, -5.0), + bar_1m(1, base_ts + 5 * minute, 4.0, 10.0, 5.0, 8.0, 10.0), + bar_1m(1, base_ts + 6 * minute, 11.0, 10.0, 5.0, 8.0, 10.0), + bar_1m(1, base_ts + 7 * minute, 8.0, 10.0, 5.0, 4.0, 10.0), + bar_1m(1, base_ts + 8 * minute, 8.0, 10.0, 5.0, 11.0, 10.0), + // Priority 3: invalid volume (NaN, Inf, negative) + bar_1m(1, base_ts + 9 * minute, 8.0, 10.0, 5.0, 8.0, f64::NAN), + bar_1m(1, base_ts + 10 * minute, 8.0, 10.0, 5.0, 8.0, f64::INFINITY), + bar_1m(1, base_ts + 11 * minute, 8.0, 10.0, 5.0, 8.0, -1.0), + // Priority 4: out-of-range ts (pre-1976, post-2030, i64::MIN, i64::MAX) + bar_1m(1, SESSION_MIN_SUPPORTED_UTC_MICROS - 1, 8.0, 10.0, 5.0, 8.0, 10.0), + bar_1m(1, SESSION_MAX_SUPPORTED_UTC_MICROS + 1, 8.0, 10.0, 5.0, 8.0, 10.0), + bar_1m(1, i64::MIN, 8.0, 10.0, 5.0, 8.0, 10.0), + bar_1m(1, i64::MAX, 8.0, 10.0, 5.0, 8.0, 10.0), + // Post-unadjust volume overflow (1e200 / 1e-200 -> Inf) -> dropped_invalid_volume + bar_1m(1, base_ts + 12 * minute, 8.0, 10.0, 5.0, 8.0, 1e200), + // Post-unadjust price underflow (1e-200 * 1e-200 -> 0.0) -> dropped_invalid_ohlc + bar_1m(1, base_ts + 13 * minute, 1e-200, 1e-200, 1e-200, 1e-200, 10.0), + // Post-unadjust price overflow (1e200 * 1e200 -> Inf) -> dropped_invalid_ohlc + bar_1m(2, base_ts + 14 * minute, 1e200, 1e200, 1e200, 1e200, 10.0), + // Exact duplicate triple (including -0.0 vs +0.0 volume) -> collapses to 1 row + bar_1m(3, base_ts, 10.0, 12.0, 9.0, 11.0, 0.0), + bar_1m(3, base_ts, 10.0, 12.0, 9.0, 11.0, -0.0), + bar_1m(3, base_ts, 10.0, 12.0, 9.0, 11.0, 0.0), + // Conflicting duplicate pair -> both dropped + bar_1m(3, base_ts + minute, 10.0, 12.0, 9.0, 11.0, 50.0), + bar_1m(3, base_ts + minute, 10.0, 12.0, 9.0, 11.01, 50.0), + ], + &splits, + ); + + assert_bars_1m_invariants(&built.stats); + assert_eq!(built.stats.bars_in, 24); + assert_eq!(built.stats.dropped_invalid_ohlc, 6); // 4 input + 1 underflow + 1 overflow + assert_eq!(built.stats.dropped_inconsistent_ohlc, 5); + assert_eq!(built.stats.dropped_invalid_volume, 4); // 3 input + 1 volume overflow + assert_eq!(built.stats.dropped_ts_out_of_range, 4); + assert_eq!(built.stats.duplicate_collapsed, 2); + assert_eq!(built.stats.duplicate_conflict_dropped, 2); + assert_eq!(built.stats.rows_out, 1); + assert_eq!(built.stats.keys_out, 1); + assert_eq!(built.rows[0].key, 3); + assert_eq!(built.rows[0].volume.to_bits(), 0.0_f64.to_bits()); +} + +#[test] +fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_and_errors() { + // 1. Invalid tolerances return Bars1mError::InvalidTolerance. + for bad_tol in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.001] { + let err = check_session_closes::, _>( + &[], + std::iter::empty(), + bad_tol, + ) + .unwrap_err(); + assert!(matches!(err, Bars1mError::InvalidTolerance { .. })); + assert!(err.source().is_none()); + assert!(err.to_string().contains("invalid relative tolerance")); + } + + // 2. Half-day early close (last RTH bar 12:59 ET, later POST bar ignored) + PRE/POST-only session. + let half_day = day(2024, 11, 29); // Day after US Thanksgiving + let post_only_day = day(2024, 12, 2); + let splits: SplitTable = SplitTable::default(); + + let built = build_bars_1m( + [ + bar_1m(1, et_ts(2024, 11, 29, 9, 30), 100.0, 101.0, 99.5, 100.5, 500.0), + bar_1m(1, et_ts(2024, 11, 29, 12, 59), 101.0, 101.5, 100.8, 101.25, 800.0), + // Later POST bar with a very different close must NOT be selected as RTH close. + bar_1m(1, et_ts(2024, 11, 29, 16, 15), 105.0, 106.0, 104.5, 105.5, 100.0), + // PRE/POST-only session must be excluded from rth_sessions. + bar_1m(1, et_ts(2024, 12, 2, 8, 0), 102.0, 103.0, 101.5, 102.5, 50.0), + bar_1m(1, et_ts(2024, 12, 2, 17, 0), 103.0, 104.0, 102.5, 103.5, 50.0), + ], + &splits, + ); + + // Reverse rows_1m to exercise the unsorted fallback path in check_session_closes. + let mut reversed_rows = built.rows.clone(); + reversed_rows.reverse(); + + let daily = [ + DailySessionClose { + key: 1, + session_date: half_day, + close: 101.25, + }, + DailySessionClose { + key: 1, + session_date: post_only_day, + close: 103.5, + }, + ]; + let sorted_check = check_session_closes(&built.rows, daily.clone(), 0.005).unwrap(); + let unsorted_check = check_session_closes(&reversed_rows, daily, 0.005).unwrap(); + assert_eq!(sorted_check, unsorted_check); + assert_close_check_invariants(&sorted_check.stats); + assert_eq!(sorted_check.stats.rth_sessions, 1); + assert_eq!(sorted_check.stats.checked, 1); + assert_eq!(sorted_check.stats.within_tolerance, 1); + assert_eq!(sorted_check.stats.mismatched, 0); + + // 3. Daily close hygiene (invalid, identical dup, conflicting dup) + >100 mismatch sample cap. + let base_day = day(2024, 1, 2); + let mut rows_1m_in = Vec::new(); + let mut daily_in = Vec::new(); + + // Session 0: exact match with identical daily duplicate -> collapses to 1 + rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 2, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0)); + daily_in.push(DailySessionClose { key: 1, session_date: base_day, close: 10.0 }); + daily_in.push(DailySessionClose { key: 1, session_date: base_day, close: 10.0 }); + + // Session 1: conflicting daily duplicate -> dropped -> unchecked + rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 3, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0)); + daily_in.push(DailySessionClose { key: 1, session_date: base_day + 1, close: 10.0 }); + daily_in.push(DailySessionClose { key: 1, session_date: base_day + 1, close: 10.5 }); + + // Session 2: invalid daily closes (NaN, <=0) -> dropped -> unchecked + rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 4, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0)); + daily_in.push(DailySessionClose { key: 1, session_date: base_day + 2, close: f64::NAN }); + daily_in.push(DailySessionClose { key: 1, session_date: base_day + 2, close: 0.0 }); + + // 110 mismatches across distinct days on key=2 (plus a tie on key=3 to verify tie-break order). + let start_day = day(2024, 2, 1); + for i in 0..110_i32 { + let d = start_day + i; + let ts = et_to_utc_micros(d, 15, 59, 0).unwrap(); + let close_1m = 100.0 + (i + 2) as f64; // rel = (i + 2) / 100 >= 0.02 > 0.005 + rows_1m_in.push(bar_1m(2, ts, close_1m, close_1m, close_1m, close_1m, 100.0)); + daily_in.push(DailySessionClose { + key: 2, + session_date: d, + close: 100.0, + }); + } + // Tie with highest rel (1.11) on key=3 vs key=2 -> key=2 must sort before key=3. + let tie_d = start_day + 109; + let tie_ts = et_to_utc_micros(tie_d, 15, 59, 0).unwrap(); + rows_1m_in.push(bar_1m(3, tie_ts, 211.0, 211.0, 211.0, 211.0, 100.0)); + daily_in.push(DailySessionClose { + key: 3, + session_date: tie_d, + close: 100.0, + }); + + let built_many = build_bars_1m(rows_1m_in, &splits); + let check_many = check_session_closes(&built_many.rows, daily_in, 0.005).unwrap(); + assert_close_check_invariants(&check_many.stats); + assert_eq!(check_many.stats.daily_invalid_close_dropped, 2); + assert_eq!(check_many.stats.daily_duplicate_collapsed, 1); + assert_eq!(check_many.stats.daily_duplicate_conflict_dropped, 2); + assert_eq!(check_many.stats.unchecked, 2); + assert_eq!(check_many.stats.mismatched, 111); + assert_eq!(check_many.mismatch_samples.len(), MAX_MISMATCH_SAMPLES); + + // Top two samples have rel == 1.11: key=2 before key=3. + assert_rel_eq(check_many.mismatch_samples[0].rel, 1.11, 1e-12); + assert_eq!(check_many.mismatch_samples[0].key, 2); + assert_rel_eq(check_many.mismatch_samples[1].rel, 1.11, 1e-12); + assert_eq!(check_many.mismatch_samples[1].key, 3); + + // Entire mismatch_samples slice is strictly ordered by (rel DESC, key ASC, session_date ASC). + for w in check_many.mismatch_samples.windows(2) { + let ord = w[1] + .rel + .total_cmp(&w[0].rel) + .then_with(|| w[0].key.cmp(&w[1].key)) + .then_with(|| w[0].session_date.cmp(&w[1].session_date)); + assert_eq!(ord, Ordering::Less, "samples out of order: {:?} vs {:?}", w[0], w[1]); + } +} + +#[test] +fn output_is_sorted_unique_and_deterministic_across_input_permutations() { + let splits = SplitTable::from_events([ + ( + "B".to_string(), + SplitEvent { + ex_date: day(2024, 6, 10), + ratio: 5.0, + }, + ), + ( + "A".to_string(), + SplitEvent { + ex_date: day(2024, 6, 12), + ratio: 0.25, + }, + ), + ]) + .unwrap(); + + let mut bars = vec![ + bar_1m("B".to_string(), et_ts(2024, 6, 10, 15, 59), 20.0, 21.0, 19.5, 20.5, 300.0), + bar_1m("A".to_string(), et_ts(2024, 6, 11, 9, 30), 40.0, 41.0, 39.0, 40.2, 100.0), + bar_1m("B".to_string(), et_ts(2024, 6, 7, 15, 59), 19.0, 20.0, 18.5, 19.8, 500.0), + bar_1m("A".to_string(), et_ts(2024, 6, 11, 9, 30), 40.0, 41.0, 39.0, 40.2, 100.0), + bar_1m("A".to_string(), et_ts(2024, 6, 12, 16, 0), 10.0, 10.5, 9.8, 10.1, 200.0), + ]; + + let forward = build_bars_1m(bars.clone(), &splits); + bars.reverse(); + let reversed = build_bars_1m(bars, &splits); + + assert_eq!(forward, reversed); + assert_bars_1m_invariants(&forward.stats); + for w in forward.rows.windows(2) { + let ord = w[0].key.cmp(&w[1].key).then_with(|| w[0].ts.cmp(&w[1].ts)); + assert_eq!(ord, Ordering::Less, "output not strictly sorted/unique"); + } +} diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 084869fd..48a448e5 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -16,6 +16,10 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume}; +use crate::bars_1m::{ + build_bars_1m, check_session_closes, Bars1mError, Bars1mStats, DailySessionClose, + EodIntradayBar, IntradaySession, SessionCloseStats, +}; use crate::bson_eod_prices::{decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats}; use crate::bson_qm_actions::{ decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, @@ -55,6 +59,7 @@ use crate::parquet_shorts::{ write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, }; use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable}; +use crate::session_close::{et_session_close_utc_micros, SESSION_MIN_SUPPORTED_UTC_MICROS}; use crate::shorts::{ add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, CeoShortReport, ShortsError, ShortsStats, SHORTS_DISSEMINATION_HOUR_ET, SHORTS_DISSEMINATION_MINUTE_ET, @@ -66,6 +71,7 @@ pub const DEFAULT_BENCH_ROWS: usize = 10_000_000; pub const DEFAULT_ADJ_BENCH_EVENTS: usize = 1_000_000; pub const DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 1_000_000; pub const DEFAULT_BARS_BENCH_ROWS: usize = 10_000_000; +pub const DEFAULT_BARS_1M_BENCH_ROWS: usize = 10_000_000; pub const DEFAULT_FX_BENCH_ROWS: usize = 20_000; pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000; pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000; @@ -105,6 +111,9 @@ const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57; const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70; const CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C049_AC71; const BARS_BENCH_SEED: u64 = 0x570C_4B07_BA45_1D00; +const BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_BA45_0100; +const BARS_1M_BENCH_KEY_COUNT: usize = 2_000; +const BARS_1M_BENCH_EVENT_COUNT: usize = 2_000; const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE; const SHORTS_BENCH_SEED: u64 = 0x570C_4B07_5404_7500; const EVENTS_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7500; @@ -689,6 +698,375 @@ pub fn run_bars_benchmark(rows: usize) -> Result { }) } +/// Summary metrics produced by [`run_bars_1m_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Bars1mBenchReport { + pub rows: usize, + pub key_count: usize, + pub split_event_count: usize, + pub daily_rows_in: usize, + pub rows_out: usize, + pub keys_out: usize, + pub mismatch_samples_out: usize, + pub build_elapsed_ms: f64, + pub check_elapsed_ms: f64, + pub total_elapsed_ms: f64, + pub rows_per_sec: f64, + pub ns_per_row: f64, + pub checksum: u64, + pub build_stats: Bars1mStats, + pub close_stats: SessionCloseStats, +} + +fn verify_bars_1m_bench_self_check() -> Result<(), Bars1mError> { + let nexm_ex = ymd_to_epoch_days(2025, 6, 18).unwrap_or(20_257); + let nvda_ex = ymd_to_epoch_days(2024, 6, 10).unwrap_or(19_884); + let splits = SplitTable::from_events([ + ( + "NEXM.V", + SplitEvent { + ex_date: nexm_ex, + ratio: 0.05, + }, + ), + ( + "NVDA.US", + SplitEvent { + ex_date: nvda_ex, + ratio: 10.0, + }, + ), + ]) + .expect("valid bench self-check splits"); + + let nexm_pre_ts = et_to_utc_micros(nexm_ex - 1, 15, 59, 0).expect("valid ET"); + let nexm_ex_ts = et_to_utc_micros(nexm_ex, 15, 59, 0).expect("valid ET"); + let nvda_pre_ts = et_to_utc_micros(nvda_ex - 3, 15, 59, 0).expect("valid ET"); + let nvda_ex_ts = et_to_utc_micros(nvda_ex, 15, 59, 0).expect("valid ET"); + let est_day = ymd_to_epoch_days(2025, 1, 15).expect("valid date"); + let est_pre_ts = et_to_utc_micros(est_day, 9, 29, 0).expect("valid ET"); + let est_rth_ts = et_to_utc_micros(est_day, 9, 30, 0).expect("valid ET"); + let est_post_ts = et_to_utc_micros(est_day, 16, 0, 0).expect("valid ET"); + + let built = build_bars_1m( + [ + EodIntradayBar { + key: "NEXM.V", + ts: nexm_pre_ts, + open: 24.0, + high: 24.5, + low: 23.9, + close: 24.29, + volume: 5_000.0, + }, + EodIntradayBar { + key: "NEXM.V", + ts: nexm_ex_ts, + open: 24.1, + high: 24.4, + low: 24.0, + close: 24.30, + volume: 10_000.0, + }, + EodIntradayBar { + key: "NVDA.US", + ts: nvda_pre_ts, + open: 120.5, + high: 121.0, + low: 120.4, + close: 120.888, + volume: 412_390.0, + }, + EodIntradayBar { + key: "NVDA.US", + ts: nvda_ex_ts, + open: 121.5, + high: 121.9, + low: 121.4, + close: 121.79, + volume: 300_000.0, + }, + EodIntradayBar { + key: "SESS", + ts: est_pre_ts, + open: 10.0, + high: 10.1, + low: 9.9, + close: 10.0, + volume: 100.0, + }, + EodIntradayBar { + key: "SESS", + ts: est_rth_ts, + open: 10.0, + high: 10.1, + low: 9.9, + close: 10.0, + volume: 100.0, + }, + EodIntradayBar { + key: "SESS", + ts: est_post_ts, + open: 10.0, + high: 10.1, + low: 9.9, + close: 10.0, + volume: 100.0, + }, + ], + &splits, + ); + + assert_eq!(built.rows.len(), 7, "self-check expected 7 bars"); + assert!( + (built.rows[0].close - 1.2145).abs() < 1e-9, + "NEXM.V pre-split self-check failed" + ); + assert_eq!(built.rows[1].close.to_bits(), 24.30_f64.to_bits()); + assert!( + (built.rows[2].close - 1_208.88).abs() < 1e-9, + "NVDA.US pre-split close self-check failed" + ); + assert!( + (built.rows[2].volume - 41_239.0).abs() < 1e-9, + "NVDA.US pre-split volume self-check failed" + ); + assert_eq!(built.rows[3].close.to_bits(), 121.79_f64.to_bits()); + assert_eq!(built.rows[4].session, IntradaySession::Pre); + assert_eq!(built.rows[5].session, IntradaySession::Rth); + assert_eq!(built.rows[6].session, IntradaySession::Post); + + let daily = [ + DailySessionClose { + key: "NEXM.V", + session_date: nexm_ex - 1, + close: 1.2145, + }, + DailySessionClose { + key: "NEXM.V", + session_date: nexm_ex, + close: 24.30, + }, + DailySessionClose { + key: "NVDA.US", + session_date: nvda_ex - 3, + close: 1_208.88, + }, + DailySessionClose { + key: "NVDA.US", + session_date: nvda_ex, + close: 121.79, + }, + ]; + let check = check_session_closes(&built.rows, daily, 0.005)?; + assert_eq!(check.stats.checked, 4, "self-check expected 4 checked sessions"); + assert_eq!(check.stats.mismatched, 0, "self-check expected 0 mismatches"); + Ok(()) +} + +/// Runs the fixed-seed `build_bars_1m` + `check_session_closes` benchmark for `rows` 1-minute bars. +/// +/// Executes a pre-timing correctness self-check (NEXM.V 1:20 reverse split, NVDA.US 10:1 forward +/// split, EST/EDT session tagging, and `check_session_closes`), then generates `rows` deterministic +/// multi-session EST/EDT 1m bars across `2_000` `i32` keys with forward/reverse splits, a small +/// share of invalid/inconsistent/out-of-range/duplicate bars, and daily close cross-check partners. +/// Times [`build_bars_1m`] and [`check_session_closes`] and returns throughput plus a deterministic +/// `u64` checksum. +pub fn run_bars_1m_benchmark(rows: usize) -> Result { + verify_bars_1m_bench_self_check()?; + + let min_date = ymd_to_epoch_days(2024, 1, 2).unwrap_or(19_724); + let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); + let date_span = (max_date - min_date + 1) as u64; + + let mut rng = SplitMix64::new(BARS_1M_BENCH_SEED); + + let mut split_events = Vec::with_capacity(BARS_1M_BENCH_EVENT_COUNT); + for _ in 0..BARS_1M_BENCH_EVENT_COUNT { + let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1; + let ex_date = min_date + (rng.next_u64() % date_span) as i32; + let ratio = SAMPLE_RATIOS[(rng.next_u64() % (SAMPLE_RATIOS.len() as u64)) as usize]; + split_events.push((key, SplitEvent { ex_date, ratio })); + } + let splits = SplitTable::from_events(split_events).unwrap_or_default(); + let split_event_count = splits.event_count(); + + let mut bars: Vec> = Vec::with_capacity(rows); + let mut daily_closes: Vec> = Vec::with_capacity(rows / 20 + 64); + + let mut last_valid: Option> = None; + for _ in 0..rows { + let roll = rng.next_u64() % 1_000; + if roll < 5 { + if let Some(prev) = last_valid.clone() { + bars.push(prev); + continue; + } + } else if roll < 7 { + if let Some(mut prev) = last_valid.clone() { + prev.close = (prev.close + 0.05).min(prev.high); + if prev.close.to_bits() == last_valid.as_ref().map_or(0, |b| b.close.to_bits()) { + prev.volume += 1.0; + } + bars.push(prev); + continue; + } + } + + let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1; + let session_date = min_date + (rng.next_u64() % date_span) as i32; + // 08:00..=19:59 ET (minutes 480..1200) -> spans PRE, RTH, and POST on both EST and EDT. + let et_minute = 480 + (rng.next_u64() % 720) as i64; + let close_1600_utc = et_session_close_utc_micros(session_date).unwrap_or(0); + let ts = close_1600_utc + (et_minute - 960) * 60_000_000; + + let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01; + let spread = ((rng.next_u64() % 300) + 5) as f64 * 0.01; + let high = low + spread; + let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); + let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); + let volume = ((rng.next_u64() % 500_000) + 10) as f64; + + let bar = match roll { + 7..=8 => EodIntradayBar { + key, + ts, + open: -1.0, + high, + low, + close, + volume, + }, + 9..=10 => EodIntradayBar { + key, + ts, + open, + high: low - 0.5, + low, + close, + volume, + }, + 11..=12 => EodIntradayBar { + key, + ts, + open, + high, + low, + close, + volume: -10.0, + }, + 13..=14 => EodIntradayBar { + key, + ts: SESSION_MIN_SUPPORTED_UTC_MICROS - 60_000_000, + open, + high, + low, + close, + volume, + }, + 15..=17 => { + let b = EodIntradayBar { + key, + ts, + open, + high, + low, + close, + volume: 0.0, + }; + last_valid = Some(b.clone()); + b + } + _ => { + let b = EodIntradayBar { + key, + ts, + open, + high, + low, + close, + volume, + }; + last_valid = Some(b.clone()); + if (570..960).contains(&et_minute) && (rng.next_u64() % 16) == 0 { + let factor = splits.cum_factor_after(&key, session_date); + let raw_close = close * factor; + let mismatch_roll = rng.next_u64() % 100; + let daily_close = if mismatch_roll == 0 { + raw_close * 1.05 + } else { + let jitter_bp = (rng.next_u64() % 41) as f64 - 20.0; // -0.20%..+0.20% + raw_close * (1.0 + jitter_bp * 0.0001) + }; + daily_closes.push(DailySessionClose { + key, + session_date, + close: daily_close, + }); + } + b + } + }; + bars.push(bar); + } + + let daily_rows_in = daily_closes.len(); + + let build_start = Instant::now(); + let built = build_bars_1m(bars, &splits); + let build_elapsed_secs = build_start.elapsed().as_secs_f64(); + + let check_start = Instant::now(); + let checked = check_session_closes(&built.rows, daily_closes, 0.005)?; + let check_elapsed_secs = check_start.elapsed().as_secs_f64(); + + let total_elapsed_secs = build_elapsed_secs + check_elapsed_secs; + let build_elapsed_ms = build_elapsed_secs * 1_000.0; + let check_elapsed_ms = check_elapsed_secs * 1_000.0; + let total_elapsed_ms = total_elapsed_secs * 1_000.0; + + let mut hash = 0u64; + for row in &built.rows { + hash = mix_u64(hash, row.key as u64); + hash = mix_u64(hash, row.ts as u64); + hash = mix_u64(hash, row.session_date as u64); + hash = mix_u64(hash, row.session as u64); + hash = mix_u64(hash, row.open.to_bits()); + hash = mix_u64(hash, row.high.to_bits()); + hash = mix_u64(hash, row.low.to_bits()); + hash = mix_u64(hash, row.close.to_bits()); + hash = mix_u64(hash, row.volume.to_bits()); + } + for sample in &checked.mismatch_samples { + hash = mix_u64(hash, sample.key as u64); + hash = mix_u64(hash, sample.session_date as u64); + hash = mix_u64(hash, sample.last_rth_ts as u64); + hash = mix_u64(hash, sample.close_1m.to_bits()); + hash = mix_u64(hash, sample.close_1d.to_bits()); + hash = mix_u64(hash, sample.rel.to_bits()); + } + let checksum = black_box(hash); + let (rows_per_sec, ns_per_row) = compute_rates(rows, total_elapsed_secs); + + Ok(Bars1mBenchReport { + rows, + key_count: BARS_1M_BENCH_KEY_COUNT, + split_event_count, + daily_rows_in, + rows_out: built.stats.rows_out, + keys_out: built.stats.keys_out, + mismatch_samples_out: checked.mismatch_samples.len(), + build_elapsed_ms, + check_elapsed_ms, + total_elapsed_ms, + rows_per_sec, + ns_per_row, + checksum, + build_stats: built.stats, + close_stats: checked.stats, + }) +} + /// Summary metrics produced by [`run_fx_benchmark`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct FxBenchReport { @@ -12539,4 +12917,63 @@ mod tests { assert_eq!(report.read_back_rows, 0); assert_eq!(report.checksum, 0); } + + #[test] + fn bars_1m_benchmark_small_run_is_deterministic_and_conserves_counts() { + let a = run_bars_1m_benchmark(5_000).unwrap(); + let b = run_bars_1m_benchmark(5_000).unwrap(); + + assert_eq!(a.rows, 5_000); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.build_stats, b.build_stats); + assert_eq!(a.close_stats, b.close_stats); + assert!(a.rows_out > 0); + assert!(a.build_stats.pre_rows_out > 0); + assert!(a.build_stats.rth_rows_out > 0); + assert!(a.build_stats.post_rows_out > 0); + assert!(a.build_stats.dropped_invalid_ohlc > 0); + assert!(a.build_stats.dropped_inconsistent_ohlc > 0); + assert!(a.build_stats.dropped_invalid_volume > 0); + assert!(a.build_stats.dropped_ts_out_of_range > 0); + assert!(a.close_stats.checked > 0); + + // Conservation invariants + assert_eq!( + a.build_stats.bars_in, + a.build_stats.rows_out + + a.build_stats.dropped_invalid_ohlc + + a.build_stats.dropped_inconsistent_ohlc + + a.build_stats.dropped_invalid_volume + + a.build_stats.dropped_ts_out_of_range + + a.build_stats.duplicate_collapsed + + a.build_stats.duplicate_conflict_dropped + ); + assert_eq!( + a.build_stats.rows_out, + a.build_stats.pre_rows_out + a.build_stats.rth_rows_out + a.build_stats.post_rows_out + ); + assert_eq!( + a.close_stats.checked + a.close_stats.unchecked, + a.close_stats.rth_sessions + ); + assert_eq!( + a.close_stats.within_tolerance + a.close_stats.mismatched, + a.close_stats.checked + ); + } + + #[test] + fn bars_1m_benchmark_zero_rows_handles_cleanly() { + let report = run_bars_1m_benchmark(0).unwrap(); + assert_eq!(report.rows, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.keys_out, 0); + assert_eq!(report.daily_rows_in, 0); + assert_eq!(report.mismatch_samples_out, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.ns_per_row, 0.0); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 73f35d58..64a26b81 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -8,7 +8,8 @@ use std::io; use std::path::{Path, PathBuf}; use crate::bench::{ - DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS, + DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_1M_BENCH_ROWS, DEFAULT_BARS_BENCH_ROWS, + DEFAULT_BENCH_ROWS, DEFAULT_BSON_EOD_PRICES_BENCH_ROWS, DEFAULT_BSON_QM_ACTIONS_BENCH_ROWS, DEFAULT_BSON_STREAM_BENCH_ROWS, DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_CURATE_ADJ_BENCH_EVENTS, DEFAULT_CURATE_ADJ_CMD_BENCH_EVENTS, @@ -70,6 +71,7 @@ pub enum CliAction { BenchAdj(usize), BenchCorporateActions(usize), BenchBars(usize), + BenchBars1m(usize), BenchFx(usize), BenchShorts(usize), BenchEvents(usize), @@ -128,6 +130,7 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-adj [events] Run fixed-seed adj_factors build benchmark (default: {DEFAULT_ADJ_BENCH_EVENTS})\n\ {name} bench-corporate-actions [events] Run fixed-seed corporate_actions build benchmark (default: {DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS})\n\ {name} bench-bars [rows] Run fixed-seed bars_1d build + cross-check benchmark (default: {DEFAULT_BARS_BENCH_ROWS})\n\ + {name} bench-bars-1m [rows] Run fixed-seed bars_1m build + session-close cross-check benchmark (default: {DEFAULT_BARS_1M_BENCH_ROWS})\n\ {name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\ {name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\ {name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\ @@ -173,6 +176,7 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-adj [events]\n\ {name} bench-corporate-actions [events]\n\ {name} bench-bars [rows]\n\ + {name} bench-bars-1m [rows]\n\ {name} bench-fx [rows]\n\ {name} bench-shorts [rows]\n\ {name} bench-events [rows]\n\ @@ -1462,6 +1466,14 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-bars", _, ..] => Err("too many arguments for bench-bars".to_string()), + ["bench-bars-1m"] => Ok(CliAction::BenchBars1m(DEFAULT_BARS_1M_BENCH_ROWS)), + ["bench-bars-1m", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchBars1m(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-bars-1m", _, ..] => Err("too many arguments for bench-bars-1m".to_string()), ["bench-fx"] => Ok(CliAction::BenchFx(DEFAULT_FX_BENCH_ROWS)), ["bench-fx", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchFx(n)), @@ -2088,6 +2100,7 @@ mod tests { assert!(full.contains("bench-adj")); assert!(full.contains("bench-corporate-actions")); assert!(full.contains("bench-bars")); + assert!(full.contains("bench-bars-1m")); assert!(full.contains("bench-fx")); assert!(full.contains("bench-shorts")); assert!(full.contains("bench-events")); @@ -2119,6 +2132,7 @@ mod tests { assert!(short.contains("bench-adj")); assert!(short.contains("bench-corporate-actions")); assert!(short.contains("bench-bars")); + assert!(short.contains("bench-bars-1m")); assert!(short.contains("bench-fx")); assert!(short.contains("bench-shorts")); assert!(short.contains("bench-events")); @@ -2146,6 +2160,22 @@ mod tests { assert!(short.contains("bench-curate-corporate-actions-cmd")); } + #[test] + fn parses_and_validates_bench_bars_1m_args() { + assert_eq!( + parse_args(&to_args(&["bench-bars-1m"])), + Ok(CliAction::BenchBars1m(DEFAULT_BARS_1M_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-bars-1m", "1000000"])), + Ok(CliAction::BenchBars1m(1_000_000)) + ); + assert!(parse_args(&to_args(&["bench-bars-1m", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-bars-1m", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-bars-1m", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-bars-1m", "10", "20"])).is_err()); + } + #[test] fn parses_and_validates_bench_curate_bars_args() { assert_eq!( diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 023e1f16..0af02987 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -2,6 +2,7 @@ pub mod adj; pub mod bars; +pub mod bars_1m; pub mod bench; pub mod bson_ceo_shorts; pub mod bson_eod_prices; @@ -36,6 +37,12 @@ pub use bars::{ build_bars_1d, Bar1dRow, Bars1dBuild, Bars1dStats, BarsError, EodDailyBar, QmRawVolume, VolumeMismatchSample, MAX_MISMATCH_SAMPLES, }; +pub use bars_1m::{ + build_bars_1m, check_session_closes, Bar1mRow, Bars1mBuild, Bars1mError, Bars1mStats, + DailySessionClose, EodIntradayBar, IntradaySession, SessionCloseCheck, + SessionCloseMismatchSample, SessionCloseStats, BARS_1M_SOURCE_EOD, RTH_END_MINUTE_ET, + RTH_START_MINUTE_ET, +}; pub use bson_ceo_shorts::{ decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD, @@ -141,9 +148,10 @@ pub use provider_mapping::{ ProviderMappingTable, }; pub use session_close::{ - et_session_close_utc_micros, SessionCloseError, SESSION_CLOSE_MAX_SUPPORTED_DATE, - SESSION_CLOSE_MAX_SUPPORTED_YEAR, SESSION_CLOSE_MIN_SUPPORTED_DATE, - SESSION_CLOSE_MIN_SUPPORTED_YEAR, + et_session_close_utc_micros, utc_micros_to_et_local, EtLocalDateTime, SessionCloseError, + SESSION_CLOSE_MAX_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_YEAR, + SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MIN_SUPPORTED_YEAR, + SESSION_MAX_SUPPORTED_UTC_MICROS, SESSION_MIN_SUPPORTED_UTC_MICROS, }; pub use shorts::{ add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index e54fba0a..aa9acace 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -4,7 +4,7 @@ use std::env; use std::process::ExitCode; use curate_etl::bench::{ - run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark, + run_adj_benchmark, run_bars_1m_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark, run_bson_qm_actions_benchmark, run_bson_stream_benchmark, run_corporate_actions_benchmark, run_curate_adj_benchmark, run_curate_adj_cmd_benchmark, run_curate_bars_benchmark, run_curate_bars_cmd_benchmark, run_curate_corporate_actions_benchmark, @@ -333,6 +333,51 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchBars1m(rows)) => { + let report = match run_bars_1m_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: bars_1m benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-bars-1m"); + println!( + " input: rows={} daily_closes={} splits={} keys={}", + report.rows, report.daily_rows_in, report.split_event_count, report.key_count + ); + println!( + " build: rows_out={} keys_out={} (pre={} rth={} post={}) build={:.2} ms check={:.2} ms total={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", + report.rows_out, + report.keys_out, + report.build_stats.pre_rows_out, + report.build_stats.rth_rows_out, + report.build_stats.post_rows_out, + report.build_elapsed_ms, + report.check_elapsed_ms, + report.total_elapsed_ms, + report.rows_per_sec, + report.ns_per_row, + report.checksum + ); + println!( + " stats: invalid_ohlc={} inconsistent_ohlc={} invalid_vol={} ts_oor={} dup_collapsed={} dup_conflict={} rth_sessions={} checked={} within_tol={} mismatched={} unchecked={} max_rel_diff={:.6} samples={}", + report.build_stats.dropped_invalid_ohlc, + report.build_stats.dropped_inconsistent_ohlc, + report.build_stats.dropped_invalid_volume, + report.build_stats.dropped_ts_out_of_range, + report.build_stats.duplicate_collapsed, + report.build_stats.duplicate_conflict_dropped, + report.close_stats.rth_sessions, + report.close_stats.checked, + report.close_stats.within_tolerance, + report.close_stats.mismatched, + report.close_stats.unchecked, + report.close_stats.max_rel_diff, + report.mismatch_samples_out + ); + ExitCode::SUCCESS + } Ok(CliAction::BenchFx(rows)) => { let report = run_fx_benchmark(rows); println!("curate-etl bench-fx"); diff --git a/tools/curate-etl/src/session_close.rs b/tools/curate-etl/src/session_close.rs index 49630836..1969073a 100644 --- a/tools/curate-etl/src/session_close.rs +++ b/tools/curate-etl/src/session_close.rs @@ -42,10 +42,37 @@ pub const SESSION_CLOSE_MIN_SUPPORTED_DATE: i32 = 2_191; /// Epoch day for `2030-12-31` (inclusive upper bound of [`et_session_close_utc_micros`]). pub const SESSION_CLOSE_MAX_SUPPORTED_DATE: i32 = 22_279; +const MICROS_PER_SECOND: i64 = 1_000_000; +const MICROS_PER_MINUTE: i64 = 60 * MICROS_PER_SECOND; +const MICROS_PER_HOUR: i64 = 3_600 * MICROS_PER_SECOND; +const MICROS_PER_DAY: i64 = 86_400 * MICROS_PER_SECOND; + +/// Inclusive lower bound in UTC microseconds for [`utc_micros_to_et_local`] +/// (`1976-01-01T00:00:00.000000 EST` = `1976-01-01T05:00:00.000000Z`). +pub const SESSION_MIN_SUPPORTED_UTC_MICROS: i64 = + SESSION_CLOSE_MIN_SUPPORTED_DATE as i64 * MICROS_PER_DAY + 5 * MICROS_PER_HOUR; + +/// Inclusive upper bound in UTC microseconds for [`utc_micros_to_et_local`] +/// (`2030-12-31T23:59:59.999999 EST` = `2031-01-01T04:59:59.999999Z`). +pub const SESSION_MAX_SUPPORTED_UTC_MICROS: i64 = + (SESSION_CLOSE_MAX_SUPPORTED_DATE as i64 + 1) * MICROS_PER_DAY + 5 * MICROS_PER_HOUR - 1; + const SUPPORTED_YEAR_COUNT: usize = (SESSION_CLOSE_MAX_SUPPORTED_YEAR - SESSION_CLOSE_MIN_SUPPORTED_YEAR + 1) as usize; -/// Typed error returned by [`et_session_close_utc_micros`]. +/// Eastern Time (`America/New_York` / `America/Toronto`) calendar date, minute-of-day, and DST +/// state returned by [`utc_micros_to_et_local`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct EtLocalDateTime { + /// Local Eastern calendar date as days since `1970-01-01`. + pub session_date: i32, + /// Local Eastern minute of day (`0..=1439`, i.e., `hour * 60 + minute`). + pub minute_of_day: u16, + /// `true` during EDT (`UTC-4`), `false` during EST (`UTC-5`). + pub is_edt: bool, +} + +/// Typed error returned by [`et_session_close_utc_micros`] and [`utc_micros_to_et_local`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SessionCloseError { /// The requested epoch day fell outside `[SESSION_CLOSE_MIN_SUPPORTED_DATE, SESSION_CLOSE_MAX_SUPPORTED_DATE]`. @@ -54,6 +81,12 @@ pub enum SessionCloseError { min_supported: i32, max_supported: i32, }, + /// The requested UTC timestamp fell outside `[SESSION_MIN_SUPPORTED_UTC_MICROS, SESSION_MAX_SUPPORTED_UTC_MICROS]`. + TimestampOutOfRange { + utc_micros: i64, + min_supported: i64, + max_supported: i64, + }, } impl fmt::Display for SessionCloseError { @@ -67,6 +100,14 @@ impl fmt::Display for SessionCloseError { f, "epoch day {epoch_day} is outside supported session-close range [{min_supported}, {max_supported}] ({SESSION_CLOSE_MIN_SUPPORTED_YEAR}-01-01..={SESSION_CLOSE_MAX_SUPPORTED_YEAR}-12-31)" ), + Self::TimestampOutOfRange { + utc_micros, + min_supported, + max_supported, + } => write!( + f, + "UTC timestamp {utc_micros} us is outside supported Eastern Time range [{min_supported}, {max_supported}] ({SESSION_CLOSE_MIN_SUPPORTED_YEAR}-01-01T05:00:00Z..=2031-01-01T04:59:59.999999Z)" + ), } } } @@ -152,6 +193,52 @@ pub fn et_session_close_utc_micros(epoch_day: i32) -> Result Result { + if !(SESSION_MIN_SUPPORTED_UTC_MICROS..=SESSION_MAX_SUPPORTED_UTC_MICROS).contains(&utc_micros) { + return Err(SessionCloseError::TimestampOutOfRange { + utc_micros, + min_supported: SESSION_MIN_SUPPORTED_UTC_MICROS, + max_supported: SESSION_MAX_SUPPORTED_UTC_MICROS, + }); + } + + // Bounds check above guarantees `est_micros >= 2191 * MICROS_PER_DAY > 0` without overflow. + let est_micros = utc_micros - 5 * MICROS_PER_HOUR; + let est_day = (est_micros / MICROS_PER_DAY) as i32; + let (year, _, _) = epoch_days_to_ymd(est_day); + let (dst_start, dst_end) = dst_bounds()[(year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize]; + + // Spring forward: 02:00:00 EST = 07:00:00 UTC on `dst_start`. + // Fall back: 02:00:00 EDT = 06:00:00 UTC on `dst_end`. + let dst_start_utc = i64::from(dst_start) * MICROS_PER_DAY + 7 * MICROS_PER_HOUR; + let dst_end_utc = i64::from(dst_end) * MICROS_PER_DAY + 6 * MICROS_PER_HOUR; + let is_edt = utc_micros >= dst_start_utc && utc_micros < dst_end_utc; + + let local_micros = if is_edt { + est_micros + MICROS_PER_HOUR + } else { + est_micros + }; + let session_date = (local_micros / MICROS_PER_DAY) as i32; + let rem_micros = local_micros - i64::from(session_date) * MICROS_PER_DAY; + let minute_of_day = (rem_micros / MICROS_PER_MINUTE) as u16; + + Ok(EtLocalDateTime { + session_date, + minute_of_day, + is_edt, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -307,4 +394,207 @@ mod tests { ); } } + + fn utc_micros(y: i32, m: u32, d: u32, h: i64, min: i64, sec: i64, us: i64) -> i64 { + let ep = day(y, m, d); + ((i64::from(ep) * 86_400 + h * 3_600 + min * 60 + sec) * 1_000_000) + us + } + + #[test] + fn utc_micros_to_et_local_round_trips_et_session_close_across_all_supported_days() { + for d in SESSION_CLOSE_MIN_SUPPORTED_DATE..=SESSION_CLOSE_MAX_SUPPORTED_DATE { + let close_utc = et_session_close_utc_micros(d).expect("in-range date"); + let local = utc_micros_to_et_local(close_utc).expect("in-range timestamp"); + assert_eq!(local.session_date, d, "session_date mismatch on day={d}"); + assert_eq!( + local.minute_of_day, + 16 * 60, + "16:00 ET minute mismatch on day={d}" + ); + let expected_edt = + (close_utc - i64::from(d) * MICROS_PER_DAY) == 20 * MICROS_PER_HOUR; + assert_eq!(local.is_edt, expected_edt, "DST flag mismatch on day={d}"); + } + } + + #[test] + fn utc_micros_to_et_local_handles_dst_transitions_across_all_three_eras() { + // (year, spring_month, spring_day, fall_month, fall_day) + let eras = [ + // Era 1 (1976..=1986): last Sun Apr -> last Sun Oct + (1976, 4, 25, 10, 31), + (1986, 4, 27, 10, 26), + // Era 2 (1987..=2006): 1st Sun Apr -> last Sun Oct (including 2003) + (1987, 4, 5, 10, 25), + (2003, 4, 6, 10, 26), + (2006, 4, 2, 10, 29), + // Era 3 (2007..=2030): 2nd Sun Mar -> 1st Sun Nov + (2007, 3, 11, 11, 4), + (2024, 3, 10, 11, 3), + (2030, 3, 10, 11, 3), + ]; + + for (y, sm, sd, fm, fd) in eras { + let spring_day = day(y, sm, sd); + // 06:59:59.999999 UTC -> 01:59:59.999999 EST + let before_spring = utc_micros(y, sm, sd, 6, 59, 59, 999_999); + assert_eq!( + utc_micros_to_et_local(before_spring).unwrap(), + EtLocalDateTime { + session_date: spring_day, + minute_of_day: 60 + 59, + is_edt: false, + }, + "before spring-forward in {y}" + ); + // 07:00:00.000000 UTC -> 03:00:00.000000 EDT (skips 02:xx) + let at_spring = utc_micros(y, sm, sd, 7, 0, 0, 0); + assert_eq!( + utc_micros_to_et_local(at_spring).unwrap(), + EtLocalDateTime { + session_date: spring_day, + minute_of_day: 3 * 60, + is_edt: true, + }, + "at spring-forward in {y}" + ); + + let fall_day = day(y, fm, fd); + // 05:59:59.999999 UTC -> 01:59:59.999999 EDT (first 01:59) + let before_fall = utc_micros(y, fm, fd, 5, 59, 59, 999_999); + assert_eq!( + utc_micros_to_et_local(before_fall).unwrap(), + EtLocalDateTime { + session_date: fall_day, + minute_of_day: 60 + 59, + is_edt: true, + }, + "before fall-back in {y}" + ); + // 06:00:00.000000 UTC -> 01:00:00.000000 EST (repeated 01:00) + let at_fall = utc_micros(y, fm, fd, 6, 0, 0, 0); + assert_eq!( + utc_micros_to_et_local(at_fall).unwrap(), + EtLocalDateTime { + session_date: fall_day, + minute_of_day: 60, + is_edt: false, + }, + "at fall-back in {y}" + ); + } + } + + #[test] + fn utc_micros_to_et_local_handles_utc_vs_et_midnight_crossovers() { + // Summer (EDT, UTC-4): 2024-06-10 00:30 UTC == 2024-06-09 20:30 EDT (previous calendar day) + assert_eq!( + utc_micros_to_et_local(utc_micros(2024, 6, 10, 0, 30, 0, 0)).unwrap(), + EtLocalDateTime { + session_date: day(2024, 6, 9), + minute_of_day: 20 * 60 + 30, + is_edt: true, + } + ); + // 2024-06-10 03:59:59.999999 UTC == 2024-06-09 23:59 EDT + assert_eq!( + utc_micros_to_et_local(utc_micros(2024, 6, 10, 3, 59, 59, 999_999)).unwrap(), + EtLocalDateTime { + session_date: day(2024, 6, 9), + minute_of_day: 23 * 60 + 59, + is_edt: true, + } + ); + // 2024-06-10 04:00:00.000000 UTC == 2024-06-10 00:00 EDT + assert_eq!( + utc_micros_to_et_local(utc_micros(2024, 6, 10, 4, 0, 0, 0)).unwrap(), + EtLocalDateTime { + session_date: day(2024, 6, 10), + minute_of_day: 0, + is_edt: true, + } + ); + + // Winter (EST, UTC-5): 2025-01-16 00:30 UTC == 2025-01-15 19:30 EST + assert_eq!( + utc_micros_to_et_local(utc_micros(2025, 1, 16, 0, 30, 0, 0)).unwrap(), + EtLocalDateTime { + session_date: day(2025, 1, 15), + minute_of_day: 19 * 60 + 30, + is_edt: false, + } + ); + // 2025-01-16 04:59:59.999999 UTC == 2025-01-15 23:59 EST + assert_eq!( + utc_micros_to_et_local(utc_micros(2025, 1, 16, 4, 59, 59, 999_999)).unwrap(), + EtLocalDateTime { + session_date: day(2025, 1, 15), + minute_of_day: 23 * 60 + 59, + is_edt: false, + } + ); + // 2025-01-16 05:00:00.000000 UTC == 2025-01-16 00:00 EST + assert_eq!( + utc_micros_to_et_local(utc_micros(2025, 1, 16, 5, 0, 0, 0)).unwrap(), + EtLocalDateTime { + session_date: day(2025, 1, 16), + minute_of_day: 0, + is_edt: false, + } + ); + } + + #[test] + fn utc_micros_to_et_local_bounds_and_out_of_range_errors() { + // Exact inclusive bounds + assert_eq!( + SESSION_MIN_SUPPORTED_UTC_MICROS, + utc_micros(1976, 1, 1, 5, 0, 0, 0) + ); + assert_eq!( + SESSION_MAX_SUPPORTED_UTC_MICROS, + utc_micros(2031, 1, 1, 4, 59, 59, 999_999) + ); + assert_eq!( + utc_micros_to_et_local(SESSION_MIN_SUPPORTED_UTC_MICROS).unwrap(), + EtLocalDateTime { + session_date: SESSION_CLOSE_MIN_SUPPORTED_DATE, + minute_of_day: 0, + is_edt: false, + } + ); + assert_eq!( + utc_micros_to_et_local(SESSION_MAX_SUPPORTED_UTC_MICROS).unwrap(), + EtLocalDateTime { + session_date: SESSION_CLOSE_MAX_SUPPORTED_DATE, + minute_of_day: 23 * 60 + 59, + is_edt: false, + } + ); + + let bad_ts = [ + SESSION_MIN_SUPPORTED_UTC_MICROS - 1, + SESSION_MAX_SUPPORTED_UTC_MICROS + 1, + 0, + i64::MIN, + i64::MAX, + ]; + for ts in bad_ts { + let err = utc_micros_to_et_local(ts).unwrap_err(); + assert_eq!( + err, + SessionCloseError::TimestampOutOfRange { + utc_micros: ts, + min_supported: SESSION_MIN_SUPPORTED_UTC_MICROS, + max_supported: SESSION_MAX_SUPPORTED_UTC_MICROS, + } + ); + assert!(err.source().is_none()); + let msg = err.to_string(); + assert!( + msg.contains(&ts.to_string()) && msg.contains("1976-01-01T05:00:00Z"), + "unexpected Display message: {msg}" + ); + } + } } diff --git a/tools/curate-etl/tests/session_close_qa_contract.rs b/tools/curate-etl/tests/session_close_qa_contract.rs index 7c93a8d4..d0a04c43 100644 --- a/tools/curate-etl/tests/session_close_qa_contract.rs +++ b/tools/curate-etl/tests/session_close_qa_contract.rs @@ -204,7 +204,10 @@ fn pre_1976_divergent_emergency_dst_years_and_post_2030_are_out_of_range() { epoch_day, min_supported, max_supported, - } = err; + } = err + else { + panic!("expected SessionCloseError::DateOutOfRange, got {err:?}"); + }; assert_eq!(epoch_day, d); assert_eq!(min_supported, SESSION_CLOSE_MIN_SUPPORTED_DATE); assert_eq!(max_supported, SESSION_CLOSE_MAX_SUPPORTED_DATE); From 3c949d532bebb5f1ec8eec6b9d73f17fe1a8cc85 Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 23:29:51 -0500 Subject: [PATCH 09/21] T-130: edits made in the worktree --- tools/curate-etl/src/bars_1m.rs | 228 +++++++++++++++++++------- tools/curate-etl/src/bars_1m_tests.rs | 207 +++++++++++++++++++---- tools/curate-etl/src/bench.rs | 157 ++++++++++++------ 3 files changed, 450 insertions(+), 142 deletions(-) diff --git a/tools/curate-etl/src/bars_1m.rs b/tools/curate-etl/src/bars_1m.rs index 5161aa20..b3dcd5a4 100644 --- a/tools/curate-etl/src/bars_1m.rs +++ b/tools/curate-etl/src/bars_1m.rs @@ -163,6 +163,44 @@ pub struct DailySessionClose { /// Session date as days since `1970-01-01` (Eastern / trading calendar date). pub session_date: i32, pub close: f64, + /// Optional exclusive Eastern Time session-close cutoff in UTC microseconds. + /// + /// When `Some(cutoff_ts)`, only [`IntradaySession::Rth`] bars with `ts < cutoff_ts` are + /// eligible as the session's closing bar (for example, `13:00:00 ET` on an early-close half + /// day so post-close prints between `13:00` and `15:59 ET` do not displace the `12:59 ET` + /// closing bar while [`Bar1mRow::session`] retains the fixed `PRE`/`RTH`/`POST` tags). + /// When `None`, defaults to the standard `16:00:00 ET` RTH boundary. + pub session_close_ts: Option, +} + +impl DailySessionClose { + /// Creates a daily close reference using the standard `16:00:00 ET` RTH cutoff. + #[inline] + pub const fn new(key: K, session_date: i32, close: f64) -> Self { + Self { + key, + session_date, + close, + session_close_ts: None, + } + } + + /// Creates a daily close reference with an explicit exclusive UTC microsecond session-close + /// cutoff (for example, `13:00:00 ET` on a half-day early close). + #[inline] + pub const fn with_close_cutoff( + key: K, + session_date: i32, + close: f64, + session_close_ts: i64, + ) -> Self { + Self { + key, + session_date, + close, + session_close_ts: Some(session_close_ts), + } + } } impl From> for DailySessionClose { @@ -172,6 +210,7 @@ impl From> for DailySessionClose { key: row.key, session_date: row.session_date, close: row.close, + session_close_ts: None, } } } @@ -183,6 +222,7 @@ impl From<&Bar1dRow> for DailySessionClose { key: row.key.clone(), session_date: row.session_date, close: row.close, + session_close_ts: None, } } } @@ -393,7 +433,10 @@ where stats.dropped_inconsistent_ohlc += 1; continue; } - if !unadj.volume.is_finite() || unadj.volume < 0.0 { + if !unadj.volume.is_finite() + || unadj.volume < 0.0 + || (first.volume > 0.0 && unadj.volume == 0.0) + { stats.dropped_invalid_volume += 1; continue; } @@ -472,9 +515,96 @@ struct LastRthBar<'a, K> { session_date: i32, ts: i64, close: f64, + /// `true` when multiple eligible `Rth` bars shared the maximum `ts` with differing closes. + conflicting_last_ts: bool, } -fn collect_last_rth_bars(rows_1m: &[Bar1mRow]) -> Vec> { +fn select_last_rth_bars<'a, K, I>( + rth_sorted: I, + valid_daily: &[DailySessionClose], +) -> Vec> +where + K: Ord + 'a, + I: IntoIterator, +{ + let mut result: Vec> = Vec::new(); + let mut daily_idx = 0usize; + + let mut cur_group: Option<(&'a K, i32, Option)> = None; + let mut cur_best: Option> = None; + + for (key, session_date, ts, close) in rth_sorted { + let cutoff = match cur_group { + Some((gk, gd, cutoff)) if gk == key && gd == session_date => cutoff, + _ => { + if let Some(best) = cur_best.take() { + result.push(best); + } + while daily_idx < valid_daily.len() { + match valid_daily[daily_idx] + .key + .cmp(key) + .then_with(|| valid_daily[daily_idx].session_date.cmp(&session_date)) + { + Ordering::Less => daily_idx += 1, + Ordering::Equal | Ordering::Greater => break, + } + } + let cutoff = if daily_idx < valid_daily.len() + && &valid_daily[daily_idx].key == key + && valid_daily[daily_idx].session_date == session_date + { + valid_daily[daily_idx].session_close_ts + } else { + None + }; + cur_group = Some((key, session_date, cutoff)); + cutoff + } + }; + + if let Some(cutoff_ts) = cutoff { + if ts >= cutoff_ts { + continue; + } + } + + match &mut cur_best { + Some(best) => match ts.cmp(&best.ts) { + Ordering::Greater => { + best.ts = ts; + best.close = close; + best.conflicting_last_ts = false; + } + Ordering::Equal => { + if close.to_bits() != best.close.to_bits() { + best.conflicting_last_ts = true; + } + } + Ordering::Less => {} + }, + None => { + cur_best = Some(LastRthBar { + key, + session_date, + ts, + close, + conflicting_last_ts: false, + }); + } + } + } + + if let Some(best) = cur_best { + result.push(best); + } + result +} + +fn collect_last_rth_bars<'a, K: Ord>( + rows_1m: &'a [Bar1mRow], + valid_daily: &[DailySessionClose], +) -> Vec> { let is_sorted = rows_1m.windows(2).all(|w| { w[0].key .cmp(&w[1].key) @@ -484,77 +614,46 @@ fn collect_last_rth_bars(rows_1m: &[Bar1mRow]) -> Vec> = Vec::new(); - for row in rows_1m { - if row.session != IntradaySession::Rth { - continue; - } - if let Some(prev) = last_rth.last_mut() { - if prev.key == &row.key && prev.session_date == row.session_date { - prev.ts = row.ts; - prev.close = row.close; - continue; - } - } - last_rth.push(LastRthBar { - key: &row.key, - session_date: row.session_date, - ts: row.ts, - close: row.close, - }); - } - return last_rth; + return select_last_rth_bars( + rows_1m + .iter() + .filter(|row| row.session == IntradaySession::Rth) + .map(|row| (&row.key, row.session_date, row.ts, row.close)), + valid_daily, + ); } - let mut rth_rows: Vec> = rows_1m + let mut rth_rows: Vec<(&'a K, i32, i64, f64)> = rows_1m .iter() .filter(|row| row.session == IntradaySession::Rth) - .map(|row| LastRthBar { - key: &row.key, - session_date: row.session_date, - ts: row.ts, - close: row.close, - }) + .map(|row| (&row.key, row.session_date, row.ts, row.close)) .collect(); - rth_rows.sort_by(|a, b| { - a.key - .cmp(b.key) - .then_with(|| a.session_date.cmp(&b.session_date)) - .then_with(|| a.ts.cmp(&b.ts)) + rth_rows.sort_unstable_by(|a, b| { + a.0.cmp(b.0) + .then_with(|| a.1.cmp(&b.1)) + .then_with(|| a.2.cmp(&b.2)) }); - let mut write_idx = 0usize; - let mut read_idx = 0usize; - while read_idx < rth_rows.len() { - let mut group_end = read_idx + 1; - while group_end < rth_rows.len() - && rth_rows[group_end].key == rth_rows[read_idx].key - && rth_rows[group_end].session_date == rth_rows[read_idx].session_date - { - group_end += 1; - } - let last_idx = group_end - 1; - if write_idx != last_idx { - rth_rows.swap(write_idx, last_idx); - } - write_idx += 1; - read_idx = group_end; - } - rth_rows.truncate(write_idx); - rth_rows + select_last_rth_bars(rth_rows, valid_daily) } /// Cross-checks the close of the last [`IntradaySession::Rth`] 1-minute bar per /// `(key, session_date)` against raw daily `bars_1d` closes. /// /// - Returns [`Bars1mError::InvalidTolerance`] if `rel_tolerance` is non-finite or `< 0.0`. -/// - Selects the last `RTH` bar by max `ts` per `(key, session_date)` (handling early-close half -/// days cleanly while ignoring `PRE`/`POST` bars and excluding `PRE`/`POST`-only sessions). +/// - Selects the last `RTH` bar by max `ts` per `(key, session_date)` strictly before the +/// partner's optional [`DailySessionClose::session_close_ts`] cutoff (defaulting to the +/// standard `16:00:00 ET` boundary when `None`), ignoring `PRE`/`POST` bars and excluding +/// sessions with no eligible `RTH` bar before their cutoff. +/// - If a caller supplies multiple eligible `RTH` bars sharing the session's maximum `ts` with +/// differing `close` values, the session is deterministically counted as `unchecked` regardless +/// of input order. /// - Uses an `O(N)` single-pass scan when `rows_1m` is already sorted by `(key, session_date, ts)` /// and falls back to a deterministic sort otherwise. /// - Filters invalid (`<= 0`, non-finite), collapses bitwise-identical duplicate, and drops -/// conflicting duplicate `bars_1d_closes` partners. +/// conflicting duplicate `bars_1d_closes` partners (comparing both `close` and +/// `session_close_ts`). /// - Retains up to [`MAX_MISMATCH_SAMPLES`] worst mismatches ordered by /// `(rel DESC, key ASC, session_date ASC)`. pub fn check_session_closes( @@ -572,8 +671,6 @@ where } let mut stats = SessionCloseStats::default(); - let last_rth = collect_last_rth_bars(rows_1m); - stats.rth_sessions = last_rth.len(); let daily_iter = bars_1d_closes.into_iter(); let mut valid_daily: Vec> = Vec::with_capacity(daily_iter.size_hint().0); @@ -606,9 +703,10 @@ where } let group_len = group_end - read_idx; let first_bits = valid_daily[read_idx].close.to_bits(); - let all_identical = valid_daily[read_idx + 1..group_end] - .iter() - .all(|other| other.close.to_bits() == first_bits); + let first_cutoff = valid_daily[read_idx].session_close_ts; + let all_identical = valid_daily[read_idx + 1..group_end].iter().all(|other| { + other.close.to_bits() == first_bits && other.session_close_ts == first_cutoff + }); if all_identical { stats.daily_duplicate_collapsed += group_len - 1; @@ -624,11 +722,19 @@ where valid_daily.truncate(write_idx); stats.daily_unique_partners = valid_daily.len(); + let last_rth = collect_last_rth_bars(rows_1m, &valid_daily); + stats.rth_sessions = last_rth.len(); + let mut daily_idx = 0usize; let mut heap: BinaryHeap> = BinaryHeap::with_capacity(MAX_MISMATCH_SAMPLES + 1); for rth in &last_rth { + if rth.conflicting_last_ts { + stats.unchecked += 1; + continue; + } + while daily_idx < valid_daily.len() { match valid_daily[daily_idx] .key diff --git a/tools/curate-etl/src/bars_1m_tests.rs b/tools/curate-etl/src/bars_1m_tests.rs index 73d44e27..81e4b66e 100644 --- a/tools/curate-etl/src/bars_1m_tests.rs +++ b/tools/curate-etl/src/bars_1m_tests.rs @@ -489,6 +489,8 @@ fn drops_bad_rows_by_priority_handles_post_unadjust_overflow_underflow_and_dupli bar_1m(1, i64::MAX, 8.0, 10.0, 5.0, 8.0, 10.0), // Post-unadjust volume overflow (1e200 / 1e-200 -> Inf) -> dropped_invalid_volume bar_1m(1, base_ts + 12 * minute, 8.0, 10.0, 5.0, 8.0, 1e200), + // Post-unadjust positive volume underflow (1e-200 / 1e200 -> 0.0) -> dropped_invalid_volume + bar_1m(2, base_ts + 15 * minute, 8.0, 10.0, 5.0, 8.0, 1e-200), // Post-unadjust price underflow (1e-200 * 1e-200 -> 0.0) -> dropped_invalid_ohlc bar_1m(1, base_ts + 13 * minute, 1e-200, 1e-200, 1e-200, 1e-200, 10.0), // Post-unadjust price overflow (1e200 * 1e200 -> Inf) -> dropped_invalid_ohlc @@ -505,10 +507,10 @@ fn drops_bad_rows_by_priority_handles_post_unadjust_overflow_underflow_and_dupli ); assert_bars_1m_invariants(&built.stats); - assert_eq!(built.stats.bars_in, 24); + assert_eq!(built.stats.bars_in, 25); assert_eq!(built.stats.dropped_invalid_ohlc, 6); // 4 input + 1 underflow + 1 overflow assert_eq!(built.stats.dropped_inconsistent_ohlc, 5); - assert_eq!(built.stats.dropped_invalid_volume, 4); // 3 input + 1 volume overflow + assert_eq!(built.stats.dropped_invalid_volume, 5); // 3 input + 1 overflow + 1 positive underflow assert_eq!(built.stats.dropped_ts_out_of_range, 4); assert_eq!(built.stats.duplicate_collapsed, 2); assert_eq!(built.stats.duplicate_conflict_dropped, 2); @@ -533,39 +535,46 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a assert!(err.to_string().contains("invalid relative tolerance")); } - // 2. Half-day early close (last RTH bar 12:59 ET, later POST bar ignored) + PRE/POST-only session. - let half_day = day(2024, 11, 29); // Day after US Thanksgiving + // 2. Half-day early close (Friday after US Thanksgiving, 13:00 ET close): + // - build_bars_1m preserves the fixed PRE/RTH/POST tags (13:00 and 13:15 still carry RTH). + // - check_session_closes applies the listing's 13:00 ET session_close_ts cutoff so 12:59 ET + // is selected and 13:00 / 13:15 / 16:15 prints do not displace the closing bar. + let half_day = day(2024, 11, 29); // Friday after US Thanksgiving let post_only_day = day(2024, 12, 2); + let ts_1259 = et_ts(2024, 11, 29, 12, 59); + let ts_1300 = et_ts(2024, 11, 29, 13, 0); + let ts_1315 = et_ts(2024, 11, 29, 13, 15); let splits: SplitTable = SplitTable::default(); let built = build_bars_1m( [ bar_1m(1, et_ts(2024, 11, 29, 9, 30), 100.0, 101.0, 99.5, 100.5, 500.0), - bar_1m(1, et_ts(2024, 11, 29, 12, 59), 101.0, 101.5, 100.8, 101.25, 800.0), - // Later POST bar with a very different close must NOT be selected as RTH close. - bar_1m(1, et_ts(2024, 11, 29, 16, 15), 105.0, 106.0, 104.5, 105.5, 100.0), + bar_1m(1, ts_1259, 101.0, 101.5, 100.8, 101.25, 800.0), + // Exact 13:00 ET boundary and 13:15 ET after-hours print (>4% away): + // fixed tags stay RTH, but the 13:00 ET cutoff must exclude both from the close check. + bar_1m(1, ts_1300, 103.5, 104.2, 103.2, 104.0, 120.0), + bar_1m(1, ts_1315, 105.0, 106.0, 104.5, 105.5, 100.0), + bar_1m(1, et_ts(2024, 11, 29, 16, 15), 105.5, 106.5, 105.0, 106.0, 80.0), // PRE/POST-only session must be excluded from rth_sessions. bar_1m(1, et_ts(2024, 12, 2, 8, 0), 102.0, 103.0, 101.5, 102.5, 50.0), bar_1m(1, et_ts(2024, 12, 2, 17, 0), 103.0, 104.0, 102.5, 103.5, 50.0), ], &splits, ); + // Output tags strictly follow fixed 09:30..16:00 ET bounds. + assert_eq!(built.rows[0].session, IntradaySession::Rth); + assert_eq!(built.rows[1].session, IntradaySession::Rth); + assert_eq!(built.rows[2].session, IntradaySession::Rth); + assert_eq!(built.rows[3].session, IntradaySession::Rth); + assert_eq!(built.rows[4].session, IntradaySession::Post); // Reverse rows_1m to exercise the unsorted fallback path in check_session_closes. let mut reversed_rows = built.rows.clone(); reversed_rows.reverse(); let daily = [ - DailySessionClose { - key: 1, - session_date: half_day, - close: 101.25, - }, - DailySessionClose { - key: 1, - session_date: post_only_day, - close: 103.5, - }, + DailySessionClose::with_close_cutoff(1, half_day, 101.25, ts_1300), + DailySessionClose::new(1, post_only_day, 103.5), ]; let sorted_check = check_session_closes(&built.rows, daily.clone(), 0.005).unwrap(); let unsorted_check = check_session_closes(&reversed_rows, daily, 0.005).unwrap(); @@ -575,6 +584,45 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a assert_eq!(sorted_check.stats.checked, 1); assert_eq!(sorted_check.stats.within_tolerance, 1); assert_eq!(sorted_check.stats.mismatched, 0); + assert_eq!(sorted_check.stats.max_rel_diff, 0.0); + + // Prove 12:59 ET (101.25) was actually selected under the 13:00 ET cutoff: + // comparing against the 13:15 ET price (105.5) must report a mismatch at ts_1259. + let prove_1259 = check_session_closes( + &built.rows, + [DailySessionClose::with_close_cutoff(1, half_day, 105.5, ts_1300)], + 0.005, + ) + .unwrap(); + assert_eq!(prove_1259.stats.mismatched, 1); + assert_eq!(prove_1259.mismatch_samples[0].last_rth_ts, ts_1259); + assert_eq!(prove_1259.mismatch_samples[0].close_1m, 101.25); + + // Without the early-close cutoff, the fixed 16:00 ET window picks 13:15 ET (105.5) and mismatches. + let without_cutoff = check_session_closes( + &built.rows, + [DailySessionClose::new(1, half_day, 101.25)], + 0.005, + ) + .unwrap(); + assert_eq!(without_cutoff.stats.mismatched, 1); + assert_eq!(without_cutoff.mismatch_samples[0].last_rth_ts, ts_1315); + assert_eq!(without_cutoff.mismatch_samples[0].close_1m, 105.5); + + // A half-day session whose only RTH bars are at/after the cutoff has no eligible RTH bar. + let post_cutoff_only = build_bars_1m( + [bar_1m(9, ts_1315, 105.0, 106.0, 104.5, 105.5, 100.0)], + &splits, + ); + let post_cutoff_check = check_session_closes( + &post_cutoff_only.rows, + [DailySessionClose::with_close_cutoff(9, half_day, 101.25, ts_1300)], + 0.005, + ) + .unwrap(); + assert_close_check_invariants(&post_cutoff_check.stats); + assert_eq!(post_cutoff_check.stats.rth_sessions, 0); + assert_eq!(post_cutoff_check.stats.checked, 0); // 3. Daily close hygiene (invalid, identical dup, conflicting dup) + >100 mismatch sample cap. let base_day = day(2024, 1, 2); @@ -583,18 +631,28 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a // Session 0: exact match with identical daily duplicate -> collapses to 1 rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 2, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0)); - daily_in.push(DailySessionClose { key: 1, session_date: base_day, close: 10.0 }); - daily_in.push(DailySessionClose { key: 1, session_date: base_day, close: 10.0 }); + daily_in.push(DailySessionClose::new(1, base_day, 10.0)); + daily_in.push(DailySessionClose::new(1, base_day, 10.0)); // Session 1: conflicting daily duplicate -> dropped -> unchecked rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 3, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0)); - daily_in.push(DailySessionClose { key: 1, session_date: base_day + 1, close: 10.0 }); - daily_in.push(DailySessionClose { key: 1, session_date: base_day + 1, close: 10.5 }); + daily_in.push(DailySessionClose::new(1, base_day + 1, 10.0)); + daily_in.push(DailySessionClose::new(1, base_day + 1, 10.5)); // Session 2: invalid daily closes (NaN, <=0) -> dropped -> unchecked rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 4, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0)); - daily_in.push(DailySessionClose { key: 1, session_date: base_day + 2, close: f64::NAN }); - daily_in.push(DailySessionClose { key: 1, session_date: base_day + 2, close: 0.0 }); + daily_in.push(DailySessionClose::new(1, base_day + 2, f64::NAN)); + daily_in.push(DailySessionClose::new(1, base_day + 2, 0.0)); + + // Session 3: same daily close but conflicting session_close_ts -> dropped -> unchecked + rows_1m_in.push(bar_1m(1, et_ts(2024, 1, 5, 15, 59), 10.0, 10.5, 9.5, 10.0, 100.0)); + daily_in.push(DailySessionClose::new(1, base_day + 3, 10.0)); + daily_in.push(DailySessionClose::with_close_cutoff( + 1, + base_day + 3, + 10.0, + et_ts(2024, 1, 5, 13, 0), + )); // 110 mismatches across distinct days on key=2 (plus a tie on key=3 to verify tie-break order). let start_day = day(2024, 2, 1); @@ -603,29 +661,21 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a let ts = et_to_utc_micros(d, 15, 59, 0).unwrap(); let close_1m = 100.0 + (i + 2) as f64; // rel = (i + 2) / 100 >= 0.02 > 0.005 rows_1m_in.push(bar_1m(2, ts, close_1m, close_1m, close_1m, close_1m, 100.0)); - daily_in.push(DailySessionClose { - key: 2, - session_date: d, - close: 100.0, - }); + daily_in.push(DailySessionClose::new(2, d, 100.0)); } // Tie with highest rel (1.11) on key=3 vs key=2 -> key=2 must sort before key=3. let tie_d = start_day + 109; let tie_ts = et_to_utc_micros(tie_d, 15, 59, 0).unwrap(); rows_1m_in.push(bar_1m(3, tie_ts, 211.0, 211.0, 211.0, 211.0, 100.0)); - daily_in.push(DailySessionClose { - key: 3, - session_date: tie_d, - close: 100.0, - }); + daily_in.push(DailySessionClose::new(3, tie_d, 100.0)); let built_many = build_bars_1m(rows_1m_in, &splits); let check_many = check_session_closes(&built_many.rows, daily_in, 0.005).unwrap(); assert_close_check_invariants(&check_many.stats); assert_eq!(check_many.stats.daily_invalid_close_dropped, 2); assert_eq!(check_many.stats.daily_duplicate_collapsed, 1); - assert_eq!(check_many.stats.daily_duplicate_conflict_dropped, 2); - assert_eq!(check_many.stats.unchecked, 2); + assert_eq!(check_many.stats.daily_duplicate_conflict_dropped, 4); + assert_eq!(check_many.stats.unchecked, 3); assert_eq!(check_many.stats.mismatched, 111); assert_eq!(check_many.mismatch_samples.len(), MAX_MISMATCH_SAMPLES); @@ -685,3 +735,90 @@ fn output_is_sorted_unique_and_deterministic_across_input_permutations() { assert_eq!(ord, Ordering::Less, "output not strictly sorted/unique"); } } + +#[test] +fn check_session_closes_handles_conflicting_latest_rth_timestamps_deterministically() { + let d1 = day(2024, 6, 10); + let d2 = day(2024, 6, 11); + let d3 = day(2024, 6, 12); + + let mk_row = |key: i32, session_date: i32, ts: i64, close: f64| Bar1mRow { + key, + session_date, + ts, + open: close, + high: close, + low: close, + close, + volume: 100.0, + session: IntradaySession::Rth, + source: BARS_1M_SOURCE_EOD, + }; + + // d1: conflicting closes at the latest RTH timestamp (one matches 100.0, one is 105.0). + let ts_d1_last = et_ts(2024, 6, 10, 15, 59); + let d1_match = mk_row(1, d1, ts_d1_last, 100.0); + let d1_mismatch = mk_row(1, d1, ts_d1_last, 105.0); + + // d2: identical duplicate closes at the latest RTH timestamp -> checked and matched. + let ts_d2_last = et_ts(2024, 6, 11, 15, 59); + let d2_a = mk_row(1, d2, ts_d2_last, 50.0); + let d2_b = mk_row(1, d2, ts_d2_last, 50.0); + + // d3: conflicting closes at an earlier timestamp (10:00) followed by a unique latest bar (15:59) + // -> latest bar is unambiguous, so d3 is checked and matched. + let ts_d3_early = et_ts(2024, 6, 12, 10, 0); + let ts_d3_last = et_ts(2024, 6, 12, 15, 59); + let d3_early_a = mk_row(1, d3, ts_d3_early, 20.0); + let d3_early_b = mk_row(1, d3, ts_d3_early, 25.0); + let d3_last = mk_row(1, d3, ts_d3_last, 22.0); + + let daily = [ + DailySessionClose::new(1, d1, 100.0), + DailySessionClose::new(1, d2, 50.0), + DailySessionClose::new(1, d3, 22.0), + ]; + + // Order A (sorted): matching bar before mismatching bar on d1. + let order_a = vec![ + d1_match.clone(), + d1_mismatch.clone(), + d2_a.clone(), + d2_b.clone(), + d3_early_a.clone(), + d3_early_b.clone(), + d3_last.clone(), + ]; + // Order B (sorted): mismatching bar before matching bar on d1. + let order_b = vec![ + d1_mismatch.clone(), + d1_match.clone(), + d2_b.clone(), + d2_a.clone(), + d3_early_b.clone(), + d3_early_a.clone(), + d3_last.clone(), + ]; + // Order C (unsorted fallback): reversed order_a. + let mut order_c = order_a.clone(); + order_c.reverse(); + // Order D (unsorted fallback): reversed order_b. + let mut order_d = order_b.clone(); + order_d.reverse(); + + let check_a = check_session_closes(&order_a, daily.clone(), 0.005).unwrap(); + let check_b = check_session_closes(&order_b, daily.clone(), 0.005).unwrap(); + let check_c = check_session_closes(&order_c, daily.clone(), 0.005).unwrap(); + let check_d = check_session_closes(&order_d, daily, 0.005).unwrap(); + + assert_eq!(check_a, check_b); + assert_eq!(check_a, check_c); + assert_eq!(check_a, check_d); + assert_close_check_invariants(&check_a.stats); + assert_eq!(check_a.stats.rth_sessions, 3); + assert_eq!(check_a.stats.checked, 2); + assert_eq!(check_a.stats.within_tolerance, 2); + assert_eq!(check_a.stats.mismatched, 0); + assert_eq!(check_a.stats.unchecked, 1); + assert!(check_a.mismatch_samples.is_empty()); +} diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 48a448e5..5b9711a1 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -837,26 +837,10 @@ fn verify_bars_1m_bench_self_check() -> Result<(), Bars1mError> { assert_eq!(built.rows[6].session, IntradaySession::Post); let daily = [ - DailySessionClose { - key: "NEXM.V", - session_date: nexm_ex - 1, - close: 1.2145, - }, - DailySessionClose { - key: "NEXM.V", - session_date: nexm_ex, - close: 24.30, - }, - DailySessionClose { - key: "NVDA.US", - session_date: nvda_ex - 3, - close: 1_208.88, - }, - DailySessionClose { - key: "NVDA.US", - session_date: nvda_ex, - close: 121.79, - }, + DailySessionClose::new("NEXM.V", nexm_ex - 1, 1.2145), + DailySessionClose::new("NEXM.V", nexm_ex, 24.30), + DailySessionClose::new("NVDA.US", nvda_ex - 3, 1_208.88), + DailySessionClose::new("NVDA.US", nvda_ex, 121.79), ]; let check = check_session_closes(&built.rows, daily, 0.005)?; assert_eq!(check.stats.checked, 4, "self-check expected 4 checked sessions"); @@ -869,9 +853,10 @@ fn verify_bars_1m_bench_self_check() -> Result<(), Bars1mError> { /// Executes a pre-timing correctness self-check (NEXM.V 1:20 reverse split, NVDA.US 10:1 forward /// split, EST/EDT session tagging, and `check_session_closes`), then generates `rows` deterministic /// multi-session EST/EDT 1m bars across `2_000` `i32` keys with forward/reverse splits, a small -/// share of invalid/inconsistent/out-of-range/duplicate bars, and daily close cross-check partners. -/// Times [`build_bars_1m`] and [`check_session_closes`] and returns throughput plus a deterministic -/// `u64` checksum. +/// share of invalid/inconsistent/out-of-range/duplicate bars, and one daily close reference per +/// sampled synthetic session derived from its expected last valid RTH minute (with deliberate +/// mismatches and duplicate conflicts injected separately). Times [`build_bars_1m`] and +/// [`check_session_closes`] and returns throughput plus a deterministic `u64` checksum. pub fn run_bars_1m_benchmark(rows: usize) -> Result { verify_bars_1m_bench_self_check()?; @@ -892,21 +877,30 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result> = Vec::with_capacity(rows); - let mut daily_closes: Vec> = Vec::with_capacity(rows / 20 + 64); + // Track every valid RTH candidate `(key, session_date, ts, close)` (including exact/conflicting + // duplicates) so we can derive each session's exact expected last valid RTH bar before timing. + let mut valid_rth_candidates: Vec<(i32, i32, i64, f64)> = Vec::with_capacity(rows / 2 + 64); - let mut last_valid: Option> = None; + let mut last_valid: Option<(EodIntradayBar, i32, bool)> = None; for _ in 0..rows { let roll = rng.next_u64() % 1_000; if roll < 5 { - if let Some(prev) = last_valid.clone() { + if let Some((prev, prev_date, prev_is_rth)) = last_valid.clone() { + if prev_is_rth { + valid_rth_candidates.push((prev.key, prev_date, prev.ts, prev.close)); + } bars.push(prev); continue; } } else if roll < 7 { - if let Some(mut prev) = last_valid.clone() { + if let Some((mut prev, prev_date, prev_is_rth)) = last_valid.clone() { + let orig_close_bits = prev.close.to_bits(); prev.close = (prev.close + 0.05).min(prev.high); - if prev.close.to_bits() == last_valid.as_ref().map_or(0, |b| b.close.to_bits()) { - prev.volume += 1.0; + if prev.close.to_bits() == orig_close_bits { + prev.close = (prev.close - 0.05).max(prev.low); + } + if prev_is_rth { + valid_rth_candidates.push((prev.key, prev_date, prev.ts, prev.close)); } bars.push(prev); continue; @@ -917,6 +911,7 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result spans PRE, RTH, and POST on both EST and EDT. let et_minute = 480 + (rng.next_u64() % 720) as i64; + let is_rth = (570..960).contains(&et_minute); let close_1600_utc = et_session_close_utc_micros(session_date).unwrap_or(0); let ts = close_1600_utc + (et_minute - 960) * 60_000_000; @@ -974,7 +969,10 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result { @@ -987,29 +985,96 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result> = + Vec::with_capacity(valid_rth_candidates.len() / 4 + 64); + let mut idx = 0usize; + while idx < valid_rth_candidates.len() { + let key = valid_rth_candidates[idx].0; + let session_date = valid_rth_candidates[idx].1; + let mut session_end = idx + 1; + while session_end < valid_rth_candidates.len() + && valid_rth_candidates[session_end].0 == key + && valid_rth_candidates[session_end].1 == session_date + { + session_end += 1; + } + + // Find the last non-conflicted `(key, ts)` subgroup within this `(key, session_date)`. + let mut expected_last_close: Option = None; + let mut g = idx; + while g < session_end { + let ts = valid_rth_candidates[g].2; + let mut g_end = g + 1; + while g_end < session_end && valid_rth_candidates[g_end].2 == ts { + g_end += 1; + } + let first_bits = valid_rth_candidates[g].3.to_bits(); + let all_same = valid_rth_candidates[g + 1..g_end] + .iter() + .all(|c| c.3.to_bits() == first_bits); + if all_same { + expected_last_close = Some(valid_rth_candidates[g].3); + } + g = g_end; + } + idx = session_end; + + let Some(adj_close) = expected_last_close else { + continue; + }; + if (rng.next_u64() % 4) != 0 { + continue; + } + + let factor = splits.cum_factor_after(&key, session_date); + let raw_close = adj_close * factor; + let case_roll = rng.next_u64() % 200; + match case_roll { + 0..=1 => { + // Deliberate 5% mismatch (> 0.5% tolerance). + daily_closes.push(DailySessionClose::new(key, session_date, raw_close * 1.05)); + } + 2 => { + // Deliberate conflicting duplicate daily reference. + daily_closes.push(DailySessionClose::new(key, session_date, raw_close)); + daily_closes.push(DailySessionClose::new(key, session_date, raw_close * 1.03)); + } + 3 => { + // Deliberate identical duplicate daily reference. + daily_closes.push(DailySessionClose::new(key, session_date, raw_close)); + daily_closes.push(DailySessionClose::new(key, session_date, raw_close)); + } + _ => { + // Within-tolerance reference (-0.20%..+0.20%). + let jitter_bp = (rng.next_u64() % 41) as f64 - 20.0; + daily_closes.push(DailySessionClose::new( + key, + session_date, + raw_close * (1.0 + jitter_bp * 0.0001), + )); + } + } + } + drop(valid_rth_candidates); + let daily_rows_in = daily_closes.len(); let build_start = Instant::now(); From b95e41393ac0b86ed852ebaa2721b29fefe92b30 Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 23:40:32 -0500 Subject: [PATCH 10/21] =?UTF-8?q?T-130:=20M2.3a=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20`bars=5F1m`=20builder=20(`eodIntraday1M`=20ful?= =?UTF-8?q?l-bar=20split=20un-adjustment=20+=20PRE/RTH/POST=20session=20ta?= =?UTF-8?q?gging=20+=20session-close=20vs=20`bars=5F1d`=20cross-check)=20w?= =?UTF-8?q?ith=20tests=20and=20local=20benchmark=20(no=20new=20crates)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/bars_1m.rs | 150 ++++++++++++++++++++++++-- tools/curate-etl/src/bars_1m_tests.rs | 106 +++++++++++++----- tools/curate-etl/src/bench.rs | 74 +++++++++---- tools/curate-etl/src/lib.rs | 8 +- 4 files changed, 281 insertions(+), 57 deletions(-) diff --git a/tools/curate-etl/src/bars_1m.rs b/tools/curate-etl/src/bars_1m.rs index b3dcd5a4..d4d603cd 100644 --- a/tools/curate-etl/src/bars_1m.rs +++ b/tools/curate-etl/src/bars_1m.rs @@ -18,8 +18,9 @@ //! - Bad single rows never panic or abort the build; each failure category is dropped and counted //! separately in [`Bars1mStats`]. +use std::borrow::Borrow; use std::cmp::Ordering; -use std::collections::BinaryHeap; +use std::collections::{BinaryHeap, HashMap}; use std::error::Error; use std::fmt; use std::hash::Hash; @@ -203,26 +204,132 @@ impl DailySessionClose { } } -impl From> for DailySessionClose { +/// Explicit in-memory session-close cutoff policy required when resolving raw [`Bar1dRow`] +/// references for [`check_session_closes_against_bars_1d`] or [`DailySessionClose::from_bar_1d`]. +/// +/// Lookup precedence for `(key, session_date)`: +/// 1. Per-listing, per-date override (`Some(cutoff_ts)` or `None` to explicitly use standard +/// `16:00:00 ET` even when a market-wide per-date cutoff is configured, e.g., a TSX listing on +/// a US early-close day). +/// 2. Per-date cutoff (e.g., `13:00:00 ET` on the Friday after US Thanksgiving). +/// 3. Standard `16:00:00 ET` RTH boundary (`None`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SessionCloseCutoffPolicy +where + K: Eq + Hash, +{ + per_date: HashMap, + per_listing_date: HashMap>>, +} + +impl SessionCloseCutoffPolicy { + /// Creates an explicit policy using the standard `16:00:00 ET` RTH boundary for all listings + /// and dates (no early-close overrides). + pub fn standard_rth() -> Self { + Self { + per_date: HashMap::new(), + per_listing_date: HashMap::new(), + } + } + + /// Sets an exclusive UTC microsecond session-close cutoff for all listings on `session_date` + /// (unless overridden by a listing-specific rule). + pub fn set_date_cutoff(&mut self, session_date: i32, cutoff_ts: i64) { + self.per_date.insert(session_date, cutoff_ts); + } + + /// Builder-style variant of [`Self::set_date_cutoff`]. + pub fn with_date_cutoff(mut self, session_date: i32, cutoff_ts: i64) -> Self { + self.set_date_cutoff(session_date, cutoff_ts); + self + } + + /// Builder-style helper to populate multiple `(session_date, cutoff_ts)` per-date cutoffs. + pub fn with_date_cutoffs(mut self, cutoffs: I) -> Self + where + I: IntoIterator, + { + for (session_date, cutoff_ts) in cutoffs { + self.set_date_cutoff(session_date, cutoff_ts); + } + self + } + + /// Sets a per-listing, per-date cutoff override. + /// + /// Pass `Some(cutoff_ts)` for a listing-specific early close, or `None` to explicitly select + /// the standard `16:00:00 ET` cutoff for `key` on `session_date` even if a per-date cutoff is + /// configured. + pub fn set_listing_date_cutoff(&mut self, key: K, session_date: i32, cutoff_ts: Option) { + self.per_listing_date + .entry(key) + .or_default() + .insert(session_date, cutoff_ts); + } + + /// Builder-style variant of [`Self::set_listing_date_cutoff`]. + pub fn with_listing_date_cutoff( + mut self, + key: K, + session_date: i32, + cutoff_ts: Option, + ) -> Self { + self.set_listing_date_cutoff(key, session_date, cutoff_ts); + self + } + + /// Builder-style helper to populate multiple `(key, session_date, cutoff_ts)` listing + /// overrides. + pub fn with_listing_date_cutoffs(mut self, cutoffs: I) -> Self + where + I: IntoIterator)>, + { + for (key, session_date, cutoff_ts) in cutoffs { + self.set_listing_date_cutoff(key, session_date, cutoff_ts); + } + self + } + + /// Resolves the exclusive UTC microsecond session-close cutoff for `(key, session_date)`, + /// returning `None` when the standard `16:00:00 ET` RTH boundary applies. #[inline] - fn from(row: Bar1dRow) -> Self { + pub fn cutoff_for(&self, key: &K, session_date: i32) -> Option { + if let Some(listing_cutoffs) = self.per_listing_date.get(key) { + if let Some(&override_cutoff) = listing_cutoffs.get(&session_date) { + return override_cutoff; + } + } + self.per_date.get(&session_date).copied() + } +} + +impl DailySessionClose { + /// Converts a raw [`Bar1dRow`] into a [`DailySessionClose`] using an explicit + /// [`SessionCloseCutoffPolicy`]. + #[inline] + pub fn from_bar_1d(row: Bar1dRow, cutoff_policy: &SessionCloseCutoffPolicy) -> Self { + let session_close_ts = cutoff_policy.cutoff_for(&row.key, row.session_date); Self { key: row.key, session_date: row.session_date, close: row.close, - session_close_ts: None, + session_close_ts, } } -} -impl From<&Bar1dRow> for DailySessionClose { + /// Converts a borrowed [`Bar1dRow`] into a [`DailySessionClose`] using an explicit + /// [`SessionCloseCutoffPolicy`]. #[inline] - fn from(row: &Bar1dRow) -> Self { + pub fn from_bar_1d_ref(row: &Bar1dRow, cutoff_policy: &SessionCloseCutoffPolicy) -> Self + where + K: Clone, + { + let session_close_ts = cutoff_policy.cutoff_for(&row.key, row.session_date); Self { key: row.key.clone(), session_date: row.session_date, close: row.close, - session_close_ts: None, + session_close_ts, } } } @@ -812,6 +919,33 @@ where }) } +/// Cross-checks the close of the last [`IntradaySession::Rth`] 1-minute bar per +/// `(key, session_date)` against raw [`Bar1dRow`] daily rows using an explicit +/// [`SessionCloseCutoffPolicy`]. +/// +/// Raw `Bar1dRow` values do not carry an exchange session-close cutoff, so callers must pass +/// `cutoff_policy` (for example, [`SessionCloseCutoffPolicy::standard_rth`] or a policy populated +/// with per-date / per-listing early-close cutoffs) rather than silently assuming `16:00:00 ET`. +pub fn check_session_closes_against_bars_1d( + rows_1m: &[Bar1mRow], + bars_1d: I, + cutoff_policy: &SessionCloseCutoffPolicy, + rel_tolerance: f64, +) -> Result, Bars1mError> +where + K: Ord + Eq + Hash + Clone, + R: Borrow>, + I: IntoIterator, +{ + check_session_closes( + rows_1m, + bars_1d + .into_iter() + .map(|row| DailySessionClose::from_bar_1d_ref(row.borrow(), cutoff_policy)), + rel_tolerance, + ) +} + #[cfg(test)] #[path = "bars_1m_tests.rs"] mod tests; diff --git a/tools/curate-etl/src/bars_1m_tests.rs b/tools/curate-etl/src/bars_1m_tests.rs index 81e4b66e..de8e7d68 100644 --- a/tools/curate-etl/src/bars_1m_tests.rs +++ b/tools/curate-etl/src/bars_1m_tests.rs @@ -196,7 +196,10 @@ fn nexm_reverse_split_1_for_20_unadjusts_pre_split_preserves_ex_date_and_matches daily_row("NEXM.V".to_string(), ex_date, 24.30), daily_row("NEXM.V".to_string(), post_day, 24.65), ]; - let check = check_session_closes(&built.rows, &daily_closes, 0.005).unwrap(); + let standard_policy = SessionCloseCutoffPolicy::standard_rth(); + let check = + check_session_closes_against_bars_1d(&built.rows, &daily_closes, &standard_policy, 0.005) + .unwrap(); assert_close_check_invariants(&check.stats); assert_eq!(check.stats.rth_sessions, 3); assert_eq!(check.stats.checked, 3); @@ -278,7 +281,10 @@ fn nvda_forward_split_10_for_1_unadjusts_pre_split_and_matches_bars_1d() { daily_row("NVDA.US".to_string(), ex_date, 121.79), daily_row("NVDA.US".to_string(), post_day, 120.91), ]; - let check = check_session_closes(&built.rows, daily_closes, 0.005).unwrap(); + let standard_policy = SessionCloseCutoffPolicy::standard_rth(); + let check = + check_session_closes_against_bars_1d(&built.rows, daily_closes, &standard_policy, 0.005) + .unwrap(); assert_close_check_invariants(&check.stats); assert_eq!(check.stats.checked, 3); assert_eq!(check.stats.within_tolerance, 3); @@ -321,7 +327,10 @@ fn negative_non_vacuity_still_adjusted_pre_split_bars_fail_session_close_check() daily_row("NEXM.V".to_string(), pre_day, 1.2145), daily_row("NEXM.V".to_string(), ex_date, 24.30), ]; - let check = check_session_closes(&built.rows, daily_closes, 0.005).unwrap(); + let standard_policy = SessionCloseCutoffPolicy::standard_rth(); + let check = + check_session_closes_against_bars_1d(&built.rows, daily_closes, &standard_policy, 0.005) + .unwrap(); assert_close_check_invariants(&check.stats); assert_eq!(check.stats.checked, 2); assert_eq!(check.stats.within_tolerance, 1); @@ -535,15 +544,24 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a assert!(err.to_string().contains("invalid relative tolerance")); } - // 2. Half-day early close (Friday after US Thanksgiving, 13:00 ET close): + // 2. Half-day early close (Friday after US Thanksgiving, 13:00 ET close) via raw Bar1dRow path: // - build_bars_1m preserves the fixed PRE/RTH/POST tags (13:00 and 13:15 still carry RTH). - // - check_session_closes applies the listing's 13:00 ET session_close_ts cutoff so 12:59 ET - // is selected and 13:00 / 13:15 / 16:15 prints do not displace the closing bar. + // - check_session_closes_against_bars_1d applies an explicit SessionCloseCutoffPolicy + // supporting per-date cutoffs and per-listing overrides: + // * listing 1 (US equity): inherits per-date 13:00 ET cutoff -> selects 12:59 ET, + // excluding 13:00 / 13:15 / 16:15 ET prints. + // * listing 2 (e.g. TSX equity on US Thanksgiving Friday): per-listing `None` override + // uses standard 16:00 ET close -> selects 15:59 ET. + // * listing 3: per-listing custom 14:00 ET cutoff -> selects 13:59 ET, excluding 14:15. let half_day = day(2024, 11, 29); // Friday after US Thanksgiving let post_only_day = day(2024, 12, 2); let ts_1259 = et_ts(2024, 11, 29, 12, 59); let ts_1300 = et_ts(2024, 11, 29, 13, 0); let ts_1315 = et_ts(2024, 11, 29, 13, 15); + let ts_1359 = et_ts(2024, 11, 29, 13, 59); + let ts_1400 = et_ts(2024, 11, 29, 14, 0); + let ts_1415 = et_ts(2024, 11, 29, 14, 15); + let ts_1559 = et_ts(2024, 11, 29, 15, 59); let splits: SplitTable = SplitTable::default(); let built = build_bars_1m( @@ -558,6 +576,12 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a // PRE/POST-only session must be excluded from rth_sessions. bar_1m(1, et_ts(2024, 12, 2, 8, 0), 102.0, 103.0, 101.5, 102.5, 50.0), bar_1m(1, et_ts(2024, 12, 2, 17, 0), 103.0, 104.0, 102.5, 103.5, 50.0), + // Listing 2 (standard 16:00 ET close override on half_day): 12:59 vs 15:59 (>5% apart). + bar_1m(2, ts_1259, 50.0, 50.5, 49.5, 50.0, 300.0), + bar_1m(2, ts_1559, 53.0, 53.5, 52.5, 53.25, 400.0), + // Listing 3 (listing-specific 14:00 ET cutoff override on half_day): 13:59 vs 14:15. + bar_1m(3, ts_1359, 20.0, 20.2, 19.8, 20.10, 250.0), + bar_1m(3, ts_1415, 21.5, 21.8, 21.2, 21.60, 100.0), ], &splits, ); @@ -572,25 +596,53 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a let mut reversed_rows = built.rows.clone(); reversed_rows.reverse(); - let daily = [ - DailySessionClose::with_close_cutoff(1, half_day, 101.25, ts_1300), - DailySessionClose::new(1, post_only_day, 103.5), + let cutoff_policy = SessionCloseCutoffPolicy::standard_rth() + .with_date_cutoff(half_day, ts_1300) + .with_listing_date_cutoff(2, half_day, None) + .with_listing_date_cutoff(3, half_day, Some(ts_1400)); + + let raw_daily_rows = [ + daily_row(1, half_day, 101.25), + daily_row(1, post_only_day, 103.5), + daily_row(2, half_day, 53.25), + daily_row(3, half_day, 20.10), ]; - let sorted_check = check_session_closes(&built.rows, daily.clone(), 0.005).unwrap(); - let unsorted_check = check_session_closes(&reversed_rows, daily, 0.005).unwrap(); + + let sorted_check = + check_session_closes_against_bars_1d(&built.rows, &raw_daily_rows, &cutoff_policy, 0.005) + .unwrap(); + let unsorted_check = + check_session_closes_against_bars_1d(&reversed_rows, &raw_daily_rows, &cutoff_policy, 0.005) + .unwrap(); assert_eq!(sorted_check, unsorted_check); assert_close_check_invariants(&sorted_check.stats); - assert_eq!(sorted_check.stats.rth_sessions, 1); - assert_eq!(sorted_check.stats.checked, 1); - assert_eq!(sorted_check.stats.within_tolerance, 1); + assert_eq!(sorted_check.stats.rth_sessions, 3); + assert_eq!(sorted_check.stats.checked, 3); + assert_eq!(sorted_check.stats.within_tolerance, 3); assert_eq!(sorted_check.stats.mismatched, 0); assert_eq!(sorted_check.stats.max_rel_diff, 0.0); - // Prove 12:59 ET (101.25) was actually selected under the 13:00 ET cutoff: - // comparing against the 13:15 ET price (105.5) must report a mismatch at ts_1259. - let prove_1259 = check_session_closes( + // Verify DailySessionClose::from_bar_1d / from_bar_1d_ref parity with the cutoff policy. + let converted_owned: Vec> = raw_daily_rows + .iter() + .cloned() + .map(|row| DailySessionClose::from_bar_1d(row, &cutoff_policy)) + .collect(); + assert_eq!(converted_owned[0].session_close_ts, Some(ts_1300)); + assert_eq!(converted_owned[1].session_close_ts, None); + assert_eq!(converted_owned[2].session_close_ts, None); + assert_eq!(converted_owned[3].session_close_ts, Some(ts_1400)); + assert_eq!( + check_session_closes(&built.rows, converted_owned, 0.005).unwrap(), + sorted_check + ); + + // Prove 12:59 ET (101.25) was actually selected for listing 1 under the 13:00 ET cutoff: + // comparing its raw Bar1dRow against the 13:15 ET price (105.5) must mismatch at ts_1259. + let prove_1259 = check_session_closes_against_bars_1d( &built.rows, - [DailySessionClose::with_close_cutoff(1, half_day, 105.5, ts_1300)], + [daily_row(1, half_day, 105.5)], + &cutoff_policy, 0.005, ) .unwrap(); @@ -598,25 +650,27 @@ fn check_session_closes_handles_early_close_pre_post_only_unsorted_hygiene_cap_a assert_eq!(prove_1259.mismatch_samples[0].last_rth_ts, ts_1259); assert_eq!(prove_1259.mismatch_samples[0].close_1m, 101.25); - // Without the early-close cutoff, the fixed 16:00 ET window picks 13:15 ET (105.5) and mismatches. - let without_cutoff = check_session_closes( + // Under an explicit standard 16:00 ET policy, listing 1 picks 13:15 ET (105.5) and mismatches. + let standard_only = check_session_closes_against_bars_1d( &built.rows, - [DailySessionClose::new(1, half_day, 101.25)], + [daily_row(1, half_day, 101.25)], + &SessionCloseCutoffPolicy::standard_rth(), 0.005, ) .unwrap(); - assert_eq!(without_cutoff.stats.mismatched, 1); - assert_eq!(without_cutoff.mismatch_samples[0].last_rth_ts, ts_1315); - assert_eq!(without_cutoff.mismatch_samples[0].close_1m, 105.5); + assert_eq!(standard_only.stats.mismatched, 1); + assert_eq!(standard_only.mismatch_samples[0].last_rth_ts, ts_1315); + assert_eq!(standard_only.mismatch_samples[0].close_1m, 105.5); // A half-day session whose only RTH bars are at/after the cutoff has no eligible RTH bar. let post_cutoff_only = build_bars_1m( [bar_1m(9, ts_1315, 105.0, 106.0, 104.5, 105.5, 100.0)], &splits, ); - let post_cutoff_check = check_session_closes( + let post_cutoff_check = check_session_closes_against_bars_1d( &post_cutoff_only.rows, - [DailySessionClose::with_close_cutoff(9, half_day, 101.25, ts_1300)], + [daily_row(9, half_day, 101.25)], + &cutoff_policy, 0.005, ) .unwrap(); diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 5b9711a1..6fea2441 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -876,10 +876,45 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result, session_date: i32) -> BenchRthCandidate { + BenchRthCandidate { + key: bar.key, + session_date, + ts: bar.ts, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + volume: if bar.volume == 0.0 { 0.0 } else { bar.volume }, + } + } + + #[inline] + fn bench_rth_values_bit_eq(a: &BenchRthCandidate, b: &BenchRthCandidate) -> bool { + a.open.to_bits() == b.open.to_bits() + && a.high.to_bits() == b.high.to_bits() + && a.low.to_bits() == b.low.to_bits() + && a.close.to_bits() == b.close.to_bits() + && a.volume.to_bits() == b.volume.to_bits() + } + let mut bars: Vec> = Vec::with_capacity(rows); - // Track every valid RTH candidate `(key, session_date, ts, close)` (including exact/conflicting - // duplicates) so we can derive each session's exact expected last valid RTH bar before timing. - let mut valid_rth_candidates: Vec<(i32, i32, i64, f64)> = Vec::with_capacity(rows / 2 + 64); + // Track every valid RTH candidate with all five normalized OHLCV fields (including exact and + // conflicting duplicates) so we match `build_bars_1m`'s duplicate-conflict drop rule when + // deriving each session's expected last surviving valid RTH bar before timing. + let mut valid_rth_candidates: Vec = Vec::with_capacity(rows / 2 + 64); let mut last_valid: Option<(EodIntradayBar, i32, bool)> = None; for _ in 0..rows { @@ -887,7 +922,7 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result Result Result Result Result> = Vec::with_capacity(valid_rth_candidates.len() / 4 + 64); let mut idx = 0usize; while idx < valid_rth_candidates.len() { - let key = valid_rth_candidates[idx].0; - let session_date = valid_rth_candidates[idx].1; + let key = valid_rth_candidates[idx].key; + let session_date = valid_rth_candidates[idx].session_date; let mut session_end = idx + 1; while session_end < valid_rth_candidates.len() - && valid_rth_candidates[session_end].0 == key - && valid_rth_candidates[session_end].1 == session_date + && valid_rth_candidates[session_end].key == key + && valid_rth_candidates[session_end].session_date == session_date { session_end += 1; } @@ -1021,17 +1057,17 @@ pub fn run_bars_1m_benchmark(rows: usize) -> Result = None; let mut g = idx; while g < session_end { - let ts = valid_rth_candidates[g].2; + let ts = valid_rth_candidates[g].ts; let mut g_end = g + 1; - while g_end < session_end && valid_rth_candidates[g_end].2 == ts { + while g_end < session_end && valid_rth_candidates[g_end].ts == ts { g_end += 1; } - let first_bits = valid_rth_candidates[g].3.to_bits(); + let first = &valid_rth_candidates[g]; let all_same = valid_rth_candidates[g + 1..g_end] .iter() - .all(|c| c.3.to_bits() == first_bits); + .all(|c| bench_rth_values_bit_eq(first, c)); if all_same { - expected_last_close = Some(valid_rth_candidates[g].3); + expected_last_close = Some(first.close); } g = g_end; } diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 0af02987..eaefb854 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -38,10 +38,10 @@ pub use bars::{ VolumeMismatchSample, MAX_MISMATCH_SAMPLES, }; pub use bars_1m::{ - build_bars_1m, check_session_closes, Bar1mRow, Bars1mBuild, Bars1mError, Bars1mStats, - DailySessionClose, EodIntradayBar, IntradaySession, SessionCloseCheck, - SessionCloseMismatchSample, SessionCloseStats, BARS_1M_SOURCE_EOD, RTH_END_MINUTE_ET, - RTH_START_MINUTE_ET, + build_bars_1m, check_session_closes, check_session_closes_against_bars_1d, Bar1mRow, + Bars1mBuild, Bars1mError, Bars1mStats, DailySessionClose, EodIntradayBar, IntradaySession, + SessionCloseCheck, SessionCloseCutoffPolicy, SessionCloseMismatchSample, SessionCloseStats, + BARS_1M_SOURCE_EOD, RTH_END_MINUTE_ET, RTH_START_MINUTE_ET, }; pub use bson_ceo_shorts::{ decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc, From 5df349e82c15fba38c553fbda3dc606eaf420a06 Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 23:47:29 -0500 Subject: [PATCH 11/21] T-130: tests --- tools/curate-etl/tests/bars_1m_qa_contract.rs | 584 ++++++++++++++++++ 1 file changed, 584 insertions(+) create mode 100644 tools/curate-etl/tests/bars_1m_qa_contract.rs diff --git a/tools/curate-etl/tests/bars_1m_qa_contract.rs b/tools/curate-etl/tests/bars_1m_qa_contract.rs new file mode 100644 index 00000000..0ffcc1ef --- /dev/null +++ b/tools/curate-etl/tests/bars_1m_qa_contract.rs @@ -0,0 +1,584 @@ +//! QA contract tests for `bars_1m::build_bars_1m` / `check_session_closes` (T-130 / M2.3a). +//! +//! Uses only the public crate API. Expected Eastern session dates and minutes come from how the +//! fixtures are generated (`et_to_utc_micros(date, hh, mm)`), not from `utc_micros_to_et_local`, +//! and expected split factors come from `SplitTable::cum_factor_after`, so the builder's +//! two-pointer split cursor and ET conversion are checked against independent oracles. + +use std::cmp::Ordering; +use std::collections::{HashMap, HashSet}; + +use curate_etl::{ + build_bars_1m, check_session_closes, check_session_closes_against_bars_1d, et_to_utc_micros, + unadjust_ohlcv, ymd_to_epoch_days, Bar1dRow, Bar1mRow, Bars1mStats, DailySessionClose, + EodIntradayBar, IntradaySession, OhlcvBar, SessionCloseCutoffPolicy, SessionCloseStats, + SplitEvent, SplitTable, BARS_1M_SOURCE_EOD, MAX_MISMATCH_SAMPLES, +}; + +/// Deterministic SplitMix64 so every run sees identical fixtures. +struct Rng(u64); + +impl Rng { + fn next_u64(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + + fn below(&mut self, n: u64) -> u64 { + self.next_u64() % n + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid date") +} + +fn et(date: i32, hour: u8, minute: u8) -> i64 { + et_to_utc_micros(date, hour, minute, 0).expect("valid ET timestamp") +} + +fn bar(key: &str, ts: i64, o: f64, h: f64, l: f64, c: f64, v: f64) -> EodIntradayBar { + EodIntradayBar { + key: key.to_string(), + ts, + open: o, + high: h, + low: l, + close: c, + volume: v, + } +} + +fn flat(key: &str, ts: i64, price: f64, volume: f64) -> EodIntradayBar { + bar(key, ts, price, price, price, price, volume) +} + +fn expected_session(minute_of_day: u16) -> IntradaySession { + if minute_of_day < 570 { + IntradaySession::Pre + } else if minute_of_day < 960 { + IntradaySession::Rth + } else { + IntradaySession::Post + } +} + +fn assert_conservation(stats: &Bars1mStats) { + assert_eq!( + stats.bars_in, + stats.rows_out + + stats.dropped_invalid_ohlc + + stats.dropped_inconsistent_ohlc + + stats.dropped_invalid_volume + + stats.dropped_ts_out_of_range + + stats.duplicate_collapsed + + stats.duplicate_conflict_dropped, + "conservation invariant failed: {stats:?}" + ); + assert_eq!( + stats.rows_out, + stats.pre_rows_out + stats.rth_rows_out + stats.post_rows_out + ); +} + +fn assert_close_invariants(stats: &SessionCloseStats) { + assert_eq!( + stats.checked + stats.unchecked, + stats.rth_sessions, + "{stats:?}" + ); + assert_eq!( + stats.within_tolerance + stats.mismatched, + stats.checked, + "{stats:?}" + ); + assert_eq!( + stats.daily_rows_in, + stats.daily_unique_partners + + stats.daily_invalid_close_dropped + + stats.daily_duplicate_collapsed + + stats.daily_duplicate_conflict_dropped, + "{stats:?}" + ); +} + +fn assert_strictly_sorted(rows: &[Bar1mRow]) { + for w in rows.windows(2) { + let ord = w[0].key.cmp(&w[1].key).then_with(|| w[0].ts.cmp(&w[1].ts)); + assert_eq!( + ord, + Ordering::Less, + "rows not strictly sorted: {:?} / {:?}", + w[0], + w[1] + ); + } +} + +#[test] +fn seeded_clean_bars_match_independent_et_and_cum_factor_oracle_bitwise() { + // Arrange: 40 keys, 0-3 splits each (forward/reverse, some on weekends), bars spread across + // 2023-2025 at arbitrary ET minutes (including 00:00 and 23:59) so EST, EDT and DST-transition + // days are all exercised. + let mut rng = Rng(0x0B45_1A11_7E57_0001); + let ratios = [0.05, 0.1, 0.25, 0.5, 2.0, 3.0, 4.0, 10.0, 1.5]; + let min_date = day(2023, 1, 1); + let span = (day(2025, 12, 31) - min_date + 1) as u64; + + let mut events = Vec::new(); + for k in 0..40 { + for _ in 0..rng.below(4) { + events.push(( + format!("K{k:02}"), + SplitEvent { + ex_date: min_date + rng.below(span) as i32, + ratio: ratios[rng.below(ratios.len() as u64) as usize], + }, + )); + } + } + let splits = SplitTable::from_events(events).expect("valid splits"); + + let mut inputs = Vec::new(); + let mut expected: HashMap<(String, i64), (i32, u16, EodIntradayBar)> = HashMap::new(); + while inputs.len() < 5_000 { + let key = format!("K{:02}", rng.below(40)); + let date = min_date + rng.below(span) as i32; + let minute = rng.below(1_440) as u16; + let (hh, mm) = ((minute / 60) as u8, (minute % 60) as u8); + // Skip wall-clock times that do not exist on spring-forward day. + let Ok(ts) = et_to_utc_micros(date, hh, mm, 0) else { + continue; + }; + if expected.contains_key(&(key.clone(), ts)) { + continue; + } + let low = 1.0 + rng.below(10_000) as f64 / 100.0; + let high = low * (1.0 + rng.below(500) as f64 / 10_000.0); + let open = low + (high - low) * 0.25; + let close = low + (high - low) * 0.75; + let volume = rng.below(1_000_000) as f64; + let b = bar(&key, ts, open, high, low, close, volume); + // Fall-back day repeats 01:xx; keep only the first occurrence's ET minute oracle. + expected.insert((key, ts), (date, minute, b.clone())); + inputs.push(b); + } + + // Act + let built = build_bars_1m(inputs.clone(), &splits); + + // Assert + assert_conservation(&built.stats); + assert_eq!(built.stats.rows_out, inputs.len()); + assert_strictly_sorted(&built.rows); + let mut applied_non_unit = 0usize; + for row in &built.rows { + let (date, minute, ref input) = expected[&(row.key.clone(), row.ts)]; + assert_eq!(row.session_date, date, "ET session_date for {row:?}"); + assert_eq!(row.session, expected_session(minute), "session for {row:?}"); + assert_eq!(row.source, BARS_1M_SOURCE_EOD); + let factor = splits.cum_factor_after(row.key.as_str(), date); + if factor != 1.0 { + applied_non_unit += 1; + } + let want = unadjust_ohlcv( + OhlcvBar { + open: input.open, + high: input.high, + low: input.low, + close: input.close, + volume: input.volume, + }, + factor, + ); + assert_eq!(row.open.to_bits(), want.open.to_bits(), "{row:?}"); + assert_eq!(row.high.to_bits(), want.high.to_bits(), "{row:?}"); + assert_eq!(row.low.to_bits(), want.low.to_bits(), "{row:?}"); + assert_eq!(row.close.to_bits(), want.close.to_bits(), "{row:?}"); + assert_eq!(row.volume.to_bits(), want.volume.to_bits(), "{row:?}"); + } + assert!( + applied_non_unit > 500, + "fixture must exercise splits: {applied_non_unit}" + ); +} + +#[test] +fn et_midnight_is_the_split_boundary_not_utc_midnight_in_est_and_edt() { + // Arrange: 2:1 splits; ex-dates in EDT (2024-06-10) and EST (2025-01-16). + for ex in [day(2024, 6, 10), day(2025, 1, 16)] { + let splits = SplitTable::from_events([( + "S".to_string(), + SplitEvent { + ex_date: ex, + ratio: 2.0, + }, + )]) + .unwrap(); + let last_pre_minute = et(ex - 1, 23, 59); + let first_ex_minute = et(ex, 0, 0); + + // Act + let built = build_bars_1m( + [ + flat("S", first_ex_minute, 10.0, 100.0), + flat("S", last_pre_minute, 10.0, 100.0), + ], + &splits, + ); + + // Assert: 23:59 ET (already the next UTC day) still gets the pre-split factor. + assert_conservation(&built.stats); + assert_eq!(built.rows.len(), 2); + assert_eq!(built.rows[0].session_date, ex - 1); + assert_eq!(built.rows[0].session, IntradaySession::Post); + assert_eq!(built.rows[0].close, 20.0); + assert_eq!(built.rows[0].volume, 50.0); + assert_eq!(built.rows[1].session_date, ex); + assert_eq!(built.rows[1].session, IntradaySession::Pre); + assert_eq!(built.rows[1].close.to_bits(), 10.0_f64.to_bits()); + assert_eq!(built.rows[1].volume.to_bits(), 100.0_f64.to_bits()); + } +} + +#[test] +fn cumulative_factor_spans_multiple_splits_and_weekend_ex_dates() { + // Arrange: 2:1 ex Saturday 2024-03-02, then 1:4 reverse ex Monday 2024-03-11. + let splits = SplitTable::from_events([ + ( + "M".to_string(), + SplitEvent { + ex_date: day(2024, 3, 2), + ratio: 2.0, + }, + ), + ( + "M".to_string(), + SplitEvent { + ex_date: day(2024, 3, 11), + ratio: 0.25, + }, + ), + ]) + .unwrap(); + + // Act + let built = build_bars_1m( + [ + flat("M", et(day(2024, 3, 1), 15, 59), 8.0, 1_000.0), // Fri: both splits ahead + flat("M", et(day(2024, 3, 4), 15, 59), 8.0, 1_000.0), // Mon: only reverse ahead + flat("M", et(day(2024, 3, 11), 15, 59), 8.0, 1_000.0), // ex-date of reverse + ], + &splits, + ); + + // Assert: factor 2*0.25 = 0.5, then 0.25, then 1. + assert_conservation(&built.stats); + let closes: Vec = built.rows.iter().map(|r| r.close).collect(); + let volumes: Vec = built.rows.iter().map(|r| r.volume).collect(); + assert_eq!(closes, vec![4.0, 2.0, 8.0]); + assert_eq!(volumes, vec![2_000.0, 4_000.0, 1_000.0]); +} + +#[test] +fn rth_boundaries_hold_on_dst_transition_sundays() { + // Arrange: spring-forward 2024-03-10 and fall-back 2024-11-03 (EDT->EST). + let splits: SplitTable = SplitTable::default(); + let mut inputs = Vec::new(); + for d in [day(2024, 3, 10), day(2024, 11, 3)] { + for (h, m) in [(9, 29), (9, 30), (15, 59), (16, 0)] { + inputs.push(flat("D", et(d, h, m), 10.0, 1.0)); + } + } + + // Act + let built = build_bars_1m(inputs, &splits); + + // Assert + let sessions: Vec<&str> = built.rows.iter().map(|r| r.session.as_str()).collect(); + assert_eq!( + sessions, + vec!["PRE", "RTH", "RTH", "POST", "PRE", "RTH", "RTH", "POST"] + ); +} + +#[test] +fn seeded_dirty_input_conserves_counts_and_is_permutation_invariant() { + // Arrange: mix of valid bars, every bad-row category, exact and conflicting duplicates. + let mut rng = Rng(0x0B45_1A11_D127_0002); + let splits = SplitTable::from_events([ + ( + "A".to_string(), + SplitEvent { + ex_date: day(2024, 6, 10), + ratio: 10.0, + }, + ), + ( + "B".to_string(), + SplitEvent { + ex_date: day(2024, 6, 12), + ratio: 0.05, + }, + ), + ]) + .unwrap(); + let keys = ["A", "B", "C"]; + let base = et(day(2024, 6, 7), 4, 0); + let mut inputs = Vec::new(); + for _ in 0..3_000 { + let key = keys[rng.below(3) as usize]; + let ts = base + rng.below(8 * 1_440) as i64 * 60_000_000; + let p = 10.0 + rng.below(100) as f64 / 10.0; + let b = match rng.below(12) { + 0 => bar(key, ts, f64::NAN, p, p, p, 1.0), + 1 => bar(key, ts, p, p, p, -p, 1.0), + 2 => bar(key, ts, p, p - 1.0, p, p, 1.0), + 3 => bar(key, ts, p, p, p, p, f64::NEG_INFINITY), + 4 => bar(key, i64::MAX - rng.below(10) as i64, p, p, p, p, 1.0), + 5 => bar(key, ts, p, p, p, p, -0.0), + _ => bar(key, ts, p, p + 0.5, p - 0.5, p, rng.below(1_000) as f64), + }; + inputs.push(b.clone()); + // ~10% exact duplicates, ~5% conflicting duplicates. + match rng.below(20) { + 0 | 1 => inputs.push(b), + 2 => { + let mut c = b; + c.volume += 1.0; + inputs.push(c); + } + _ => {} + } + } + + // Act + let forward = build_bars_1m(inputs.clone(), &splits); + let mut shuffled = inputs.clone(); + for i in (1..shuffled.len()).rev() { + shuffled.swap(i, rng.below(i as u64 + 1) as usize); + } + let permuted = build_bars_1m(shuffled, &splits); + + // Assert + assert_conservation(&forward.stats); + assert_eq!(forward, permuted, "output must not depend on input order"); + assert_strictly_sorted(&forward.rows); + for counter in [ + forward.stats.dropped_invalid_ohlc, + forward.stats.dropped_inconsistent_ohlc, + forward.stats.dropped_invalid_volume, + forward.stats.dropped_ts_out_of_range, + forward.stats.duplicate_collapsed, + forward.stats.duplicate_conflict_dropped, + ] { + assert!( + counter > 0, + "every category must be exercised: {:?}", + forward.stats + ); + } + let unique: HashSet<(String, i64)> = + forward.rows.iter().map(|r| (r.key.clone(), r.ts)).collect(); + assert_eq!(unique.len(), forward.rows.len()); + assert!(forward + .rows + .iter() + .all(|r| r.volume.to_bits() != (-0.0_f64).to_bits())); +} + +#[test] +fn keys_out_ignores_keys_whose_every_bar_is_dropped() { + let splits: SplitTable = SplitTable::default(); + let ts = et(day(2024, 6, 10), 10, 0); + let built = build_bars_1m( + [ + flat("GONE", ts, 10.0, 1.0), + flat("GONE", ts, 10.5, 1.0), // conflict drops the whole group + flat("NAN", ts, f64::NAN, 1.0), + flat("KEEP", ts, 10.0, 1.0), + ], + &splits, + ); + assert_conservation(&built.stats); + assert_eq!(built.stats.keys_out, 1); + assert_eq!(built.rows.len(), 1); + assert_eq!(built.rows[0].key, "KEEP"); +} + +#[test] +fn session_close_tolerance_is_inclusive_and_zero_tolerance_is_accepted() { + let d = day(2024, 6, 10); + let splits: SplitTable = SplitTable::default(); + let built = build_bars_1m([flat("T", et(d, 15, 59), 100.5, 1.0)], &splits); + let daily = [DailySessionClose::new("T".to_string(), d, 100.0)]; + + // rel == 0.5 / 100 == 0.005 exactly -> within tolerance. + let at_edge = check_session_closes(&built.rows, daily.clone(), 0.005).unwrap(); + assert_close_invariants(&at_edge.stats); + assert_eq!(at_edge.stats.within_tolerance, 1); + assert_eq!(at_edge.stats.mismatched, 0); + + let zero = check_session_closes(&built.rows, daily.clone(), 0.0).unwrap(); + assert_eq!(zero.stats.mismatched, 1); + let neg_zero = check_session_closes(&built.rows, daily, -0.0).unwrap(); + assert_eq!(neg_zero.stats.mismatched, 1); +} + +#[test] +fn daily_partner_without_intraday_rows_and_post_only_sessions_are_not_rth_sessions() { + let d1 = day(2024, 6, 10); + let d2 = day(2024, 6, 11); + let splits: SplitTable = SplitTable::default(); + let built = build_bars_1m( + [ + flat("X", et(d1, 15, 59), 50.0, 1.0), + flat("X", et(d2, 16, 30), 99.0, 1.0), // POST only + ], + &splits, + ); + let rows_1d = [ + Bar1dRow { + key: "X".to_string(), + session_date: d1, + open: 50.0, + high: 50.0, + low: 50.0, + close: 50.0, + volume: 1.0, + }, + Bar1dRow { + key: "X".to_string(), + session_date: d2, + open: 50.0, + high: 50.0, + low: 50.0, + close: 50.0, + volume: 1.0, + }, + Bar1dRow { + key: "Y".to_string(), + session_date: d1, + open: 7.0, + high: 7.0, + low: 7.0, + close: 7.0, + volume: 1.0, + }, + ]; + let check = check_session_closes_against_bars_1d( + &built.rows, + &rows_1d, + &SessionCloseCutoffPolicy::standard_rth(), + 0.005, + ) + .unwrap(); + assert_close_invariants(&check.stats); + assert_eq!(check.stats.rth_sessions, 1); + assert_eq!(check.stats.checked, 1); + assert_eq!(check.stats.within_tolerance, 1); + assert_eq!(check.stats.daily_unique_partners, 3); +} + +#[test] +fn early_close_date_cutoff_applies_to_listings_without_override() { + // Arrange: Friday after US Thanksgiving 2024 (13:00 ET close); policy sets only a date cutoff. + let d = day(2024, 11, 29); + let splits: SplitTable = SplitTable::default(); + let built = build_bars_1m( + [ + flat("U", et(d, 12, 59), 40.0, 1.0), + flat("U", et(d, 13, 15), 44.0, 1.0), + flat("V", et(d, 12, 59), 70.0, 1.0), + flat("V", et(d, 15, 59), 77.0, 1.0), + ], + &splits, + ); + let policy = SessionCloseCutoffPolicy::standard_rth().with_date_cutoff(d, et(d, 13, 0)); + let rows_1d = [ + Bar1dRow { + key: "U".to_string(), + session_date: d, + open: 40.0, + high: 40.0, + low: 40.0, + close: 40.0, + volume: 1.0, + }, + Bar1dRow { + key: "V".to_string(), + session_date: d, + open: 70.0, + high: 70.0, + low: 70.0, + close: 70.0, + volume: 1.0, + }, + ]; + + // Act + let check = check_session_closes_against_bars_1d(&built.rows, rows_1d, &policy, 0.005).unwrap(); + + // Assert: both listings resolve to their 12:59 ET bar. + assert_close_invariants(&check.stats); + assert_eq!(check.stats.checked, 2); + assert_eq!(check.stats.mismatched, 0); + assert_eq!(check.stats.max_rel_diff, 0.0); +} + +#[test] +fn split_fixture_cross_check_is_order_independent_and_samples_are_capped() { + // Arrange: 150 sessions on one 1:20 reverse-split key; feed adjusted (empty split table) and + // un-adjusted builds against the same raw daily closes. + let ex = day(2025, 6, 18); + let splits = SplitTable::from_events([( + "NEXM.V".to_string(), + SplitEvent { + ex_date: ex, + ratio: 0.05, + }, + )]) + .unwrap(); + let empty: SplitTable = SplitTable::default(); + let mut bars = Vec::new(); + let mut daily = Vec::new(); + for i in 0..150 { + let d = ex - 150 + i; + let adj_close = 20.0 + f64::from(i) * 0.01; + bars.push(flat("NEXM.V", et(d, 15, 59), adj_close, 1_000.0)); + bars.push(flat("NEXM.V", et(d, 16, 5), adj_close * 1.1, 10.0)); // POST noise + daily.push(DailySessionClose::new( + "NEXM.V".to_string(), + d, + adj_close * 0.05, + )); + } + + // Act + let unadj = build_bars_1m(bars.clone(), &splits); + let still_adj = build_bars_1m(bars, &empty); + let good = check_session_closes(&unadj.rows, daily.clone(), 0.005).unwrap(); + let bad = check_session_closes(&still_adj.rows, daily.clone(), 0.005).unwrap(); + let mut reversed = still_adj.rows.clone(); + reversed.reverse(); + let bad_reversed = check_session_closes(&reversed, daily, 0.005).unwrap(); + + // Assert + assert_close_invariants(&good.stats); + assert_eq!(good.stats.checked, 150); + assert_eq!(good.stats.mismatched, 0); + assert!(good.stats.max_rel_diff < 1e-12); + + assert_close_invariants(&bad.stats); + assert_eq!(bad.stats.mismatched, 150); + assert!(bad.stats.max_rel_diff > 0.005); + assert_eq!(bad.mismatch_samples.len(), MAX_MISMATCH_SAMPLES); + assert_eq!(bad, bad_reversed); + for s in &bad.mismatch_samples { + assert!((s.rel - 19.0).abs() < 1e-9, "rel {s:?}"); + assert_eq!(s.last_rth_ts, et(s.session_date, 15, 59)); + } +} From e7bd019bb6c169df849824aa9c203b1f8c55cfbe Mon Sep 17 00:00:00 2001 From: Studio Date: Mon, 30 Nov 2026 23:58:55 -0500 Subject: [PATCH 12/21] =?UTF-8?q?T-131:=20M2.1b=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`analyze=5Fsignal`=20tool:=20vault-fenced=20short-interest?= =?UTF-8?q?=20signal=20study=20(bars=20+=20`shortsAsOf`=20=E2=86=92=20forw?= =?UTF-8?q?ard-return=20panel=20=E2=86=92=20`analyzeSignal`=20+=20trial=20?= =?UTF-8?q?ledger)=20in=20`libs/research/src/mcp/tools/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/index.ts | 1 + libs/research/src/mcp/tools/analyze-signal.ts | 744 +++++++++ libs/research/src/mcp/tools/query-data.ts | 253 +--- .../src/mcp/tools/vault-fenced-input.ts | 322 ++++ libs/research/test/mcp-analyze-signal.test.ts | 1325 +++++++++++++++++ 5 files changed, 2420 insertions(+), 225 deletions(-) create mode 100644 libs/research/src/mcp/tools/analyze-signal.ts create mode 100644 libs/research/src/mcp/tools/vault-fenced-input.ts create mode 100644 libs/research/test/mcp-analyze-signal.test.ts diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 8b021dbe..1838886b 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -1,4 +1,5 @@ export * from './protocol'; export * from './server'; export * from './stdio'; +export * from './tools/analyze-signal'; export * from './tools/query-data'; diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts new file mode 100644 index 00000000..b33c6df0 --- /dev/null +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -0,0 +1,744 @@ +import { + type IcSummary, + type RecencySplitResult, + type SignalPanelAnalysis, + type SignalPanelDiagnostics as CalcSignalPanelDiagnostics, + analyzeSignalPanel, +} from '@stock-bot/calculations'; +import { z } from 'zod'; +import { + type BarRecord, + type MarketDataStore, + MarketDataStoreValidationError, + type Table, + type TableRow, + type VaultFenceContext, +} from '../../market-data-store'; +import { + SHORTS_SIGNAL_FIELDS, + type ShortsSignalField, + type SignalPanelDiagnostics, + SignalPanelError, + type SignalPanelErrorCode, + buildForwardReturnPanel, + collectBars, + shortsTableToSignalRows, +} from '../../signal-panel'; +import { + type AnalyzeSignalInsufficientDataReason, + type SignalLedgerSeries, + SignalStudyError, + type SignalStudyErrorCode, + type SignalStudyExpression, + type StudyTrialSummary, + analyzeSignal, +} from '../../signal-study'; +import { + type ClusterDeflatedSharpeResult, + HORIZON_BUCKETS, + type HorizonBucket, + TrialLedgerError, + type TrialLedgerErrorCode, + type TrialLedgerExecutor, + UNIVERSE_MARKETS, + type UniverseMarket, +} from '../../trial-ledger'; +import type { McpToolCallResult } from '../protocol'; +import { type McpToolEntry, defineMcpTool } from '../server'; +import { + EXCLUSIVE_LISTING_SELECTOR_MESSAGE, + MCP_MAX_LISTING_IDS, + createListingIdsFieldSchema, + createUniverseFieldSchema, + fenceVaultQueryBounds, + formatMappedStoreError, + hasExclusiveListingSelector, + isValidUtcBoundString, + resolvePreStartUniverseDate, + utcDateOf, + validateVaultCutoffTs, +} from './vault-fenced-input'; + +/** Hard maximum number of explicit `listingIds` accepted by `analyze_signal`. */ +export const ANALYZE_SIGNAL_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS; + +/** Hard maximum forward-return horizon in trading sessions. */ +export const ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS = 252; + +/** Maximum number of latest dated observations exposed in the tool response preview. */ +export const ANALYZE_SIGNAL_MAX_SERIES_POINTS = 100; + +const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const AGENT_PRINCIPAL_RE = + /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; +const UTC_BOUND_ERROR_MESSAGE = + 'Expected YYYY-MM-DD calendar date or UTC ISO-8601 timestamp with timezone offset.'; + +const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE); + +const shortsSignalSpecSchema = z + .object({ + source: z.literal('shorts').describe('Signal data source (currently "shorts").'), + field: z + .enum(SHORTS_SIGNAL_FIELDS) + .describe('Short-interest field to evaluate (shares_short, net_change, or pct_float).'), + }) + .strict() + .describe('Discriminated signal source and field specification.'); + +/** + * Strict Zod input schema for the `analyze_signal` MCP tool. + * + * Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and + * `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them + * or any other unknown top-level or nested key. + */ +export const analyzeSignalInputSchema = z + .object({ + listingIds: createListingIdsFieldSchema( + 'Explicit INT32 listing IDs to study (mutually exclusive with universe).' + ), + universe: createUniverseFieldSchema( + 'Survivorship-free universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).' + ), + from: utcBoundStringSchema.describe( + 'Inclusive study start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.' + ), + to: utcBoundStringSchema.describe( + 'Inclusive study end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.' + ), + asOf: utcBoundStringSchema + .optional() + .describe( + 'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.' + ), + signal: shortsSignalSpecSchema, + horizonSessions: z + .number() + .int() + .min(1) + .max(ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS) + .describe( + `Forward-return horizon in trading sessions (1–${ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS}).` + ), + maxSignalAgeSessions: z + .number() + .int() + .min(0) + .max(Number.MAX_SAFE_INTEGER) + .optional() + .describe('Optional maximum signal age in trading sessions before a signal is treated as stale.'), + universeMarket: z + .enum(UNIVERSE_MARKETS) + .describe('Relatedness-cluster market bucket recorded in trial_ledger.'), + horizonBucket: z + .enum(HORIZON_BUCKETS) + .describe('Relatedness-cluster horizon bucket recorded in trial_ledger.'), + ledgerSeries: z + .enum(['rank_ic', 'quantile_spread']) + .default('rank_ic') + .describe('Daily series recorded to trial_ledger and evaluated for DSR (default rank_ic).'), + campaignId: z + .string() + .regex(LEDGER_UUID_RE, 'Expected a UUID string.') + .optional() + .describe('Optional research campaign UUID recorded in trial_ledger.'), + hypothesisId: z + .string() + .regex(LEDGER_UUID_RE, 'Expected a UUID string.') + .optional() + .describe('Optional research hypothesis UUID recorded in trial_ledger.'), + adjustment: z + .enum(['raw', 'split', 'total']) + .default('raw') + .describe('Bar price adjustment mode (default raw).'), + }) + .strict() + .refine(hasExclusiveListingSelector, EXCLUSIVE_LISTING_SELECTOR_MESSAGE); + +export type AnalyzeSignalInput = z.infer; + +/** Server-side injected configuration for {@link createAnalyzeSignalTool}. */ +export interface AnalyzeSignalToolOptions { + readonly store: MarketDataStore; + readonly ledger: TrialLedgerExecutor; + readonly vaultContext: Pick; + readonly principalId: string; +} + +/** Single dated observation in the bounded series preview. */ +export interface AnalyzeSignalSeriesPoint { + readonly date: string; + readonly value: number; +} + +/** Bounded preview of the selected ledger series (latest 100 observations). */ +export interface AnalyzeSignalSeriesPreview { + readonly series: SignalLedgerSeries; + readonly totalCount: number; + readonly truncated: boolean; + readonly points: readonly AnalyzeSignalSeriesPoint[]; +} + +/** Projected quantile-spread summary without raw per-bucket typed arrays. */ +export interface AnalyzeSignalQuantilesSummary { + readonly quantiles: number; + readonly validDates: number; + readonly skippedDates: number; + readonly bucketMeanReturns: readonly (number | null)[]; + readonly spreadSummary: IcSummary; +} + +/** Projected top/bottom quantile membership turnover summary. */ +export interface AnalyzeSignalTurnoverSummary { + readonly count: number; + readonly meanTopTurnover: number | null; + readonly meanBottomTurnover: number | null; +} + +/** Bounded summary projection of {@link SignalPanelAnalysis}. */ +export interface AnalyzeSignalAnalysisSummary { + readonly pearsonIc: IcSummary; + readonly rankIc: IcSummary; + readonly quantiles: AnalyzeSignalQuantilesSummary; + readonly turnover: AnalyzeSignalTurnoverSummary; + readonly recency: RecencySplitResult; + readonly diagnostics: CalcSignalPanelDiagnostics; + readonly ledgerSeries: AnalyzeSignalSeriesPreview; +} + +interface AnalyzeSignalResultBase { + readonly scope: 'vault_fenced'; + readonly vaultCutoffTs: number; + readonly vaultCutoffDate: string; + readonly signal: { + readonly source: 'shorts'; + readonly field: ShortsSignalField; + }; + readonly horizonSessions: number; + readonly adjustment: 'raw' | 'split' | 'total'; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly fromMs: number; + readonly toMs: number; + readonly asOfMs: number; + readonly clampedTo: boolean; + readonly clampedAsOf: boolean; + readonly listingCount: number; + readonly panelDiagnostics: SignalPanelDiagnostics; + readonly analysis: AnalyzeSignalAnalysisSummary; +} + +/** Structured JSON payload serialized into the `analyze_signal` MCP text result. */ +export type AnalyzeSignalResultPayload = + | (AnalyzeSignalResultBase & { + readonly status: 'ok'; + readonly trial: StudyTrialSummary; + readonly deflatedSharpe: ClusterDeflatedSharpeResult; + }) + | (AnalyzeSignalResultBase & { + readonly status: 'insufficient_data'; + readonly reason: AnalyzeSignalInsufficientDataReason; + }); + +const ZERO_PANEL_DIAGNOSTICS: SignalPanelDiagnostics = { + vaultExcludedDates: 0, + droppedNoSignal: 0, + droppedStaleSignal: 0, + droppedMissingForwardBar: 0, + droppedNonPositiveClose: 0, + duplicateBars: 0, +}; + +const SIGNAL_PANEL_ERROR_MESSAGES: Readonly> = { + invalid_input: 'Invalid signal panel input.', + invalid_horizon: 'Invalid forward-return horizon.', + invalid_option: 'Invalid signal panel option.', + invalid_date: 'Invalid signal panel date.', + invalid_bar: 'Market bar data failed panel validation.', + invalid_signal: 'Signal table data failed panel validation.', + duplicate_bar: 'Conflicting duplicate daily bars detected.', +}; + +const SIGNAL_STUDY_ERROR_MESSAGES: Readonly> = { + invalid_request: 'Invalid signal study request.', + empty_panel: 'Signal panel is empty.', + invalid_date: 'Invalid signal study date.', + unsorted_dates: 'Signal panel dates are not strictly ascending.', + duplicate_date: 'Duplicate date detected in signal panel.', + invalid_panel: 'Signal panel failed validation.', + invalid_option: 'Invalid signal study option.', + dsr_read_failed: 'Trial was recorded, but cluster deflated Sharpe evaluation failed.', +}; + +const TRIAL_LEDGER_ERROR_MESSAGES: Readonly>> = { + VAULT_FENCE_VIOLATION: 'Sample window violates the Vault holdout cutoff.', + INVALID_PRINCIPAL: 'Invalid trial ledger principal.', + INVALID_UUID: 'Invalid trial ledger UUID.', + INVALID_SAMPLE_WINDOW: 'Invalid trial ledger sample window.', + INVALID_DATE: 'Invalid trial ledger date.', + SERIES_TOO_SHORT: 'Observation series is too short for trial ledger recording.', + ZERO_VARIANCE_SERIES: 'Observation series has zero variance.', + TRIAL_NOT_FOUND: 'Recorded trial could not be found in trial ledger.', +}; + +function sortAndDedupeListingIds(ids: readonly number[]): number[] { + return [...new Set(ids)].sort((a, b) => a - b); +} + +function projectAnalysisSummary( + analysis: SignalPanelAnalysis, + selectedSeries: SignalLedgerSeries +): AnalyzeSignalAnalysisSummary { + const rawDates = selectedSeries === 'rank_ic' ? analysis.dates : analysis.quantiles.dates; + const rawValues = + selectedSeries === 'rank_ic' ? analysis.rankIcSeries : analysis.quantiles.spreadSeries; + const totalCount = Math.min(rawDates.length, rawValues.length); + const truncated = totalCount > ANALYZE_SIGNAL_MAX_SERIES_POINTS; + const startIdx = truncated ? totalCount - ANALYZE_SIGNAL_MAX_SERIES_POINTS : 0; + const points: AnalyzeSignalSeriesPoint[] = []; + + for (let i = startIdx; i < totalCount; i += 1) { + points.push({ + date: rawDates[i] as string, + value: rawValues[i] as number, + }); + } + + return { + pearsonIc: analysis.pearsonIc, + rankIc: analysis.rankIc, + quantiles: { + quantiles: analysis.quantiles.quantiles, + validDates: analysis.quantiles.validDates, + skippedDates: analysis.quantiles.skippedDates, + bucketMeanReturns: [...analysis.quantiles.bucketMeanReturns], + spreadSummary: analysis.quantiles.spreadSummary, + }, + turnover: { + count: analysis.turnover.count, + meanTopTurnover: analysis.turnover.meanTopTurnover, + meanBottomTurnover: analysis.turnover.meanBottomTurnover, + }, + recency: analysis.recency, + diagnostics: analysis.diagnostics, + ledgerSeries: { + series: selectedSeries, + totalCount, + truncated, + points, + }, + }; +} + +function filterEligibleBars( + bars: readonly BarRecord[], + listingIdSet: ReadonlySet, + fromMs: number, + toMs: number, + asOfMs: number, + vaultCutoffTs: number, + vaultCutoffDate: string +): BarRecord[] { + const eligible: BarRecord[] = []; + for (let i = 0; i < bars.length; i += 1) { + const row = bars[i]; + if (typeof row !== 'object' || row === null) { + eligible.push(row as unknown as BarRecord); + continue; + } + if (typeof row.ts === 'number' && Number.isFinite(row.ts)) { + if ( + row.ts < fromMs || + row.ts > toMs || + row.ts >= vaultCutoffTs || + utcDateOf(row.ts) >= vaultCutoffDate + ) { + continue; + } + } + if (typeof row.knownAt === 'number' && Number.isFinite(row.knownAt)) { + if (row.knownAt > asOfMs || row.knownAt >= vaultCutoffTs) { + continue; + } + } + if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) { + continue; + } + eligible.push(row); + } + return eligible; +} + +function filterEligibleShortsTable( + table: Table, + listingIdSet: ReadonlySet, + fromUtcDate: string, + toUtcDate: string, + asOfMs: number, + vaultCutoffTs: number, + vaultCutoffDate: string +): Table { + if ( + typeof table !== 'object' || + table === null || + !Array.isArray(table.columns) || + !Array.isArray(table.rows) + ) { + return table; + } + + const eligibleRows: TableRow[] = []; + for (let i = 0; i < table.rows.length; i += 1) { + const row = table.rows[i]; + if (typeof row !== 'object' || row === null) { + eligibleRows.push(row as TableRow); + continue; + } + const knownAt = row.known_at; + if (typeof knownAt === 'number' && Number.isFinite(knownAt)) { + if (knownAt > asOfMs || knownAt >= vaultCutoffTs) { + continue; + } + } + const reportDate = row.report_date; + if (typeof reportDate === 'string') { + if (reportDate < fromUtcDate || reportDate > toUtcDate || reportDate >= vaultCutoffDate) { + continue; + } + } + const listingId = row.listing_id; + if (typeof listingId === 'number' && !listingIdSet.has(listingId)) { + continue; + } + eligibleRows.push(row); + } + + return { + columns: table.columns, + rows: eligibleRows, + }; +} + +function buildCanonicalStudyExpression(params: { + readonly input: AnalyzeSignalInput; + readonly listingIds: readonly number[]; + readonly universeSnapshotDate: string | null; + readonly fromMs: number; + readonly toMs: number; + readonly asOfMs: number; +}): SignalStudyExpression { + const { input, listingIds, universeSnapshotDate, fromMs, toMs, asOfMs } = params; + return { + expression: `mcp:analyze_signal:v1:${input.signal.source}:${input.signal.field}`, + params: { + version: 1, + signalSource: input.signal.source, + signalField: input.signal.field, + horizonSessions: input.horizonSessions, + maxSignalAgeSessions: input.maxSignalAgeSessions ?? null, + adjustment: input.adjustment, + ledgerSeries: input.ledgerSeries, + fromMs, + toMs, + asOfMs, + }, + universe: + input.universe !== undefined + ? { + kind: 'universe', + ref: input.universe, + snapshotDate: universeSnapshotDate, + listingIds, + } + : { + kind: 'listingIds', + listingIds, + }, + horizon: `${input.horizonSessions}d`, + }; +} + +function formatMappedAnalyzeSignalError(err: unknown): McpToolCallResult { + const storeMapped = formatMappedStoreError(err); + if (storeMapped !== null) { + return storeMapped; + } + + if (err instanceof SignalPanelError) { + const detail = Object.prototype.hasOwnProperty.call(SIGNAL_PANEL_ERROR_MESSAGES, err.code) + ? SIGNAL_PANEL_ERROR_MESSAGES[err.code] + : 'Signal panel construction failed.'; + return { + content: [{ type: 'text', text: `SignalPanelError: ${detail}` }], + isError: true, + }; + } + + if (err instanceof SignalStudyError) { + const detail = Object.prototype.hasOwnProperty.call(SIGNAL_STUDY_ERROR_MESSAGES, err.code) + ? SIGNAL_STUDY_ERROR_MESSAGES[err.code] + : 'Signal study execution failed.'; + return { + content: [{ type: 'text', text: `SignalStudyError: ${detail}` }], + isError: true, + }; + } + + if (err instanceof TrialLedgerError) { + const detail = + Object.prototype.hasOwnProperty.call(TRIAL_LEDGER_ERROR_MESSAGES, err.code) && + TRIAL_LEDGER_ERROR_MESSAGES[err.code] !== undefined + ? TRIAL_LEDGER_ERROR_MESSAGES[err.code] + : 'Trial ledger operation failed.'; + return { + content: [{ type: 'text', text: `TrialLedgerError: ${detail}` }], + isError: true, + }; + } + + return { + content: [{ type: 'text', text: 'Error: Tool execution failed.' }], + isError: true, + }; +} + +function validateFactoryOptions(options: AnalyzeSignalToolOptions): number { + if ( + typeof options.store !== 'object' || + options.store === null || + typeof options.store.bars !== 'function' || + typeof options.store.shortsAsOf !== 'function' || + typeof options.store.universe !== 'function' + ) { + throw new MarketDataStoreValidationError( + 'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, and `universe`.', + 'store' + ); + } + + if ( + typeof options.ledger !== 'object' || + options.ledger === null || + typeof options.ledger.query !== 'function' + ) { + throw new SignalStudyError( + 'invalid_request', + 'Invalid `ledger`: expected a TrialLedgerExecutor implementing `query`.' + ); + } + + if ( + typeof options.principalId !== 'string' || + (options.principalId !== 'operator' && !AGENT_PRINCIPAL_RE.test(options.principalId)) + ) { + throw new TrialLedgerError( + 'INVALID_PRINCIPAL', + `Invalid \`principalId\`: "${String(options.principalId)}".` + ); + } + + return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs); +} + +/** + * Creates the Vault-fenced `analyze_signal` MCP tool backed by an injected + * {@link MarketDataStore} and {@link TrialLedgerExecutor}. + * + * Enforces `scope: 'vault_fenced'`, fences bounds before any store call, + * resolves named universes strictly prior to the study start date, filters + * bars and shorts defensively against the effective window and Vault cutoff, + * builds the forward-return panel, runs `analyzeSignal` with the injected + * research principal, and returns a bounded summary payload. + */ +export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpToolEntry { + const vaultCutoffTs = validateFactoryOptions(options); + const { store, ledger, principalId } = options; + + return defineMcpTool({ + name: 'analyze_signal', + description: + 'Run a Vault-fenced cross-sectional short-interest signal study and record eligible trials to trial_ledger.', + inputSchema: analyzeSignalInputSchema, + async handler(input: AnalyzeSignalInput): Promise { + try { + const fenced = fenceVaultQueryBounds( + { + from: input.from, + to: input.to, + asOf: input.asOf, + }, + vaultCutoffTs + ); + + let listingIds: number[]; + let universeSnapshotDate: string | null = null; + + if (input.universe !== undefined) { + universeSnapshotDate = resolvePreStartUniverseDate( + fenced.fromMs, + fenced.asOfMs, + fenced.asOfSubMs + ); + const resolved = await store.universe({ + ref: input.universe, + date: universeSnapshotDate, + }); + listingIds = sortAndDedupeListingIds(resolved); + } else { + listingIds = sortAndDedupeListingIds(input.listingIds ?? []); + } + + const basePayloadFields = { + scope: 'vault_fenced' as const, + vaultCutoffTs, + vaultCutoffDate: fenced.vaultCutoffDate, + signal: { + source: input.signal.source, + field: input.signal.field, + }, + horizonSessions: input.horizonSessions, + adjustment: input.adjustment, + universeMarket: input.universeMarket, + horizonBucket: input.horizonBucket, + fromMs: fenced.fromMs, + toMs: fenced.toMs, + asOfMs: fenced.asOfMs, + clampedTo: fenced.clampedTo, + clampedAsOf: fenced.clampedAsOf, + listingCount: listingIds.length, + }; + + if (listingIds.length === 0) { + const emptyAnalysis = analyzeSignalPanel([], { + vaultCutoffDate: fenced.vaultCutoffDate, + }); + const payload: AnalyzeSignalResultPayload = { + ...basePayloadFields, + status: 'insufficient_data', + reason: 'too_few_observations', + panelDiagnostics: ZERO_PANEL_DIAGNOSTICS, + analysis: projectAnalysisSummary(emptyAnalysis, input.ledgerSeries), + }; + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } + + const rawBars = await collectBars( + store.bars({ + listingIds, + timeframe: '1d', + from: input.from, + to: fenced.effectiveFencedTo, + adjustment: input.adjustment, + asOf: fenced.effectiveFencedAsOf, + scope: 'vault_fenced', + }) + ); + + const rawShortsTable = await store.shortsAsOf({ + listingIds, + from: input.from, + to: fenced.effectiveFencedTo, + asOf: fenced.effectiveFencedAsOf, + }); + + const listingIdSet = new Set(listingIds); + const eligibleBars = filterEligibleBars( + rawBars, + listingIdSet, + fenced.fromMs, + fenced.toMs, + fenced.asOfMs, + vaultCutoffTs, + fenced.vaultCutoffDate + ); + + const eligibleShortsTable = filterEligibleShortsTable( + rawShortsTable, + listingIdSet, + utcDateOf(fenced.fromMs), + utcDateOf(fenced.toMs), + fenced.asOfMs, + vaultCutoffTs, + fenced.vaultCutoffDate + ); + + const signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); + const built = buildForwardReturnPanel({ + bars: eligibleBars, + signals, + horizonSessions: input.horizonSessions, + vaultCutoffDate: fenced.vaultCutoffDate, + ...(input.maxSignalAgeSessions !== undefined + ? { maxSignalAgeSessions: input.maxSignalAgeSessions } + : {}), + }); + + if (built.panel.length === 0) { + const emptyAnalysis = analyzeSignalPanel([], { + vaultCutoffDate: fenced.vaultCutoffDate, + }); + const payload: AnalyzeSignalResultPayload = { + ...basePayloadFields, + status: 'insufficient_data', + reason: 'too_few_observations', + panelDiagnostics: built.diagnostics, + analysis: projectAnalysisSummary(emptyAnalysis, input.ledgerSeries), + }; + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } + + const expression = buildCanonicalStudyExpression({ + input, + listingIds, + universeSnapshotDate, + fromMs: fenced.fromMs, + toMs: fenced.toMs, + asOfMs: fenced.asOfMs, + }); + + const studyResult = await analyzeSignal(ledger, { + principalId, + ...(input.campaignId !== undefined ? { campaignId: input.campaignId } : {}), + ...(input.hypothesisId !== undefined ? { hypothesisId: input.hypothesisId } : {}), + universeMarket: input.universeMarket, + horizonBucket: input.horizonBucket, + expression, + panel: built.panel, + vaultCutoffDate: fenced.vaultCutoffDate, + ledgerSeries: input.ledgerSeries, + }); + + const analysisSummary = projectAnalysisSummary(studyResult.analysis, input.ledgerSeries); + + const payload: AnalyzeSignalResultPayload = + studyResult.status === 'ok' + ? { + ...basePayloadFields, + status: 'ok', + panelDiagnostics: built.diagnostics, + analysis: analysisSummary, + trial: studyResult.trial, + deflatedSharpe: studyResult.deflatedSharpe, + } + : { + ...basePayloadFields, + status: 'insufficient_data', + reason: studyResult.reason, + panelDiagnostics: built.diagnostics, + analysis: analysisSummary, + }; + + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } catch (err: unknown) { + return formatMappedAnalyzeSignalError(err); + } + }, + }); +} diff --git a/libs/research/src/mcp/tools/query-data.ts b/libs/research/src/mcp/tools/query-data.ts index 5cfdc92a..b65fff46 100644 --- a/libs/research/src/mcp/tools/query-data.ts +++ b/libs/research/src/mcp/tools/query-data.ts @@ -4,24 +4,20 @@ import { type MarketDataStore, MarketDataStoreValidationError, type VaultFenceContext, - VaultHoldoutFenceError, - VaultScopeNotAuthorizedError, - applyVaultFence, } from '../../market-data-store'; -import { - AdjFactorsSnapshotError, - type AdjFactorsSnapshotErrorCode, - MarketDataStoreNotImplementedError, -} from '../../market-data-store-duckdb'; import type { McpToolCallResult } from '../protocol'; import { type McpToolEntry, defineMcpTool } from '../server'; - -const INT32_MIN = -2_147_483_648; -const INT32_MAX = 2_147_483_647; -const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; -const MS_PER_DAY = 86_400_000; -const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; -const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/; +import { + EXCLUSIVE_LISTING_SELECTOR_MESSAGE, + MCP_MAX_LISTING_IDS, + createListingIdsFieldSchema, + createUniverseFieldSchema, + fenceVaultQueryBounds, + formatMappedStoreError, + hasExclusiveListingSelector, + resolveUniverseDate, + validateVaultCutoffTs, +} from './vault-fenced-input'; /** Default maximum number of bar rows returned by `query_data`. */ export const QUERY_DATA_DEFAULT_LIMIT = 500; @@ -30,7 +26,7 @@ export const QUERY_DATA_DEFAULT_LIMIT = 500; export const QUERY_DATA_MAX_LIMIT = 5_000; /** Hard maximum number of explicit `listingIds` accepted by `query_data`. */ -export const QUERY_DATA_MAX_LISTING_IDS = 500; +export const QUERY_DATA_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS; /** * Strict Zod input schema for the `query_data` MCP tool. @@ -40,17 +36,12 @@ export const QUERY_DATA_MAX_LISTING_IDS = 500; */ export const queryDataInputSchema = z .object({ - listingIds: z - .array(z.number().int().min(INT32_MIN).max(INT32_MAX)) - .min(1) - .max(QUERY_DATA_MAX_LISTING_IDS) - .optional() - .describe('Explicit INT32 listing IDs to query (mutually exclusive with universe).'), - universe: z - .string() - .min(1) - .optional() - .describe('Universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).'), + listingIds: createListingIdsFieldSchema( + 'Explicit INT32 listing IDs to query (mutually exclusive with universe).' + ), + universe: createUniverseFieldSchema( + 'Universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).' + ), from: z .string() .min(1) @@ -83,10 +74,7 @@ export const queryDataInputSchema = z ), }) .strict() - .refine( - data => (data.listingIds !== undefined) !== (data.universe !== undefined), - 'Exactly one of "listingIds" or "universe" must be provided.' - ); + .refine(hasExclusiveListingSelector, EXCLUSIVE_LISTING_SELECTOR_MESSAGE); export type QueryDataInput = z.infer; @@ -113,166 +101,7 @@ export interface QueryDataResultPayload { readonly rows: readonly BarRecord[]; } -const SAFE_VALIDATION_FIELDS: ReadonlySet = new Set([ - 'from', - 'to', - 'asOf', - 'date', - 'ref', - 'listingIds', - 'timeframe', - 'adjustment', - 'scope', - 'limit', -]); - -const SAFE_STORE_METHODS: ReadonlySet = new Set([ - 'bars', - 'crossSection', - 'fundamentalsAsOf', - 'events', - 'shortsAsOf', - 'macroAsOf', - 'fx', - 'universe', -]); - -const ADJ_SNAPSHOT_ERROR_MESSAGES: Readonly> = { - missing_snapshot: - 'Adjusted bars require a verified point-in-time fenced adj_factors snapshot.', - missing_metadata: 'Required adj_factors snapshot metadata is missing.', - invalid_metadata: 'adj_factors snapshot metadata is invalid.', - unsupported_version: 'adj_factors snapshot metadata version is unsupported.', - retrospective_rejected: - 'Retrospective adj_factors snapshots are rejected for point-in-time queries.', - incompatible_fence: - 'adj_factors snapshot fence does not match the query asOf or Vault cutoff.', - path_mismatch: 'adj_factors snapshot metadata does not match the configured artifact.', - unpinned_mutable_path: - 'Adjusted bars require a pinned or immutable adj_factors snapshot artifact.', -}; - -function utcDateOf(epochMs: number): string { - return new Date(epochMs).toISOString().slice(0, 10); -} - -function extractExplicitSubMsMicros(raw: string): number { - const match = ISO_FRACTIONAL_RE.exec(raw); - if (match === null) { - return 0; - } - const frac = match[1] ?? ''; - if (frac.length <= 3) { - return 0; - } - const microDigits = frac.slice(3, 6).padEnd(3, '0'); - return Number(microDigits); -} - -function resolveToSubMsMicros(rawTo: string, clampedTo: boolean): number { - if (clampedTo || DATE_ONLY_RE.test(rawTo)) { - return 999; - } - return extractExplicitSubMsMicros(rawTo); -} - -function resolveAsOfSubMsMicros(rawAsOf: string | undefined, clampedAsOf: boolean): number { - if (clampedAsOf || rawAsOf === undefined || DATE_ONLY_RE.test(rawAsOf)) { - return 999; - } - return extractExplicitSubMsMicros(rawAsOf); -} - -function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { - const isoMs = new Date(epochMs).toISOString(); - if (subMsMicros === 0) { - return isoMs; - } - const extra = String(subMsMicros).padStart(3, '0'); - return `${isoMs.slice(0, -1)}${extra}Z`; -} - -function resolveCompletedUtcDate(epochMs: number, subMsMicros: number): string { - const dayStartMs = Math.floor(epochMs / MS_PER_DAY) * MS_PER_DAY; - const dayEndMs = dayStartMs + MS_PER_DAY - 1; - if (epochMs === dayEndMs && subMsMicros === 999) { - return utcDateOf(dayStartMs); - } - return utcDateOf(dayStartMs - MS_PER_DAY); -} - -function resolveUniverseDate( - toMs: number, - toSubMs: number, - asOfMs: number, - asOfSubMs: number -): string { - if (asOfMs < toMs || (asOfMs === toMs && asOfSubMs < toSubMs)) { - return resolveCompletedUtcDate(asOfMs, asOfSubMs); - } - return resolveCompletedUtcDate(toMs, toSubMs); -} - -function formatMappedStoreError(err: unknown): McpToolCallResult | null { - if (err instanceof VaultHoldoutFenceError) { - return { - content: [ - { - type: 'text', - text: 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.', - }, - ], - isError: true, - }; - } - - if (err instanceof VaultScopeNotAuthorizedError) { - return { - content: [ - { - type: 'text', - text: "VaultScopeNotAuthorizedError: Data scope 'vault_evaluation_only' is not permitted through MCP.", - }, - ], - isError: true, - }; - } - - if (err instanceof MarketDataStoreValidationError) { - const text = - err.field !== undefined && SAFE_VALIDATION_FIELDS.has(err.field) - ? `MarketDataStoreValidationError: Invalid query parameter "${err.field}".` - : 'MarketDataStoreValidationError: Query parameters failed store validation.'; - return { - content: [{ type: 'text', text }], - isError: true, - }; - } - - if (err instanceof MarketDataStoreNotImplementedError) { - const text = SAFE_STORE_METHODS.has(err.method) - ? `MarketDataStoreNotImplementedError: Store operation "${err.method}" is not supported for this query.` - : 'MarketDataStoreNotImplementedError: Requested store operation is not supported.'; - return { - content: [{ type: 'text', text }], - isError: true, - }; - } - - if (err instanceof AdjFactorsSnapshotError) { - const detail = Object.prototype.hasOwnProperty.call(ADJ_SNAPSHOT_ERROR_MESSAGES, err.code) - ? ADJ_SNAPSHOT_ERROR_MESSAGES[err.code] - : 'Adjusted bars snapshot verification failed.'; - return { - content: [{ type: 'text', text: `AdjFactorsSnapshotError: ${detail}` }], - isError: true, - }; - } - - return null; -} - -function validateFactoryOptions(options: QueryDataToolOptions): void { +function validateFactoryOptions(options: QueryDataToolOptions): number { if ( typeof options.store !== 'object' || options.store === null || @@ -285,18 +114,7 @@ function validateFactoryOptions(options: QueryDataToolOptions): void { ); } - const cutoffTs = options.vaultContext?.vaultCutoffTs; - if ( - typeof cutoffTs !== 'number' || - !Number.isFinite(cutoffTs) || - !Number.isSafeInteger(cutoffTs) || - Math.abs(cutoffTs) >= MAX_ECMASCRIPT_EPOCH_MS - ) { - throw new MarketDataStoreValidationError( - `Invalid \`vaultContext.vaultCutoffTs\`: ${String(cutoffTs)}.`, - 'vaultCutoffTs' - ); - } + return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs); } /** @@ -309,9 +127,8 @@ function validateFactoryOptions(options: QueryDataToolOptions): void { * hard max {@link QUERY_DATA_MAX_LIMIT}). */ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry { - validateFactoryOptions(options); + const vaultCutoffTs = validateFactoryOptions(options); const { store } = options; - const vaultCutoffTs = options.vaultContext.vaultCutoffTs; return defineMcpTool({ name: 'query_data', @@ -320,30 +137,24 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry inputSchema: queryDataInputSchema, async handler(input: QueryDataInput): Promise { try { - const fenced = applyVaultFence( + const fenced = fenceVaultQueryBounds( { from: input.from, to: input.to, asOf: input.asOf, - scope: 'vault_fenced', }, - { - vaultCutoffTs, - vaultOperatorAuthorized: false, - } + vaultCutoffTs ); const effectiveLimit = input.limit; - const toSubMs = resolveToSubMsMicros(input.to, fenced.clampedTo); - const asOfSubMs = resolveAsOfSubMsMicros(input.asOf, fenced.clampedAsOf); let listingIds: number[]; if (input.universe !== undefined) { const universeDate = resolveUniverseDate( fenced.toMs, - toSubMs, + fenced.toSubMs, fenced.asOfMs, - asOfSubMs + fenced.asOfSubMs ); const resolved = await store.universe({ ref: input.universe, @@ -374,21 +185,13 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry listingIds = [...(input.listingIds ?? [])]; } - const effectiveFencedTo = fenced.clampedTo - ? formatUtcIsoWithMicros(fenced.toMs, 999) - : input.to; - const effectiveFencedAsOf = - fenced.clampedAsOf || input.asOf === undefined - ? formatUtcIsoWithMicros(fenced.asOfMs, 999) - : input.asOf; - const stream = store.bars({ listingIds, timeframe: input.timeframe, from: input.from, - to: effectiveFencedTo, + to: fenced.effectiveFencedTo, adjustment: input.adjustment, - asOf: effectiveFencedAsOf, + asOf: fenced.effectiveFencedAsOf, scope: 'vault_fenced', }); diff --git a/libs/research/src/mcp/tools/vault-fenced-input.ts b/libs/research/src/mcp/tools/vault-fenced-input.ts new file mode 100644 index 00000000..cf74cf67 --- /dev/null +++ b/libs/research/src/mcp/tools/vault-fenced-input.ts @@ -0,0 +1,322 @@ +import { z } from 'zod'; +import { + type FencedTimeRange, + MarketDataStoreValidationError, + VaultHoldoutFenceError, + VaultScopeNotAuthorizedError, + applyVaultFence, +} from '../../market-data-store'; +import { + AdjFactorsSnapshotError, + type AdjFactorsSnapshotErrorCode, + MarketDataStoreNotImplementedError, +} from '../../market-data-store-duckdb'; +import type { McpToolCallResult } from '../protocol'; + +export const INT32_MIN = -2_147_483_648; +export const INT32_MAX = 2_147_483_647; +export const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; +export const MS_PER_DAY = 86_400_000; + +/** Hard maximum number of explicit `listingIds` accepted by Vault-fenced MCP tools. */ +export const MCP_MAX_LISTING_IDS = 500; + +const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; +const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/; + +export const EXCLUSIVE_LISTING_SELECTOR_MESSAGE = + 'Exactly one of "listingIds" or "universe" must be provided.'; + +/** Returns true when exactly one of `listingIds` or `universe` is supplied. */ +export function hasExclusiveListingSelector(data: { + readonly listingIds?: readonly number[]; + readonly universe?: string; +}): boolean { + return (data.listingIds !== undefined) !== (data.universe !== undefined); +} + +/** Shared Zod field schema for explicit INT32 `listingIds` (1–500). */ +export function createListingIdsFieldSchema(description: string) { + return z + .array(z.number().int().min(INT32_MIN).max(INT32_MAX)) + .min(1) + .max(MCP_MAX_LISTING_IDS) + .optional() + .describe(description); +} + +/** Shared Zod field schema for a named `universe` reference. */ +export function createUniverseFieldSchema(description: string) { + return z.string().min(1).optional().describe(description); +} + +/** + * Validates that a raw string is a valid calendar date (`YYYY-MM-DD`) or + * UTC ISO-8601 timestamp with an explicit timezone offset (`Z` or `±HH:MM`). + */ +export function isValidUtcBoundString(raw: string): boolean { + try { + applyVaultFence( + { from: raw, to: raw, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ); + return true; + } catch { + return false; + } +} + +/** Validates an injected server-side `vaultCutoffTs` epoch-ms boundary. */ +export function validateVaultCutoffTs(cutoffTs: unknown): number { + if ( + typeof cutoffTs !== 'number' || + !Number.isFinite(cutoffTs) || + !Number.isSafeInteger(cutoffTs) || + Math.abs(cutoffTs) >= MAX_ECMASCRIPT_EPOCH_MS + ) { + throw new MarketDataStoreValidationError( + `Invalid \`vaultContext.vaultCutoffTs\`: ${String(cutoffTs)}.`, + 'vaultCutoffTs' + ); + } + return cutoffTs; +} + +/** Returns the UTC calendar date (`YYYY-MM-DD`) for an epoch-ms timestamp. */ +export function utcDateOf(epochMs: number): string { + return new Date(epochMs).toISOString().slice(0, 10); +} + +export function extractExplicitSubMsMicros(raw: string): number { + const match = ISO_FRACTIONAL_RE.exec(raw); + if (match === null) { + return 0; + } + const frac = match[1] ?? ''; + if (frac.length <= 3) { + return 0; + } + const microDigits = frac.slice(3, 6).padEnd(3, '0'); + return Number(microDigits); +} + +export function resolveToSubMsMicros(rawTo: string, clampedTo: boolean): number { + if (clampedTo || DATE_ONLY_RE.test(rawTo)) { + return 999; + } + return extractExplicitSubMsMicros(rawTo); +} + +export function resolveAsOfSubMsMicros(rawAsOf: string | undefined, clampedAsOf: boolean): number { + if (clampedAsOf || rawAsOf === undefined || DATE_ONLY_RE.test(rawAsOf)) { + return 999; + } + return extractExplicitSubMsMicros(rawAsOf); +} + +export function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { + const isoMs = new Date(epochMs).toISOString(); + if (subMsMicros === 0) { + return isoMs; + } + const extra = String(subMsMicros).padStart(3, '0'); + return `${isoMs.slice(0, -1)}${extra}Z`; +} + +/** + * Resolves the latest completed UTC calendar date at or before `(epochMs, subMsMicros)`. + * A full day is completed only at `23:59:59.999999Z`; any earlier instant resolves + * to the preceding UTC calendar date. + */ +export function resolveCompletedUtcDate(epochMs: number, subMsMicros: number): string { + const dayStartMs = Math.floor(epochMs / MS_PER_DAY) * MS_PER_DAY; + const dayEndMs = dayStartMs + MS_PER_DAY - 1; + if (epochMs === dayEndMs && subMsMicros === 999) { + return utcDateOf(dayStartMs); + } + return utcDateOf(dayStartMs - MS_PER_DAY); +} + +/** + * Resolves the completed UTC date at `min(effectiveTo, effectiveAsOf)` for point-in-time + * universe resolution in `query_data`. + */ +export function resolveUniverseDate( + toMs: number, + toSubMs: number, + asOfMs: number, + asOfSubMs: number +): string { + if (asOfMs < toMs || (asOfMs === toMs && asOfSubMs < toSubMs)) { + return resolveCompletedUtcDate(asOfMs, asOfSubMs); + } + return resolveCompletedUtcDate(toMs, toSubMs); +} + +/** + * Resolves a fixed pre-study cohort date: the latest completed UTC date strictly + * before the study start (`fromMs`) and no later than effective `asOf`. + */ +export function resolvePreStartUniverseDate( + fromMs: number, + asOfMs: number, + asOfSubMs: number +): string { + const fromDayStartMs = Math.floor(fromMs / MS_PER_DAY) * MS_PER_DAY; + const preStartDate = utcDateOf(fromDayStartMs - MS_PER_DAY); + const asOfCompletedDate = resolveCompletedUtcDate(asOfMs, asOfSubMs); + return asOfCompletedDate < preStartDate ? asOfCompletedDate : preStartDate; +} + +/** Result of fencing MCP query bounds against the server-injected Vault cutoff. */ +export interface VaultFencedBounds extends FencedTimeRange { + readonly vaultCutoffDate: string; + readonly toSubMs: number; + readonly asOfSubMs: number; + readonly effectiveFencedTo: string; + readonly effectiveFencedAsOf: string; +} + +/** + * Runs {@link applyVaultFence} under `scope: 'vault_fenced'` with + * `vaultOperatorAuthorized: false` and computes microsecond-preserving effective + * `to` / `asOf` query strings. + */ +export function fenceVaultQueryBounds( + input: { readonly from: string; readonly to: string; readonly asOf?: string }, + vaultCutoffTs: number +): VaultFencedBounds { + const fenced = applyVaultFence( + { + from: input.from, + to: input.to, + asOf: input.asOf, + scope: 'vault_fenced', + }, + { + vaultCutoffTs, + vaultOperatorAuthorized: false, + } + ); + + const toSubMs = resolveToSubMsMicros(input.to, fenced.clampedTo); + const asOfSubMs = resolveAsOfSubMsMicros(input.asOf, fenced.clampedAsOf); + const effectiveFencedTo = fenced.clampedTo + ? formatUtcIsoWithMicros(fenced.toMs, 999) + : input.to; + const effectiveFencedAsOf = + fenced.clampedAsOf || input.asOf === undefined + ? formatUtcIsoWithMicros(fenced.asOfMs, 999) + : input.asOf; + + return { + ...fenced, + vaultCutoffDate: utcDateOf(vaultCutoffTs), + toSubMs, + asOfSubMs, + effectiveFencedTo, + effectiveFencedAsOf, + }; +} + +const SAFE_VALIDATION_FIELDS: ReadonlySet = new Set([ + 'from', + 'to', + 'asOf', + 'date', + 'ref', + 'listingIds', + 'timeframe', + 'adjustment', + 'scope', + 'limit', +]); + +const SAFE_STORE_METHODS: ReadonlySet = new Set([ + 'bars', + 'crossSection', + 'fundamentalsAsOf', + 'events', + 'shortsAsOf', + 'macroAsOf', + 'fx', + 'universe', +]); + +const ADJ_SNAPSHOT_ERROR_MESSAGES: Readonly> = { + missing_snapshot: + 'Adjusted bars require a verified point-in-time fenced adj_factors snapshot.', + missing_metadata: 'Required adj_factors snapshot metadata is missing.', + invalid_metadata: 'adj_factors snapshot metadata is invalid.', + unsupported_version: 'adj_factors snapshot metadata version is unsupported.', + retrospective_rejected: + 'Retrospective adj_factors snapshots are rejected for point-in-time queries.', + incompatible_fence: + 'adj_factors snapshot fence does not match the query asOf or Vault cutoff.', + path_mismatch: 'adj_factors snapshot metadata does not match the configured artifact.', + unpinned_mutable_path: + 'Adjusted bars require a pinned or immutable adj_factors snapshot artifact.', +}; + +/** + * Maps known `MarketDataStore` / Vault domain errors to fixed, sanitized + * `isError: true` MCP tool results without leaking SQL, file paths, or URIs. + */ +export function formatMappedStoreError(err: unknown): McpToolCallResult | null { + if (err instanceof VaultHoldoutFenceError) { + return { + content: [ + { + type: 'text', + text: 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.', + }, + ], + isError: true, + }; + } + + if (err instanceof VaultScopeNotAuthorizedError) { + return { + content: [ + { + type: 'text', + text: "VaultScopeNotAuthorizedError: Data scope 'vault_evaluation_only' is not permitted through MCP.", + }, + ], + isError: true, + }; + } + + if (err instanceof MarketDataStoreValidationError) { + const text = + err.field !== undefined && SAFE_VALIDATION_FIELDS.has(err.field) + ? `MarketDataStoreValidationError: Invalid query parameter "${err.field}".` + : 'MarketDataStoreValidationError: Query parameters failed store validation.'; + return { + content: [{ type: 'text', text }], + isError: true, + }; + } + + if (err instanceof MarketDataStoreNotImplementedError) { + const text = SAFE_STORE_METHODS.has(err.method) + ? `MarketDataStoreNotImplementedError: Store operation "${err.method}" is not supported for this query.` + : 'MarketDataStoreNotImplementedError: Requested store operation is not supported.'; + return { + content: [{ type: 'text', text }], + isError: true, + }; + } + + if (err instanceof AdjFactorsSnapshotError) { + const detail = Object.prototype.hasOwnProperty.call(ADJ_SNAPSHOT_ERROR_MESSAGES, err.code) + ? ADJ_SNAPSHOT_ERROR_MESSAGES[err.code] + : 'Adjusted bars snapshot verification failed.'; + return { + content: [{ type: 'text', text: `AdjFactorsSnapshotError: ${detail}` }], + isError: true, + }; + } + + return null; +} diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts new file mode 100644 index 00000000..2a5ad720 --- /dev/null +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -0,0 +1,1325 @@ +import { describe, expect, test } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + type MarketDataStore, + MarketDataStoreValidationError, + type Table, + type TableRow, + VaultScopeNotAuthorizedError, +} from '../src/market-data-store'; +import { + type BarsQuery, + MarketDataStoreNotImplementedError, + type ShortsAsOfQuery, + type UniverseQuery, +} from '../src/market-data-store-duckdb'; +import { + ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS, + ANALYZE_SIGNAL_MAX_LISTING_IDS, + ANALYZE_SIGNAL_MAX_SERIES_POINTS, + type AnalyzeSignalResultPayload, + createAnalyzeSignalTool, + createMcpServer, + createQueryDataTool, +} from '../src/mcp/index'; +import { buildForwardReturnPanel, shortsTableToSignalRows } from '../src/signal-panel'; +import { analyzeSignal } from '../src/signal-study'; +import type { TrialLedgerExecutor } from '../src/trial-ledger'; + +const SEED = 20261129; +const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const CAMPAIGN_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; +const HYPOTHESIS_UUID = '12345678-1234-4123-8123-123456789abc'; + +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out: string[] = new Array(count); + const current = new Date(`${startDate}T00:00:00.000Z`); + let written = 0; + while (written < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out[written] = current.toISOString().slice(0, 10); + written += 1; + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +function makeUtcMs(date: string, hourUtc: number): number { + const [y, m, d] = date.split('-').map(Number); + return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0); +} + +interface StoredTrialRow { + readonly trial_id: string; + readonly created_at: Date; + readonly principal_id: string; + readonly campaign_id: string | null; + readonly stage: string; + readonly universe_market: string; + readonly horizon_bucket: string; + readonly hypothesis_id: string | null; + readonly expression_hash: string; + readonly sample_start: string; + readonly sample_end: string; + readonly n_obs: number; + readonly sharpe_unann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly daily_series: readonly number[]; +} + +function createFakeTrialLedger(options?: { + insertError?: Error; + dsrReadError?: Error; +}): { + executor: TrialLedgerExecutor; + rows: StoredTrialRow[]; + insertCalls: number; + selectCalls: number; +} { + const rows: StoredTrialRow[] = []; + let nextTrialId = 1; + const state = { + rows, + insertCalls: 0, + selectCalls: 0, + executor: null as unknown as TrialLedgerExecutor, + }; + + state.executor = { + async query>(text: string, params?: readonly unknown[]) { + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + state.insertCalls += 1; + if (options?.insertError !== undefined) { + throw options.insertError; + } + const p = params ?? []; + const trialId = nextTrialId++; + const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); + const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); + const stored: StoredTrialRow = { + trial_id: String(trialId), + created_at: createdAt, + principal_id: p[0] as string, + campaign_id: (p[1] as string | null) ?? null, + stage: p[2] as string, + universe_market: p[3] as string, + horizon_bucket: p[4] as string, + hypothesis_id: (p[5] as string | null) ?? null, + expression_hash: p[6] as string, + sample_start: p[7] as string, + sample_end: p[8] as string, + n_obs: p[9] as number, + sharpe_unann: p[10] as number, + skewness: p[11] as number, + kurtosis: p[12] as number, + daily_series: dailySeries, + }; + rows.push(stored); + return { + rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], + rowCount: 1, + }; + } + + if (trimmed.startsWith('SELECT')) { + state.selectCalls += 1; + if (options?.dsrReadError !== undefined) { + throw options.dsrReadError; + } + if (text.includes('WHERE trial_id = $1::bigint')) { + const targetId = String(params?.[0]); + const matched = rows.filter(r => r.trial_id === targetId); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const market = params?.[0] as string; + const bucket = params?.[1] as string; + const matched = rows.filter( + r => r.universe_market === market && r.horizon_bucket === bucket + ); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + } + + return { rows: [], rowCount: 0 }; + }, + }; + + return state; +} + +interface CeoShortsFixture { + readonly listingIds: number[]; + readonly allDates: string[]; + readonly vaultCutoffDate: string; + readonly vaultCutoffTs: number; + readonly bars: BarRecord[]; + readonly shortsTable: Table; +} + +const SHORTS_COLUMNS = [ + 'listing_id', + 'report_date', + 'known_at', + 'shares_short', + 'net_change', + 'pct_float', + 'source', +] as const; + +function buildCeoShortsFixture(options?: { + preCutoffSessions?: number; + postCutoffSessions?: number; + listingCount?: number; + poisonPostCutoff?: boolean; +}): CeoShortsFixture { + const rand = createSeededRng(SEED); + const listingCount = options?.listingCount ?? 28; + const preCutoffSessions = options?.preCutoffSessions ?? 140; + const postCutoffSessions = options?.postCutoffSessions ?? 10; + const poisonPostCutoff = options?.poisonPostCutoff ?? false; + + const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions); + const vaultCutoffDate = allDates[preCutoffSessions]!; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + + const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i); + const bars: BarRecord[] = []; + const shortsRows: TableRow[] = []; + + const PUBLICATION_LAG_SESSIONS = 4; + const activeNetChange = new Float64Array(listingCount); + const pendingByPublishIdx = new Map(); + const prices = new Float64Array(listingCount); + for (let l = 0; l < listingCount; l += 1) { + prices[l] = 10 + l * 1.5; + } + + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); // 16:00 ET close + + const released = pendingByPublishIdx.get(t - 1); + if (released !== undefined) { + for (let l = 0; l < listingCount; l += 1) { + const v = released[l]; + if (v !== null && v !== undefined) { + activeNetChange[l] = v / 20_000; + } + } + } + + const publishIdx = t + PUBLICATION_LAG_SESSIONS; + if (t % 10 === 0 && publishIdx < allDates.length) { + const reportKnownAt = makeUtcMs(allDates[publishIdx]!, 22); // 17:00 ET on T+4 + const pending: (number | null)[] = []; + for (let l = 0; l < listingCount; l += 1) { + const isNullCell = t > 0 && (t + l) % 19 === 0; + const netChange = isNullCell ? null : Math.round((rand() * 2 - 1) * 20_000); + pending.push(netChange); + shortsRows.push({ + listing_id: listingIds[l]!, + report_date: date, + known_at: reportKnownAt, + shares_short: 100_000 + l * 5_000 + Math.round(rand() * 10_000), + net_change: netChange, + pct_float: isNullCell ? null : Number((0.02 + rand() * 0.08).toFixed(4)), + source: 'ceoShorts', + }); + } + pendingByPublishIdx.set(publishIdx, pending); + } + + for (let l = 0; l < listingCount; l += 1) { + const dailyRet = -0.004 * activeNetChange[l]! + (rand() * 2 - 1) * 0.008; + prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet)); + const isPostCutoff = date >= vaultCutoffDate; + const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : Number(prices[l]!.toFixed(6)); + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: closeVal, + high: closeVal, + low: closeVal, + close: closeVal, + volume: 50_000, + vwap: closeVal, + knownAt: closeTs, + }); + } + } + + return { + listingIds, + allDates, + vaultCutoffDate, + vaultCutoffTs, + bars, + shortsTable: { + columns: SHORTS_COLUMNS, + rows: shortsRows, + }, + }; +} + +interface FakeStoreState { + readonly barsCalls: BarsQuery[]; + readonly shortsCalls: ShortsAsOfQuery[]; + readonly universeCalls: UniverseQuery[]; + readonly store: MarketDataStore; +} + +function createFakeStore(options?: { + bars?: readonly BarRecord[]; + shortsTable?: Table; + universeIds?: readonly number[]; + universeResolver?: (q: UniverseQuery) => number[]; + leaky?: boolean; + barsError?: Error; + shortsError?: Error; + universeError?: Error; +}): FakeStoreState { + const barsCalls: BarsQuery[] = []; + const shortsCalls: ShortsAsOfQuery[] = []; + const universeCalls: UniverseQuery[] = []; + + const allBars = options?.bars ?? []; + const allShorts = options?.shortsTable ?? { columns: SHORTS_COLUMNS, rows: [] }; + const leaky = options?.leaky ?? false; + + const store: MarketDataStore = { + bars(q: BarsQuery): AsyncIterable { + barsCalls.push(q); + if (options?.barsError !== undefined) { + const err = options.barsError; + return { + [Symbol.asyncIterator]() { + return { + next() { + return Promise.reject(err); + }, + }; + }, + }; + } + + const idSet = new Set(q.listingIds); + const fromMs = Date.parse(q.from.length === 10 ? `${q.from}T00:00:00.000Z` : q.from); + const toMs = Date.parse(q.to.length === 10 ? `${q.to}T23:59:59.999Z` : q.to); + const asOfMs = + q.asOf !== undefined + ? Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf) + : Number.POSITIVE_INFINITY; + + const filtered = leaky + ? [...allBars] + : allBars.filter( + row => + idSet.has(row.listingId) && + row.ts >= fromMs && + row.ts <= toMs && + row.knownAt <= asOfMs + ); + + return { + async *[Symbol.asyncIterator]() { + yield { rows: filtered }; + }, + }; + }, + + async shortsAsOf(q: ShortsAsOfQuery): Promise { + shortsCalls.push(q); + if (options?.shortsError !== undefined) { + throw options.shortsError; + } + + if (leaky) { + return { + columns: allShorts.columns, + rows: [...allShorts.rows], + }; + } + + const idSet = new Set(q.listingIds); + const fromDate = q.from.slice(0, 10); + const toDate = q.to.slice(0, 10); + const asOfMs = + q.asOf !== undefined + ? Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf) + : Number.POSITIVE_INFINITY; + + const rows = allShorts.rows.filter(row => { + const lid = row.listing_id as number; + const reportDate = row.report_date as string | undefined; + const knownAt = row.known_at as number; + const inDateRange = + reportDate === undefined || (reportDate >= fromDate && reportDate <= toDate); + return idSet.has(lid) && inDateRange && knownAt <= asOfMs; + }); + + return { + columns: allShorts.columns, + rows, + }; + }, + + async universe(q: UniverseQuery): Promise { + universeCalls.push(q); + if (options?.universeError !== undefined) { + throw options.universeError; + } + if (options?.universeResolver !== undefined) { + return options.universeResolver(q); + } + return [...(options?.universeIds ?? [])]; + }, + + crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; + + return { barsCalls, shortsCalls, universeCalls, store }; +} + +async function callAnalyzeSignal(params: { + store: MarketDataStore; + ledger: TrialLedgerExecutor; + vaultCutoffTs: number; + principalId?: string; + args: Record; +}): Promise<{ + rawResponse: string; + isError: boolean; + text: string; +}> { + const tool = createAnalyzeSignalTool({ + store: params.store, + ledger: params.ledger, + vaultContext: { vaultCutoffTs: params.vaultCutoffTs }, + principalId: params.principalId ?? AGENT_PRINCIPAL, + }); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [tool], + }); + + const rawResponse = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'as-1', + method: 'tools/call', + params: { + name: 'analyze_signal', + arguments: params.args, + }, + }) + ); + + expect(rawResponse).not.toBeNull(); + const parsed = JSON.parse(rawResponse as string) as { + result: { + isError?: boolean; + content: { type: string; text: string }[]; + }; + }; + return { + rawResponse: rawResponse as string, + isError: parsed.result.isError === true, + text: parsed.result.content[0]?.text ?? '', + }; +} + +describe('MCP analyze_signal tool', () => { + test('tools/list advertises query_data and analyze_signal and omits server-controlled fields from analyze_signal schema', async () => { + const fixture = buildCeoShortsFixture({ preCutoffSessions: 20, postCutoffSessions: 5, listingCount: 6 }); + const fakeStore = createFakeStore({ bars: fixture.bars, shortsTable: fixture.shortsTable }); + const fakeLedger = createFakeTrialLedger(); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: fakeStore.store, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + }), + createAnalyzeSignalTool({ + store: fakeStore.store, + ledger: fakeLedger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + }), + ], + }); + + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'list-1', + method: 'tools/list', + }) + ); + + const parsed = JSON.parse(raw as string) as { + result: { + tools: { + name: string; + description: string; + inputSchema: { + type: string; + properties: Record }>; + required?: string[]; + additionalProperties: boolean; + }; + }[]; + }; + }; + + const names = parsed.result.tools.map(t => t.name); + expect(names).toEqual(['query_data', 'analyze_signal']); + + const analyzeTool = parsed.result.tools.find(t => t.name === 'analyze_signal'); + expect(analyzeTool).toBeDefined(); + expect(analyzeTool?.inputSchema.type).toBe('object'); + expect(analyzeTool?.inputSchema.additionalProperties).toBe(false); + expect(analyzeTool?.inputSchema.properties.signal?.additionalProperties).toBe(false); + + const propKeys = Object.keys(analyzeTool?.inputSchema.properties ?? {}); + expect(propKeys).toContain('listingIds'); + expect(propKeys).toContain('universe'); + expect(propKeys).toContain('from'); + expect(propKeys).toContain('to'); + expect(propKeys).toContain('signal'); + expect(propKeys).toContain('horizonSessions'); + expect(propKeys).toContain('universeMarket'); + expect(propKeys).toContain('horizonBucket'); + + for (const forbidden of ['scope', 'vault_evaluation_only', 'principalId', 'vaultCutoffDate']) { + expect(propKeys).not.toContain(forbidden); + expect(analyzeTool?.inputSchema.required ?? []).not.toContain(forbidden); + } + }); + + test('executes seeded ceoShorts fixture with parity to direct analyzeSignal and writes exactly one trial row under injected principal', async () => { + const fixture = buildCeoShortsFixture(); + const fakeStore = createFakeStore({ + bars: fixture.bars, + shortsTable: fixture.shortsTable, + }); + const mcpLedger = createFakeTrialLedger(); + + const from = fixture.allDates[0]!; + const to = fixture.allDates[fixture.allDates.length - 1]!; + + const res = await callAnalyzeSignal({ + store: fakeStore.store, + ledger: mcpLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + principalId: AGENT_PRINCIPAL, + args: { + listingIds: fixture.listingIds, + from, + to, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + campaignId: CAMPAIGN_UUID, + hypothesisId: HYPOTHESIS_UUID, + }, + }); + + expect(res.isError).toBe(false); + const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; + expect(payload.status).toBe('ok'); + if (payload.status !== 'ok') { + return; + } + + // Run direct research pipeline on the same pre-cutoff bars/shorts with a fresh isolated ledger + const directLedger = createFakeTrialLedger(); + const preCutoffBars = fixture.bars.filter(b => b.ts < fixture.vaultCutoffTs); + const preCutoffShorts: Table = { + columns: fixture.shortsTable.columns, + rows: fixture.shortsTable.rows.filter( + r => (r.report_date as string) < fixture.vaultCutoffDate && (r.known_at as number) < fixture.vaultCutoffTs + ), + }; + const directSignals = shortsTableToSignalRows(preCutoffShorts, 'net_change'); + const directBuilt = buildForwardReturnPanel({ + bars: preCutoffBars, + signals: directSignals, + horizonSessions: 5, + vaultCutoffDate: fixture.vaultCutoffDate, + }); + const directStudy = await analyzeSignal(directLedger.executor, { + principalId: AGENT_PRINCIPAL, + campaignId: CAMPAIGN_UUID, + hypothesisId: HYPOTHESIS_UUID, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'direct_reference', + params: { field: 'net_change', horizonSessions: 5 }, + universe: fixture.listingIds, + horizon: '5d', + }, + panel: directBuilt.panel, + vaultCutoffDate: fixture.vaultCutoffDate, + }); + + expect(directStudy.status).toBe('ok'); + if (directStudy.status !== 'ok') { + return; + } + + // Parity between MCP payload and direct research pipeline + expect(payload.scope).toBe('vault_fenced'); + expect(payload.vaultCutoffTs).toBe(fixture.vaultCutoffTs); + expect(payload.vaultCutoffDate).toBe(fixture.vaultCutoffDate); + expect(payload.panelDiagnostics).toEqual(directBuilt.diagnostics); + expect(payload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); + expect(payload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); + expect(payload.analysis.quantiles.spreadSummary).toEqual( + directStudy.analysis.quantiles.spreadSummary + ); + expect(payload.analysis.turnover.meanTopTurnover).toBe( + directStudy.analysis.turnover.meanTopTurnover + ); + expect(payload.analysis.recency).toEqual(directStudy.analysis.recency); + expect(payload.analysis.diagnostics).toEqual(directStudy.analysis.diagnostics); + expect(payload.trial.sampleStart).toBe(directStudy.trial.sampleStart); + expect(payload.trial.sampleEnd).toBe(directStudy.trial.sampleEnd); + expect(payload.trial.sampleEnd < fixture.vaultCutoffDate).toBe(true); + expect(payload.trial.nObs).toBe(directStudy.trial.nObs); + expect(payload.trial.expressionHash).toMatch(/^[0-9a-f]{64}$/); + expect(payload.deflatedSharpe).toEqual(directStudy.deflatedSharpe); + + // Bounded series preview: >100 observations truncated to latest 100 while study & ledger keep full sample + expect(payload.analysis.ledgerSeries.series).toBe('rank_ic'); + expect(payload.analysis.ledgerSeries.totalCount).toBe(directStudy.trial.nObs); + expect(payload.analysis.ledgerSeries.totalCount).toBeGreaterThan(ANALYZE_SIGNAL_MAX_SERIES_POINTS); + expect(payload.analysis.ledgerSeries.truncated).toBe(true); + expect(payload.analysis.ledgerSeries.points).toHaveLength(ANALYZE_SIGNAL_MAX_SERIES_POINTS); + const lastPoint = payload.analysis.ledgerSeries.points[ANALYZE_SIGNAL_MAX_SERIES_POINTS - 1]; + expect(lastPoint?.date).toBe(directStudy.trial.sampleEnd); + + // Exactly one trial_ledger row written with injected principalId and full daily_series + expect(mcpLedger.rows).toHaveLength(1); + const stored = mcpLedger.rows[0]!; + expect(stored.stage).toBe('signal_ic'); + expect(stored.principal_id).toBe(AGENT_PRINCIPAL); + expect(stored.campaign_id).toBe(CAMPAIGN_UUID); + expect(stored.hypothesis_id).toBe(HYPOTHESIS_UUID); + expect(stored.universe_market).toBe('CA_EQ'); + expect(stored.horizon_bucket).toBe('swing_1_10d'); + expect(stored.n_obs).toBe(directStudy.trial.nObs); + expect(stored.daily_series).toHaveLength(directStudy.trial.nObs); + }); + + test('identical requests and reordered/duplicate listingIds produce the same expressionHash; changing field, horizon, or ledgerSeries changes it', async () => { + const fixture = buildCeoShortsFixture(); + const from = fixture.allDates[0]!; + const to = fixture.allDates[fixture.allDates.length - 1]!; + + async function runWithArgs(args: Record) { + const store = createFakeStore({ bars: fixture.bars, shortsTable: fixture.shortsTable }); + const ledger = createFakeTrialLedger(); + const res = await callAnalyzeSignal({ + store: store.store, + ledger: ledger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args, + }); + expect(res.isError).toBe(false); + const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; + expect(payload.status).toBe('ok'); + if (payload.status !== 'ok') { + throw new Error('Expected ok status'); + } + return { payload, ledger }; + } + + const baseArgs = { + listingIds: fixture.listingIds, + from, + to, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }; + + const run1 = await runWithArgs(baseArgs); + const run2 = await runWithArgs(baseArgs); + expect(run1.payload.trial.expressionHash).toBe(run2.payload.trial.expressionHash); + + // Reordered and duplicated listingIds canonicalize to the exact same expressionHash + const reorderedIds = [...fixture.listingIds].reverse(); + reorderedIds.push(fixture.listingIds[0]!, fixture.listingIds[3]!); + const runReordered = await runWithArgs({ ...baseArgs, listingIds: reorderedIds }); + expect(runReordered.payload.trial.expressionHash).toBe(run1.payload.trial.expressionHash); + + // Different signal.field -> different expressionHash + const runOtherField = await runWithArgs({ + ...baseArgs, + signal: { source: 'shorts', field: 'pct_float' }, + }); + expect(runOtherField.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); + + // Different horizonSessions -> different expressionHash + const runOtherHorizon = await runWithArgs({ ...baseArgs, horizonSessions: 10 }); + expect(runOtherHorizon.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); + + // quantile_spread ledgerSeries works, truncates preview to 100 while preserving full count, and hashes distinctly + const runSpread = await runWithArgs({ ...baseArgs, ledgerSeries: 'quantile_spread' }); + expect(runSpread.payload.analysis.ledgerSeries.series).toBe('quantile_spread'); + expect(runSpread.payload.analysis.ledgerSeries.totalCount).toBe(runSpread.payload.trial.nObs); + expect(runSpread.payload.analysis.ledgerSeries.truncated).toBe(true); + expect(runSpread.payload.analysis.ledgerSeries.points).toHaveLength( + ANALYZE_SIGNAL_MAX_SERIES_POINTS + ); + expect(runSpread.ledger.rows[0]?.daily_series).toHaveLength(runSpread.payload.trial.nObs); + expect(runSpread.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); + }); + + test('clamps to/asOf strictly below cutoff and blocks post-cutoff and post-asOf leakage from a leaky store, including intraday cutoff', async () => { + const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false }); + const poisonedFixture = buildCeoShortsFixture({ poisonPostCutoff: true }); + const from = cleanFixture.allDates[0]!; + const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!; + + // Add a mid-window explicit asOf and verify rows known after asOf are excluded even from a leaky store + const explicitAsOfDate = cleanFixture.allDates[100]!; + const explicitAsOfMs = makeUtcMs(explicitAsOfDate, 23) + 59 * 60_000 + 59_999; + + const cleanStore = createFakeStore({ + bars: cleanFixture.bars, + shortsTable: cleanFixture.shortsTable, + leaky: false, + }); + const leakyStore = createFakeStore({ + bars: [ + ...poisonedFixture.bars, + // Extra bar on exact vaultCutoffDate before an intraday cutoff + { + listingId: poisonedFixture.listingIds[0]!, + ts: makeUtcMs(poisonedFixture.vaultCutoffDate, 10), + open: 888_888, + high: 888_888, + low: 888_888, + close: 888_888, + volume: 100, + vwap: 888_888, + knownAt: makeUtcMs(poisonedFixture.vaultCutoffDate, 10), + }, + ], + shortsTable: { + columns: poisonedFixture.shortsTable.columns, + rows: [ + ...poisonedFixture.shortsTable.rows, + // Shorts row with report_date on vaultCutoffDate and known_at before intraday cutoff + { + listing_id: poisonedFixture.listingIds[0]!, + report_date: poisonedFixture.vaultCutoffDate, + known_at: makeUtcMs(poisonedFixture.vaultCutoffDate, 9), + shares_short: 9_999_999, + net_change: 9_999_999, + pct_float: 0.99, + source: 'ceoShorts', + }, + // Shorts row with known_at after explicitAsOf + { + listing_id: poisonedFixture.listingIds[1]!, + report_date: cleanFixture.allDates[50]!, + known_at: explicitAsOfMs + 60_000, + shares_short: 7_777_777, + net_change: 7_777_777, + pct_float: 0.77, + source: 'ceoShorts', + }, + ], + }, + leaky: true, + }); + + // 1. Clamping test with to and asOf after Vault cutoff (midnight cutoff) + const clampLedger = createFakeTrialLedger(); + const clampStore = createFakeStore({ + bars: cleanFixture.bars, + shortsTable: cleanFixture.shortsTable, + }); + const clampRes = await callAnalyzeSignal({ + store: clampStore.store, + ledger: clampLedger.executor, + vaultCutoffTs: cleanFixture.vaultCutoffTs, + args: { + listingIds: cleanFixture.listingIds, + from, + to: postCutoffDate, + asOf: postCutoffDate, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + + expect(clampRes.isError).toBe(false); + const clampPayload = JSON.parse(clampRes.text) as AnalyzeSignalResultPayload; + expect(clampPayload.status).toBe('ok'); + expect(clampPayload.clampedTo).toBe(true); + expect(clampPayload.clampedAsOf).toBe(true); + expect(clampPayload.toMs).toBe(cleanFixture.vaultCutoffTs - 1); + expect(clampPayload.asOfMs).toBe(cleanFixture.vaultCutoffTs - 1); + + // Store received fenced to and asOf strictly below vaultCutoffTs + expect(clampStore.barsCalls).toHaveLength(1); + expect(clampStore.barsCalls[0]?.scope).toBe('vault_fenced'); + expect(Date.parse(clampStore.barsCalls[0]?.to ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); + expect(Date.parse(clampStore.barsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); + expect(clampStore.shortsCalls).toHaveLength(1); + expect(Date.parse(clampStore.shortsCalls[0]?.to ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); + expect(Date.parse(clampStore.shortsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); + if (clampPayload.status === 'ok') { + expect(clampPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true); + } + + // 2. Leaky store with intraday cutoff (12:00 UTC on vaultCutoffDate) and earlier explicit asOf matches clean store + const intradayCutoffTs = makeUtcMs(cleanFixture.vaultCutoffDate, 12); + const cleanLedger = createFakeTrialLedger(); + const leakyLedger = createFakeTrialLedger(); + + const cleanRes = await callAnalyzeSignal({ + store: cleanStore.store, + ledger: cleanLedger.executor, + vaultCutoffTs: intradayCutoffTs, + args: { + listingIds: cleanFixture.listingIds, + from, + to: postCutoffDate, + asOf: explicitAsOfDate, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + const leakyRes = await callAnalyzeSignal({ + store: leakyStore.store, + ledger: leakyLedger.executor, + vaultCutoffTs: intradayCutoffTs, + args: { + listingIds: cleanFixture.listingIds, + from, + to: postCutoffDate, + asOf: explicitAsOfDate, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + + expect(cleanRes.isError).toBe(false); + expect(leakyRes.isError).toBe(false); + expect(leakyRes.text).toBe(cleanRes.text); + expect(leakyLedger.rows).toEqual(cleanLedger.rows); + }); + + test('request wholly inside Vault holdout returns fixed VaultHoldoutFenceError with zero store and ledger calls', async () => { + const fixture = buildCeoShortsFixture(); + const fakeStore = createFakeStore({ + bars: fixture.bars, + shortsTable: fixture.shortsTable, + }); + const fakeLedger = createFakeTrialLedger(); + + const res = await callAnalyzeSignal({ + store: fakeStore.store, + ledger: fakeLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + listingIds: fixture.listingIds, + from: fixture.vaultCutoffDate, + to: fixture.allDates[fixture.allDates.length - 1]!, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + + expect(res.isError).toBe(true); + expect(res.text).toBe( + 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.' + ); + expect(fakeStore.barsCalls).toHaveLength(0); + expect(fakeStore.shortsCalls).toHaveLength(0); + expect(fakeStore.universeCalls).toHaveLength(0); + expect(fakeLedger.insertCalls).toBe(0); + expect(fakeLedger.rows).toHaveLength(0); + }); + + test('named universe resolves strictly before study start and respects earlier/intraday asOf', async () => { + const fixture = buildCeoShortsFixture(); + const from = fixture.allDates[0]!; // 2022-09-01 + const to = fixture.allDates[fixture.allDates.length - 1]!; + + const fakeStore = createFakeStore({ + bars: fixture.bars, + shortsTable: fixture.shortsTable, + universeIds: [...fixture.listingIds].reverse(), + }); + const fakeLedger = createFakeTrialLedger(); + + const res = await callAnalyzeSignal({ + store: fakeStore.store, + ledger: fakeLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + universe: 'CA_EQ', + from, + to, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + + expect(res.isError).toBe(false); + // Study starts 2022-09-01 -> universe must be resolved on 2022-08-31 (strictly before study start) + expect(fakeStore.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-31' }]); + // Sorted listingIds passed to bars and shortsAsOf + expect(fakeStore.barsCalls[0]?.listingIds).toEqual(fixture.listingIds); + expect(fakeStore.shortsCalls[0]?.listingIds).toEqual(fixture.listingIds); + + // Earlier intraday asOf (2022-08-15T12:00:00Z) -> universe resolved on completed UTC date 2022-08-14 + const earlyStore = createFakeStore({ + bars: fixture.bars, + shortsTable: fixture.shortsTable, + universeIds: fixture.listingIds, + }); + const earlyLedger = createFakeTrialLedger(); + await callAnalyzeSignal({ + store: earlyStore.store, + ledger: earlyLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: { + universe: 'CA_EQ', + from, + to, + asOf: '2022-08-15T12:00:00Z', + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(earlyStore.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-14' }]); + }); + + test('insufficient-data cases (empty universe, empty panel, undersized panel, zero-variance series) return reason with zero ledger writes', async () => { + const cutoffDate = '2025-03-31'; + const cutoffTs = makeUtcMs(cutoffDate, 0); + + // 1. Empty resolved universe -> zero bars/shorts calls, zero ledger rows + const emptyUniStore = createFakeStore({ universeIds: [] }); + const emptyUniLedger = createFakeTrialLedger(); + const emptyUniRes = await callAnalyzeSignal({ + store: emptyUniStore.store, + ledger: emptyUniLedger.executor, + vaultCutoffTs: cutoffTs, + args: { + universe: 'CA_EQ', + from: '2025-01-01', + to: '2025-03-20', + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 1, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(emptyUniRes.isError).toBe(false); + const emptyUniPayload = JSON.parse(emptyUniRes.text) as AnalyzeSignalResultPayload; + expect(emptyUniPayload.status).toBe('insufficient_data'); + if (emptyUniPayload.status === 'insufficient_data') { + expect(emptyUniPayload.reason).toBe('too_few_observations'); + } + expect(emptyUniStore.barsCalls).toHaveLength(0); + expect(emptyUniStore.shortsCalls).toHaveLength(0); + expect(emptyUniLedger.rows).toHaveLength(0); + + // 2. Empty panel (bars exist but no shorts signals) + const dates = makeBusinessDates('2025-01-02', 6); + const barsForSixDays: BarRecord[] = []; + for (let d = 0; d < dates.length; d += 1) { + const ts = makeUtcMs(dates[d]!, 21); + for (let id = 1; id <= 6; id += 1) { + barsForSixDays.push({ + listingId: id, + ts, + open: 100 + d, + high: 101 + d, + low: 99 + d, + close: 100 + d + id * 0.1, + volume: 1000, + vwap: 100 + d, + knownAt: ts, + }); + } + } + const emptyPanelStore = createFakeStore({ + bars: barsForSixDays, + shortsTable: { columns: SHORTS_COLUMNS, rows: [] }, + }); + const emptyPanelLedger = createFakeTrialLedger(); + const emptyPanelRes = await callAnalyzeSignal({ + store: emptyPanelStore.store, + ledger: emptyPanelLedger.executor, + vaultCutoffTs: cutoffTs, + args: { + listingIds: [1, 2, 3, 4, 5, 6], + from: dates[0]!, + to: dates[dates.length - 1]!, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(emptyPanelRes.isError).toBe(false); + const emptyPanelPayload = JSON.parse(emptyPanelRes.text) as AnalyzeSignalResultPayload; + expect(emptyPanelPayload.status).toBe('insufficient_data'); + if (emptyPanelPayload.status === 'insufficient_data') { + expect(emptyPanelPayload.reason).toBe('too_few_observations'); + } + expect(emptyPanelLedger.rows).toHaveLength(0); + + // 3. Undersized non-empty panel (only 1 date with forward return -> too_few_observations) + const twoDayBars = barsForSixDays.filter(b => b.ts <= makeUtcMs(dates[1]!, 21)); + const singleSignalRows: TableRow[] = [1, 2, 3, 4, 5, 6].map(id => ({ + listing_id: id, + report_date: dates[0]!, + known_at: makeUtcMs(dates[0]!, 10), + shares_short: 1000 * id, + net_change: 100 * id, + pct_float: 0.01 * id, + source: 'ceoShorts', + })); + const undersizedStore = createFakeStore({ + bars: twoDayBars, + shortsTable: { columns: SHORTS_COLUMNS, rows: singleSignalRows }, + }); + const undersizedLedger = createFakeTrialLedger(); + const undersizedRes = await callAnalyzeSignal({ + store: undersizedStore.store, + ledger: undersizedLedger.executor, + vaultCutoffTs: cutoffTs, + args: { + listingIds: [1, 2, 3, 4, 5, 6], + from: dates[0]!, + to: dates[1]!, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(undersizedRes.isError).toBe(false); + const undersizedPayload = JSON.parse(undersizedRes.text) as AnalyzeSignalResultPayload; + expect(undersizedPayload.status).toBe('insufficient_data'); + if (undersizedPayload.status === 'insufficient_data') { + expect(undersizedPayload.reason).toBe('too_few_observations'); + } + expect(undersizedLedger.rows).toHaveLength(0); + + // 4. Zero-variance rank_ic series (identical strictly monotone rank ordering every day -> rank_ic = 1.0 on every date) + const monotoneBars: BarRecord[] = []; + for (let d = 0; d < dates.length; d += 1) { + const ts = makeUtcMs(dates[d]!, 21); + for (let id = 1; id <= 6; id += 1) { + const close = 100 * Math.pow(1 + 0.01 * id, d); + monotoneBars.push({ + listingId: id, + ts, + open: close, + high: close, + low: close, + close, + volume: 1000, + vwap: close, + knownAt: ts, + }); + } + } + const zeroVarStore = createFakeStore({ + bars: monotoneBars, + shortsTable: { columns: SHORTS_COLUMNS, rows: singleSignalRows }, + }); + const zeroVarLedger = createFakeTrialLedger(); + const zeroVarRes = await callAnalyzeSignal({ + store: zeroVarStore.store, + ledger: zeroVarLedger.executor, + vaultCutoffTs: cutoffTs, + args: { + listingIds: [1, 2, 3, 4, 5, 6], + from: dates[0]!, + to: dates[dates.length - 1]!, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }); + expect(zeroVarRes.isError).toBe(false); + const zeroVarPayload = JSON.parse(zeroVarRes.text) as AnalyzeSignalResultPayload; + expect(zeroVarPayload.status).toBe('insufficient_data'); + if (zeroVarPayload.status === 'insufficient_data') { + expect(zeroVarPayload.reason).toBe('zero_variance_series'); + } + expect(zeroVarLedger.rows).toHaveLength(0); + }); + + test('strict schema rejects forbidden keys, unknown keys, bad selectors, invalid dates/UUIDs, INT32/limit/horizon violations with zero store or ledger calls', async () => { + const cutoffTs = makeUtcMs('2025-03-31', 0); + const validBase = { + listingIds: [101, 102], + from: '2025-01-02', + to: '2025-03-20', + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }; + + const invalidCases: readonly [string, Record][] = [ + ['scope vault_evaluation_only', { ...validBase, scope: 'vault_evaluation_only' }], + ['scope vault_fenced', { ...validBase, scope: 'vault_fenced' }], + ['vault_evaluation_only flag', { ...validBase, vault_evaluation_only: true }], + ['principalId override', { ...validBase, principalId: 'operator' }], + ['vaultCutoffDate override', { ...validBase, vaultCutoffDate: '2026-01-01' }], + ['unknown top-level key', { ...validBase, extraFlag: true }], + [ + 'unknown nested signal key', + { ...validBase, signal: { source: 'shorts', field: 'net_change', extra: 1 } }, + ], + ['both listingIds and universe', { ...validBase, universe: 'CA_EQ' }], + [ + 'neither listingIds nor universe', + { + from: validBase.from, + to: validBase.to, + signal: validBase.signal, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }, + ], + ['unknown signal.source', { ...validBase, signal: { source: 'fundamentals', field: 'net_change' } }], + ['unknown signal.field', { ...validBase, signal: { source: 'shorts', field: 'unknown_col' } }], + ['invalid calendar date from', { ...validBase, from: '2025-02-30' }], + ['invalid string date to', { ...validBase, to: 'not-a-date' }], + ['naive timestamp without offset in asOf', { ...validBase, asOf: '2025-02-01T12:00:00' }], + ['invalid campaignId UUID', { ...validBase, campaignId: 'not-a-uuid' }], + ['invalid hypothesisId UUID', { ...validBase, hypothesisId: '12345' }], + ['INT32 overflow listingId', { ...validBase, listingIds: [2_147_483_648] }], + ['INT32 underflow listingId', { ...validBase, listingIds: [-2_147_483_649] }], + ['non-integer listingId', { ...validBase, listingIds: [101.5] }], + ['empty listingIds', { ...validBase, listingIds: [] }], + [ + 'more than 500 explicit listingIds', + { + ...validBase, + listingIds: Array.from({ length: ANALYZE_SIGNAL_MAX_LISTING_IDS + 1 }, (_, i) => i + 1), + }, + ], + ['horizonSessions 0', { ...validBase, horizonSessions: 0 }], + ['horizonSessions negative', { ...validBase, horizonSessions: -3 }], + [ + 'horizonSessions above max', + { ...validBase, horizonSessions: ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS + 1 }, + ], + ['horizonSessions float', { ...validBase, horizonSessions: 2.5 }], + ['negative maxSignalAgeSessions', { ...validBase, maxSignalAgeSessions: -1 }], + ]; + + for (const [_label, args] of invalidCases) { + const fakeStore = createFakeStore(); + const fakeLedger = createFakeTrialLedger(); + const res = await callAnalyzeSignal({ + store: fakeStore.store, + ledger: fakeLedger.executor, + vaultCutoffTs: cutoffTs, + args, + }); + + expect(res.isError).toBe(true); + expect(res.text).toContain('Invalid arguments for tool "analyze_signal":'); + expect(fakeStore.barsCalls).toHaveLength(0); + expect(fakeStore.shortsCalls).toHaveLength(0); + expect(fakeStore.universeCalls).toHaveLength(0); + expect(fakeLedger.insertCalls).toBe(0); + } + + // Raw JSON own __proto__ key rejected with zero store or ledger calls + const protoStore = createFakeStore(); + const protoLedger = createFakeTrialLedger(); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createAnalyzeSignalTool({ + store: protoStore.store, + ledger: protoLedger.executor, + vaultContext: { vaultCutoffTs: cutoffTs }, + principalId: AGENT_PRINCIPAL, + }), + ], + }); + const rawProto = + '{"jsonrpc":"2.0","id":"proto-1","method":"tools/call","params":{"name":"analyze_signal","arguments":{"listingIds":[101],"from":"2025-01-02","to":"2025-03-20","signal":{"source":"shorts","field":"net_change"},"horizonSessions":5,"universeMarket":"CA_EQ","horizonBucket":"swing_1_10d","__proto__":{"principalId":"operator"}}}}'; + const protoResp = JSON.parse((await server.handleMessage(rawProto)) as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(protoResp.result.isError).toBe(true); + expect(protoStore.barsCalls).toHaveLength(0); + expect(protoLedger.insertCalls).toBe(0); + }); + + test('sanitizes store, panel, ledger insert, and DSR read failures without leaking SQL, paths, or connection URIs', async () => { + const fixture = buildCeoShortsFixture(); + const from = fixture.allDates[0]!; + const to = fixture.allDates[fixture.allDates.length - 1]!; + const validArgs = { + listingIds: fixture.listingIds, + from, + to, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }; + + const sensitiveDetail = + 'SELECT * FROM trial_ledger WHERE secret=1 at /mnt/data/stockbot/curated/shorts/part.parquet via postgres://user:pass@host:5432/trading_bot'; + + function assertNoLeak(rawResponse: string): void { + expect(rawResponse).not.toContain('SELECT * FROM trial_ledger'); + expect(rawResponse).not.toContain('/mnt/data/stockbot'); + expect(rawResponse).not.toContain('part.parquet'); + expect(rawResponse).not.toContain('postgres://user:pass@host'); + } + + // 1. Store domain & unexpected errors + const storeErrors: readonly [Error, string][] = [ + [new VaultScopeNotAuthorizedError(sensitiveDetail), 'VaultScopeNotAuthorizedError'], + [new MarketDataStoreValidationError(sensitiveDetail, 'curatedRoot'), 'MarketDataStoreValidationError'], + [new MarketDataStoreNotImplementedError('shortsAsOf', sensitiveDetail), 'MarketDataStoreNotImplementedError'], + [new Error(sensitiveDetail), 'Error: Tool execution failed.'], + ]; + for (const [err, expectedSnippet] of storeErrors) { + const store = createFakeStore({ shortsError: err, bars: fixture.bars }); + const ledger = createFakeTrialLedger(); + const res = await callAnalyzeSignal({ + store: store.store, + ledger: ledger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: validArgs, + }); + expect(res.isError).toBe(true); + expect(res.text).toContain(expectedSnippet); + assertNoLeak(res.rawResponse); + expect(ledger.rows).toHaveLength(0); + } + + // 2. Malformed shorts table -> SignalPanelError mapped cleanly + const badTableStore = createFakeStore({ + bars: fixture.bars, + shortsTable: { columns: ['listing_id'], rows: [] }, + }); + const badTableLedger = createFakeTrialLedger(); + const badTableRes = await callAnalyzeSignal({ + store: badTableStore.store, + ledger: badTableLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: validArgs, + }); + expect(badTableRes.isError).toBe(true); + expect(badTableRes.text).toContain('SignalPanelError:'); + expect(badTableLedger.rows).toHaveLength(0); + + // 3. Ledger INSERT failure -> isError: true, no leak, zero trial rows written + const insertFailStore = createFakeStore({ + bars: fixture.bars, + shortsTable: fixture.shortsTable, + }); + const insertFailLedger = createFakeTrialLedger({ + insertError: new Error(sensitiveDetail), + }); + const insertFailRes = await callAnalyzeSignal({ + store: insertFailStore.store, + ledger: insertFailLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: validArgs, + }); + expect(insertFailRes.isError).toBe(true); + expect(insertFailRes.text).toBe('Error: Tool execution failed.'); + assertNoLeak(insertFailRes.rawResponse); + expect(insertFailLedger.insertCalls).toBe(1); + expect(insertFailLedger.rows).toHaveLength(0); + + // 4. DSR read failure after INSERT -> isError: true, fixed SignalStudyError, no leak, exactly 1 insert (never retried) + const dsrFailStore = createFakeStore({ + bars: fixture.bars, + shortsTable: fixture.shortsTable, + }); + const dsrFailLedger = createFakeTrialLedger({ + dsrReadError: new Error(sensitiveDetail), + }); + const dsrFailRes = await callAnalyzeSignal({ + store: dsrFailStore.store, + ledger: dsrFailLedger.executor, + vaultCutoffTs: fixture.vaultCutoffTs, + args: validArgs, + }); + expect(dsrFailRes.isError).toBe(true); + expect(dsrFailRes.text).toBe( + 'SignalStudyError: Trial was recorded, but cluster deflated Sharpe evaluation failed.' + ); + assertNoLeak(dsrFailRes.rawResponse); + expect(dsrFailLedger.insertCalls).toBe(1); + expect(dsrFailLedger.rows).toHaveLength(1); + }); +}); From ff9a180f12ece85db16e42590cf16f1f0c3c5310 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 00:14:59 -0500 Subject: [PATCH 13/21] =?UTF-8?q?T-131:=20M2.1b=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`analyze=5Fsignal`=20tool:=20vault-fenced=20short-interest?= =?UTF-8?q?=20signal=20study=20(bars=20+=20`shortsAsOf`=20=E2=86=92=20forw?= =?UTF-8?q?ard-return=20panel=20=E2=86=92=20`analyzeSignal`=20+=20trial=20?= =?UTF-8?q?ledger)=20in=20`libs/research/src/mcp/tools/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/src/mcp/tools/analyze-signal.ts | 81 +++- .../src/mcp/tools/vault-fenced-input.ts | 19 + libs/research/test/mcp-analyze-signal.test.ts | 432 ++++++++++++++---- 3 files changed, 434 insertions(+), 98 deletions(-) diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts index b33c6df0..090e9e32 100644 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ b/libs/research/src/mcp/tools/analyze-signal.ts @@ -14,6 +14,7 @@ import { type TableRow, type VaultFenceContext, } from '../../market-data-store'; +import { UNIVERSE_REFS } from '../../market-data-store-duckdb'; import { SHORTS_SIGNAL_FIELDS, type ShortsSignalField, @@ -73,6 +74,11 @@ const AGENT_PRINCIPAL_RE = /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; const UTC_BOUND_ERROR_MESSAGE = 'Expected YYYY-MM-DD calendar date or UTC ISO-8601 timestamp with timezone offset.'; +const SUPPORTED_UNIVERSE_REF_SET: ReadonlySet = new Set(UNIVERSE_REFS); + +function canonicalDailyHorizonBucket(horizonSessions: number): HorizonBucket { + return horizonSessions <= 10 ? 'swing_1_10d' : 'position_10d_plus'; +} const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE); @@ -154,7 +160,40 @@ export const analyzeSignalInputSchema = z .describe('Bar price adjustment mode (default raw).'), }) .strict() - .refine(hasExclusiveListingSelector, EXCLUSIVE_LISTING_SELECTOR_MESSAGE); + .superRefine((data, ctx) => { + if (!hasExclusiveListingSelector(data)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: EXCLUSIVE_LISTING_SELECTOR_MESSAGE, + }); + } + + const expectedBucket = canonicalDailyHorizonBucket(data.horizonSessions); + if (data.horizonBucket !== expectedBucket) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['horizonBucket'], + message: `Daily horizonSessions=${data.horizonSessions} requires horizonBucket "${expectedBucket}".`, + }); + } + + if (data.universe !== undefined && SUPPORTED_UNIVERSE_REF_SET.has(data.universe)) { + if (data.universeMarket !== data.universe) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['universeMarket'], + message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`, + }); + } + } else if (data.signal.source === 'shorts' && data.universeMarket === 'FX') { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['universeMarket'], + message: + 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', + }); + } + }); export type AnalyzeSignalInput = z.infer; @@ -222,6 +261,9 @@ interface AnalyzeSignalResultBase { readonly fromMs: number; readonly toMs: number; readonly asOfMs: number; + readonly effectiveFrom: string; + readonly effectiveTo: string; + readonly effectiveAsOf: string; readonly clampedTo: boolean; readonly clampedAsOf: boolean; readonly listingCount: number; @@ -351,6 +393,7 @@ function filterEligibleBars( if ( row.ts < fromMs || row.ts > toMs || + row.ts > asOfMs || row.ts >= vaultCutoffTs || utcDateOf(row.ts) >= vaultCutoffDate ) { @@ -424,11 +467,12 @@ function buildCanonicalStudyExpression(params: { readonly input: AnalyzeSignalInput; readonly listingIds: readonly number[]; readonly universeSnapshotDate: string | null; - readonly fromMs: number; - readonly toMs: number; - readonly asOfMs: number; + readonly effectiveFrom: string; + readonly effectiveTo: string; + readonly effectiveAsOf: string; }): SignalStudyExpression { - const { input, listingIds, universeSnapshotDate, fromMs, toMs, asOfMs } = params; + const { input, listingIds, universeSnapshotDate, effectiveFrom, effectiveTo, effectiveAsOf } = + params; return { expression: `mcp:analyze_signal:v1:${input.signal.source}:${input.signal.field}`, params: { @@ -439,9 +483,9 @@ function buildCanonicalStudyExpression(params: { maxSignalAgeSessions: input.maxSignalAgeSessions ?? null, adjustment: input.adjustment, ledgerSeries: input.ledgerSeries, - fromMs, - toMs, - asOfMs, + effectiveFrom, + effectiveTo, + effectiveAsOf, }, universe: input.universe !== undefined @@ -604,6 +648,9 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT fromMs: fenced.fromMs, toMs: fenced.toMs, asOfMs: fenced.asOfMs, + effectiveFrom: fenced.canonicalFrom, + effectiveTo: fenced.canonicalTo, + effectiveAsOf: fenced.canonicalAsOf, clampedTo: fenced.clampedTo, clampedAsOf: fenced.clampedAsOf, listingCount: listingIds.length, @@ -629,19 +676,19 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT store.bars({ listingIds, timeframe: '1d', - from: input.from, - to: fenced.effectiveFencedTo, + from: fenced.canonicalFrom, + to: fenced.canonicalTo, adjustment: input.adjustment, - asOf: fenced.effectiveFencedAsOf, + asOf: fenced.canonicalAsOf, scope: 'vault_fenced', }) ); const rawShortsTable = await store.shortsAsOf({ listingIds, - from: input.from, - to: fenced.effectiveFencedTo, - asOf: fenced.effectiveFencedAsOf, + from: fenced.canonicalFrom, + to: fenced.canonicalTo, + asOf: fenced.canonicalAsOf, }); const listingIdSet = new Set(listingIds); @@ -696,9 +743,9 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT input, listingIds, universeSnapshotDate, - fromMs: fenced.fromMs, - toMs: fenced.toMs, - asOfMs: fenced.asOfMs, + effectiveFrom: fenced.canonicalFrom, + effectiveTo: fenced.canonicalTo, + effectiveAsOf: fenced.canonicalAsOf, }); const studyResult = await analyzeSignal(ledger, { diff --git a/libs/research/src/mcp/tools/vault-fenced-input.ts b/libs/research/src/mcp/tools/vault-fenced-input.ts index cf74cf67..3eaa97c7 100644 --- a/libs/research/src/mcp/tools/vault-fenced-input.ts +++ b/libs/research/src/mcp/tools/vault-fenced-input.ts @@ -100,6 +100,13 @@ export function extractExplicitSubMsMicros(raw: string): number { return Number(microDigits); } +export function resolveFromSubMsMicros(rawFrom: string): number { + if (DATE_ONLY_RE.test(rawFrom)) { + return 0; + } + return extractExplicitSubMsMicros(rawFrom); +} + export function resolveToSubMsMicros(rawTo: string, clampedTo: boolean): number { if (clampedTo || DATE_ONLY_RE.test(rawTo)) { return 999; @@ -171,8 +178,12 @@ export function resolvePreStartUniverseDate( /** Result of fencing MCP query bounds against the server-injected Vault cutoff. */ export interface VaultFencedBounds extends FencedTimeRange { readonly vaultCutoffDate: string; + readonly fromSubMs: number; readonly toSubMs: number; readonly asOfSubMs: number; + readonly canonicalFrom: string; + readonly canonicalTo: string; + readonly canonicalAsOf: string; readonly effectiveFencedTo: string; readonly effectiveFencedAsOf: string; } @@ -199,8 +210,12 @@ export function fenceVaultQueryBounds( } ); + const fromSubMs = resolveFromSubMsMicros(input.from); const toSubMs = resolveToSubMsMicros(input.to, fenced.clampedTo); const asOfSubMs = resolveAsOfSubMsMicros(input.asOf, fenced.clampedAsOf); + const canonicalFrom = formatUtcIsoWithMicros(fenced.fromMs, fromSubMs); + const canonicalTo = formatUtcIsoWithMicros(fenced.toMs, toSubMs); + const canonicalAsOf = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); const effectiveFencedTo = fenced.clampedTo ? formatUtcIsoWithMicros(fenced.toMs, 999) : input.to; @@ -212,8 +227,12 @@ export function fenceVaultQueryBounds( return { ...fenced, vaultCutoffDate: utcDateOf(vaultCutoffTs), + fromSubMs, toSubMs, asOfSubMs, + canonicalFrom, + canonicalTo, + canonicalAsOf, effectiveFencedTo, effectiveFencedAsOf, }; diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts index 2a5ad720..e7840a38 100644 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ b/libs/research/test/mcp-analyze-signal.test.ts @@ -333,6 +333,7 @@ function createFakeStore(options?: { idSet.has(row.listingId) && row.ts >= fromMs && row.ts <= toMs && + row.ts <= asOfMs && row.knownAt <= asOfMs ); @@ -697,9 +698,83 @@ describe('MCP analyze_signal tool', () => { }); expect(runOtherField.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); - // Different horizonSessions -> different expressionHash - const runOtherHorizon = await runWithArgs({ ...baseArgs, horizonSessions: 10 }); + // Different horizonSessions -> different expressionHash (including position_10d_plus bucket for 11d) + const runOtherHorizon = await runWithArgs({ + ...baseArgs, + horizonSessions: 11, + horizonBucket: 'position_10d_plus', + }); expect(runOtherHorizon.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); + expect(runOtherHorizon.ledger.rows[0]?.horizon_bucket).toBe('position_10d_plus'); + + // Equivalent date/timestamp/offset forms canonicalize to identical effective microsecond bounds & expressionHash + const midDate = fixture.allDates[120]!; + const runDateForm = await runWithArgs({ + ...baseArgs, + from, + to: midDate, + asOf: midDate, + }); + const runIsoMicrosForm = await runWithArgs({ + ...baseArgs, + from: `${from}T00:00:00.000000Z`, + to: `${midDate}T23:59:59.999999Z`, + asOf: `${midDate}T23:59:59.999999Z`, + }); + const runOffsetForm = await runWithArgs({ + ...baseArgs, + from: '2022-08-31T19:00:00.000000-05:00', + to: `${midDate}T18:59:59.999999-05:00`, + asOf: `${midDate}T18:59:59.999999-05:00`, + }); + expect(runDateForm.payload.effectiveFrom).toBe(`${from}T00:00:00.000Z`); + expect(runDateForm.payload.effectiveTo).toBe(`${midDate}T23:59:59.999999Z`); + expect(runDateForm.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999999Z`); + expect(runIsoMicrosForm.payload.effectiveFrom).toBe(runDateForm.payload.effectiveFrom); + expect(runIsoMicrosForm.payload.effectiveTo).toBe(runDateForm.payload.effectiveTo); + expect(runIsoMicrosForm.payload.effectiveAsOf).toBe(runDateForm.payload.effectiveAsOf); + expect(runIsoMicrosForm.payload.trial.expressionHash).toBe( + runDateForm.payload.trial.expressionHash + ); + expect(runOffsetForm.payload.trial.expressionHash).toBe( + runDateForm.payload.trial.expressionHash + ); + + // Distinct sub-millisecond effective bounds produce different expressionHash even with identical sampleStart/sampleEnd + const runAsOfZeroMicros = await runWithArgs({ + ...baseArgs, + from, + to: midDate, + asOf: `${midDate}T23:59:59.999000Z`, + }); + expect(runAsOfZeroMicros.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999Z`); + expect(runAsOfZeroMicros.payload.trial.sampleStart).toBe(runDateForm.payload.trial.sampleStart); + expect(runAsOfZeroMicros.payload.trial.sampleEnd).toBe(runDateForm.payload.trial.sampleEnd); + expect(runAsOfZeroMicros.payload.trial.expressionHash).not.toBe( + runDateForm.payload.trial.expressionHash + ); + + const runToZeroMicros = await runWithArgs({ + ...baseArgs, + from, + to: `${midDate}T23:59:59.999000Z`, + asOf: midDate, + }); + expect(runToZeroMicros.payload.effectiveTo).toBe(`${midDate}T23:59:59.999Z`); + expect(runToZeroMicros.payload.trial.expressionHash).not.toBe( + runDateForm.payload.trial.expressionHash + ); + + const runFromOneMicro = await runWithArgs({ + ...baseArgs, + from: `${from}T00:00:00.000001Z`, + to: midDate, + asOf: midDate, + }); + expect(runFromOneMicro.payload.effectiveFrom).toBe(`${from}T00:00:00.000001Z`); + expect(runFromOneMicro.payload.trial.expressionHash).not.toBe( + runDateForm.payload.trial.expressionHash + ); // quantile_spread ledgerSeries works, truncates preview to 100 while preserving full count, and hashes distinctly const runSpread = await runWithArgs({ ...baseArgs, ledgerSeries: 'quantile_spread' }); @@ -713,65 +788,12 @@ describe('MCP analyze_signal tool', () => { expect(runSpread.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); }); - test('clamps to/asOf strictly below cutoff and blocks post-cutoff and post-asOf leakage from a leaky store, including intraday cutoff', async () => { + test('clamps to/asOf strictly below midnight and intraday Vault cutoffs and blocks cutoff-day leakage from a leaky store', async () => { const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false }); const poisonedFixture = buildCeoShortsFixture({ poisonPostCutoff: true }); const from = cleanFixture.allDates[0]!; const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!; - - // Add a mid-window explicit asOf and verify rows known after asOf are excluded even from a leaky store - const explicitAsOfDate = cleanFixture.allDates[100]!; - const explicitAsOfMs = makeUtcMs(explicitAsOfDate, 23) + 59 * 60_000 + 59_999; - - const cleanStore = createFakeStore({ - bars: cleanFixture.bars, - shortsTable: cleanFixture.shortsTable, - leaky: false, - }); - const leakyStore = createFakeStore({ - bars: [ - ...poisonedFixture.bars, - // Extra bar on exact vaultCutoffDate before an intraday cutoff - { - listingId: poisonedFixture.listingIds[0]!, - ts: makeUtcMs(poisonedFixture.vaultCutoffDate, 10), - open: 888_888, - high: 888_888, - low: 888_888, - close: 888_888, - volume: 100, - vwap: 888_888, - knownAt: makeUtcMs(poisonedFixture.vaultCutoffDate, 10), - }, - ], - shortsTable: { - columns: poisonedFixture.shortsTable.columns, - rows: [ - ...poisonedFixture.shortsTable.rows, - // Shorts row with report_date on vaultCutoffDate and known_at before intraday cutoff - { - listing_id: poisonedFixture.listingIds[0]!, - report_date: poisonedFixture.vaultCutoffDate, - known_at: makeUtcMs(poisonedFixture.vaultCutoffDate, 9), - shares_short: 9_999_999, - net_change: 9_999_999, - pct_float: 0.99, - source: 'ceoShorts', - }, - // Shorts row with known_at after explicitAsOf - { - listing_id: poisonedFixture.listingIds[1]!, - report_date: cleanFixture.allDates[50]!, - known_at: explicitAsOfMs + 60_000, - shares_short: 7_777_777, - net_change: 7_777_777, - pct_float: 0.77, - source: 'ceoShorts', - }, - ], - }, - leaky: true, - }); + const horizonSessions = 5; // 1. Clamping test with to and asOf after Vault cutoff (midnight cutoff) const clampLedger = createFakeTrialLedger(); @@ -789,7 +811,7 @@ describe('MCP analyze_signal tool', () => { to: postCutoffDate, asOf: postCutoffDate, signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, + horizonSessions, universeMarket: 'CA_EQ', horizonBucket: 'swing_1_10d', }, @@ -813,48 +835,246 @@ describe('MCP analyze_signal tool', () => { expect(Date.parse(clampStore.shortsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); if (clampPayload.status === 'ok') { expect(clampPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true); + const endIdx = cleanFixture.allDates.indexOf(clampPayload.trial.sampleEnd); + const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!; + expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true); } - // 2. Leaky store with intraday cutoff (12:00 UTC on vaultCutoffDate) and earlier explicit asOf matches clean store + // 2. Intraday Vault cutoff (12:00 UTC on vaultCutoffDate) with asOf beyond cutoff and leaky store + // injecting rows on vaultCutoffDate before cutoff, at exact cutoff timestamp, and after cutoff. const intradayCutoffTs = makeUtcMs(cleanFixture.vaultCutoffDate, 12); + const cleanPreCutoffBars = cleanFixture.bars.filter( + b => new Date(b.ts).toISOString().slice(0, 10) < cleanFixture.vaultCutoffDate + ); + const cleanPreCutoffShorts: Table = { + columns: cleanFixture.shortsTable.columns, + rows: cleanFixture.shortsTable.rows.filter( + r => + (r.report_date as string) < cleanFixture.vaultCutoffDate && + (r.known_at as number) < intradayCutoffTs + ), + }; + const cleanIntradayStore = createFakeStore({ + bars: cleanPreCutoffBars, + shortsTable: cleanPreCutoffShorts, + leaky: false, + }); + const leakyIntradayStore = createFakeStore({ + bars: [ + ...poisonedFixture.bars, + // Cutoff-day bars BEFORE intradayCutoffTs (10:00 UTC) for every listing + ...poisonedFixture.listingIds.map(listingId => ({ + listingId, + ts: makeUtcMs(poisonedFixture.vaultCutoffDate, 10), + open: 888_888, + high: 888_888, + low: 888_888, + close: 888_888, + volume: 100, + vwap: 888_888, + knownAt: makeUtcMs(poisonedFixture.vaultCutoffDate, 10), + })), + // Bar at EXACT intradayCutoffTs (12:00 UTC) + { + listingId: poisonedFixture.listingIds[0]!, + ts: intradayCutoffTs, + open: 777_777, + high: 777_777, + low: 777_777, + close: 777_777, + volume: 100, + vwap: 777_777, + knownAt: intradayCutoffTs, + }, + ], + shortsTable: { + columns: poisonedFixture.shortsTable.columns, + rows: [ + ...poisonedFixture.shortsTable.rows, + // Shorts row on vaultCutoffDate with known_at before intradayCutoffTs + { + listing_id: poisonedFixture.listingIds[0]!, + report_date: poisonedFixture.vaultCutoffDate, + known_at: makeUtcMs(poisonedFixture.vaultCutoffDate, 9), + shares_short: 9_999_999, + net_change: 9_999_999, + pct_float: 0.99, + source: 'ceoShorts', + }, + // Shorts row with report_date before cutoff but known_at at exact intradayCutoffTs + { + listing_id: poisonedFixture.listingIds[1]!, + report_date: cleanFixture.allDates[100]!, + known_at: intradayCutoffTs, + shares_short: 8_888_888, + net_change: 8_888_888, + pct_float: 0.88, + source: 'ceoShorts', + }, + ], + }, + leaky: true, + }); + + const cleanIntradayLedger = createFakeTrialLedger(); + const leakyIntradayLedger = createFakeTrialLedger(); + const intradayArgs = { + listingIds: cleanFixture.listingIds, + from, + to: postCutoffDate, + asOf: postCutoffDate, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }; + + const cleanIntradayRes = await callAnalyzeSignal({ + store: cleanIntradayStore.store, + ledger: cleanIntradayLedger.executor, + vaultCutoffTs: intradayCutoffTs, + args: intradayArgs, + }); + const leakyIntradayRes = await callAnalyzeSignal({ + store: leakyIntradayStore.store, + ledger: leakyIntradayLedger.executor, + vaultCutoffTs: intradayCutoffTs, + args: intradayArgs, + }); + + expect(cleanIntradayRes.isError).toBe(false); + expect(leakyIntradayRes.isError).toBe(false); + expect(leakyIntradayRes.text).toBe(cleanIntradayRes.text); + expect(leakyIntradayLedger.rows).toEqual(cleanIntradayLedger.rows); + + const intradayPayload = JSON.parse(leakyIntradayRes.text) as AnalyzeSignalResultPayload; + expect(intradayPayload.status).toBe('ok'); + expect(intradayPayload.clampedTo).toBe(true); + expect(intradayPayload.clampedAsOf).toBe(true); + expect(intradayPayload.toMs).toBe(intradayCutoffTs - 1); + expect(intradayPayload.asOfMs).toBe(intradayCutoffTs - 1); + if (intradayPayload.status === 'ok') { + expect(intradayPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true); + const endIdx = cleanFixture.allDates.indexOf(intradayPayload.trial.sampleEnd); + const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!; + expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true); + } + }); + + test('earlier explicit asOf excludes bars with ts > asOf or knownAt > asOf independently from a leaky store and matches clean replay', async () => { + const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false }); + const from = cleanFixture.allDates[0]!; + const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!; + const horizonSessions = 5; + + // Set asOf to noon UTC on session 100 while `to` extends past cutoff + const asOfSessionIdx = 100; + const asOfDate = cleanFixture.allDates[asOfSessionIdx]!; + const asOfIso = `${asOfDate}T12:00:00.000Z`; + const asOfMs = makeUtcMs(asOfDate, 12); + + // Clean replay store filters strictly by ts <= asOfMs && knownAt <= asOfMs + const cleanStore = createFakeStore({ + bars: cleanFixture.bars, + shortsTable: cleanFixture.shortsTable, + leaky: false, + }); + + // Leaky store injects two independent bar leaks + a delayed shorts row: + // (a) Closing bars on `asOfDate` stamped at 21:00 UTC (> noon asOf) with knownAt at 00:00 UTC (<= noon asOf) and poisoned close + // (b) Delayed bars on session 95 (ts <= noon asOf) with knownAt at 15:00 UTC on `asOfDate` (> noon asOf) and poisoned close + const delayedBarDate = cleanFixture.allDates[95]!; + const leakyBars: BarRecord[] = cleanFixture.bars.map(bar => { + if (bar.ts === makeUtcMs(asOfDate, 21)) { + return { + ...bar, + open: 666_666, + high: 666_666, + low: 666_666, + close: 666_666, + vwap: 666_666, + knownAt: makeUtcMs(asOfDate, 0), // earlier than noon asOf, while ts (21:00 UTC) > noon asOf + }; + } + return bar; + }); + // Also inject a bar with ts <= asOfMs but knownAt > asOfMs for listing 0 on session 95 (replace clean bar? No, add extra listing or poisoned bar on a date not in clean? Better: inject on a date after clean or with a listing that has a delayed knownAt!) + // Specifically: take a clean bar on session 95 for listing 0 and verify a delayed-knownAt poison bar on session 100-1 (where ts <= asOfMs and knownAt > asOfMs) is dropped. + // Even stronger: add a synthetic bar on `delayedBarDate` at 10:00 UTC (ts <= asOfMs) with knownAt = 15:00 UTC on `asOfDate` (> asOfMs) and poisoned close 555_555. + // If knownAt filter regresses, buildForwardReturnPanel will throw duplicate_bar (conflicting close on delayedBarDate)! + leakyBars.push({ + listingId: cleanFixture.listingIds[0]!, + ts: makeUtcMs(delayedBarDate, 10), + open: 555_555, + high: 555_555, + low: 555_555, + close: 555_555, + volume: 100, + vwap: 555_555, + knownAt: makeUtcMs(asOfDate, 15), // > noon asOf, while ts <= noon asOf + }); + + const leakyStore = createFakeStore({ + bars: leakyBars, + shortsTable: { + columns: cleanFixture.shortsTable.columns, + rows: [ + ...cleanFixture.shortsTable.rows, + { + listing_id: cleanFixture.listingIds[1]!, + report_date: cleanFixture.allDates[50]!, + known_at: makeUtcMs(asOfDate, 15), // > noon asOf + shares_short: 7_777_777, + net_change: 7_777_777, + pct_float: 0.77, + source: 'ceoShorts', + }, + ], + }, + leaky: true, + }); + const cleanLedger = createFakeTrialLedger(); const leakyLedger = createFakeTrialLedger(); + const args = { + listingIds: cleanFixture.listingIds, + from, + to: postCutoffDate, + asOf: asOfIso, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }; const cleanRes = await callAnalyzeSignal({ store: cleanStore.store, ledger: cleanLedger.executor, - vaultCutoffTs: intradayCutoffTs, - args: { - listingIds: cleanFixture.listingIds, - from, - to: postCutoffDate, - asOf: explicitAsOfDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, + vaultCutoffTs: cleanFixture.vaultCutoffTs, + args, }); const leakyRes = await callAnalyzeSignal({ store: leakyStore.store, ledger: leakyLedger.executor, - vaultCutoffTs: intradayCutoffTs, - args: { - listingIds: cleanFixture.listingIds, - from, - to: postCutoffDate, - asOf: explicitAsOfDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, + vaultCutoffTs: cleanFixture.vaultCutoffTs, + args, }); expect(cleanRes.isError).toBe(false); expect(leakyRes.isError).toBe(false); expect(leakyRes.text).toBe(cleanRes.text); expect(leakyLedger.rows).toEqual(cleanLedger.rows); + + const payload = JSON.parse(leakyRes.text) as AnalyzeSignalResultPayload; + expect(payload.status).toBe('ok'); + expect(payload.clampedAsOf).toBe(false); + expect(payload.asOfMs).toBe(asOfMs); + if (payload.status === 'ok') { + const endIdx = cleanFixture.allDates.indexOf(payload.trial.sampleEnd); + const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!; + // Closing bar on asOfDate (21:00 UTC) was excluded by ts > asOfMs, so last forward endpoint must precede asOfDate + expect(lastForwardEndpoint < asOfDate).toBe(true); + } }); test('request wholly inside Vault holdout returns fixed VaultHoldoutFenceError with zero store and ledger calls', async () => { @@ -1173,6 +1393,56 @@ describe('MCP analyze_signal tool', () => { ], ['horizonSessions float', { ...validBase, horizonSessions: 2.5 }], ['negative maxSignalAgeSessions', { ...validBase, maxSignalAgeSessions: -1 }], + ['mismatched horizonBucket intraday for 5d daily horizon', { ...validBase, horizonSessions: 5, horizonBucket: 'intraday' }], + [ + 'mismatched horizonBucket position_10d_plus for 5d daily horizon', + { ...validBase, horizonSessions: 5, horizonBucket: 'position_10d_plus' }, + ], + [ + 'mismatched horizonBucket swing_1_10d for 11d daily horizon', + { ...validBase, horizonSessions: 11, horizonBucket: 'swing_1_10d' }, + ], + [ + 'mismatched horizonBucket intraday for 15d daily horizon', + { ...validBase, horizonSessions: 15, horizonBucket: 'intraday' }, + ], + [ + 'named universe CA_EQ with mismatched universeMarket FX', + { + from: validBase.from, + to: validBase.to, + signal: validBase.signal, + horizonSessions: 5, + universe: 'CA_EQ', + universeMarket: 'FX', + horizonBucket: 'swing_1_10d', + }, + ], + [ + 'named universe CA_EQ with mismatched universeMarket US_EQ', + { + from: validBase.from, + to: validBase.to, + signal: validBase.signal, + horizonSessions: 5, + universe: 'CA_EQ', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + ], + [ + 'named universe US_CA_EQ with mismatched universeMarket US_EQ', + { + from: validBase.from, + to: validBase.to, + signal: validBase.signal, + horizonSessions: 5, + universe: 'US_CA_EQ', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + ], + ['shorts study with FX universeMarket and listingIds', { ...validBase, universeMarket: 'FX' }], ]; for (const [_label, args] of invalidCases) { From e70b4b1a7dc7ae78c786ffdc13359c39f1628b7b Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 00:22:44 -0500 Subject: [PATCH 14/21] T-131: tests --- .../test/mcp-analyze-signal-qa.test.ts | 820 ++++++++++++++++++ 1 file changed, 820 insertions(+) create mode 100644 libs/research/test/mcp-analyze-signal-qa.test.ts diff --git a/libs/research/test/mcp-analyze-signal-qa.test.ts b/libs/research/test/mcp-analyze-signal-qa.test.ts new file mode 100644 index 00000000..78f010c8 --- /dev/null +++ b/libs/research/test/mcp-analyze-signal-qa.test.ts @@ -0,0 +1,820 @@ +import { describe, expect, test } from 'bun:test'; +import { + type BarBatch, + type BarRecord, + type MarketDataStore, + MarketDataStoreValidationError, + type Table, + type TableRow, +} from '../src/market-data-store'; +import { + type BarsQuery, + MarketDataStoreNotImplementedError, + type ShortsAsOfQuery, + type UniverseQuery, +} from '../src/market-data-store-duckdb'; +import { + type AnalyzeSignalResultPayload, + createAnalyzeSignalTool, + createMcpServer, +} from '../src/mcp/index'; +import { + SignalPanelError, + buildForwardReturnPanel, + shortsTableToSignalRows, +} from '../src/signal-panel'; +import { TrialLedgerError, type TrialLedgerExecutor } from '../src/trial-ledger'; + +// QA fixture: seeded synthetic short-interest panel (SEED below), 12 listings, +// 140 pre-cutoff + 10 post-cutoff business sessions from 2022-09-01, shorts +// every 10 sessions published T+4 at 22:00 UTC, gross close-to-close returns, +// raw adjustment, no fills or fees. +const SEED = 4_242_026; +const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const POISON = 'POISON' as unknown as number; +const SHORTS_COLUMNS = [ + 'listing_id', + 'report_date', + 'known_at', + 'shares_short', + 'net_change', + 'pct_float', + 'source', +] as const; + +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out: string[] = []; + const current = new Date(`${startDate}T00:00:00.000Z`); + while (out.length < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out.push(current.toISOString().slice(0, 10)); + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +function utcMs(date: string, hour: number, minute = 0): number { + return Date.parse(`${date}T00:00:00.000Z`) + hour * 3_600_000 + minute * 60_000; +} + +interface Fixture { + readonly listingIds: number[]; + readonly allDates: string[]; + readonly cutoffDate: string; + readonly cutoffTs: number; + readonly bars: BarRecord[]; + readonly shorts: Table; +} + +function buildFixture(): Fixture { + const rand = createSeededRng(SEED); + const listingCount = 12; + const pre = 140; + const allDates = makeBusinessDates('2022-09-01', pre + 10); + const cutoffDate = allDates[pre]!; + const listingIds = Array.from({ length: listingCount }, (_, i) => 70_001 + i); + const bars: BarRecord[] = []; + const shortsRows: TableRow[] = []; + const active = new Float64Array(listingCount); + const pending = new Map(); + const prices = Array.from({ length: listingCount }, (_, l) => 20 + l); + + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const released = pending.get(t - 1); + if (released !== undefined) { + for (let l = 0; l < listingCount; l += 1) { + active[l] = released[l]! / 20_000; + } + } + if (t % 10 === 0 && t + 4 < allDates.length) { + const knownAt = utcMs(allDates[t + 4]!, 22); + const values: number[] = []; + for (let l = 0; l < listingCount; l += 1) { + const netChange = Math.round((rand() * 2 - 1) * 20_000); + values.push(netChange); + shortsRows.push({ + listing_id: listingIds[l]!, + report_date: date, + known_at: knownAt, + shares_short: 100_000 + Math.round(rand() * 10_000), + net_change: netChange, + pct_float: Number((0.02 + rand() * 0.08).toFixed(4)), + source: 'ceoShorts', + }); + } + pending.set(t + 4, values); + } + for (let l = 0; l < listingCount; l += 1) { + prices[l] = Math.max(0.5, prices[l]! * (1 - 0.004 * active[l]! + (rand() * 2 - 1) * 0.008)); + const close = Number(prices[l]!.toFixed(6)); + const ts = utcMs(date, 21); + bars.push({ + listingId: listingIds[l]!, + ts, + open: close, + high: close, + low: close, + close, + volume: 10_000, + knownAt: ts, + }); + } + } + + return { + listingIds, + allDates, + cutoffDate, + cutoffTs: utcMs(cutoffDate, 0), + bars, + shorts: { columns: SHORTS_COLUMNS, rows: shortsRows }, + }; +} + +function parseBound(raw: string, endOfDay: boolean): number { + if (raw.length === 10) { + return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); + } + return Date.parse(raw); +} + +interface FakeStore { + readonly store: MarketDataStore; + readonly barsCalls: BarsQuery[]; + readonly shortsCalls: ShortsAsOfQuery[]; + readonly universeCalls: UniverseQuery[]; +} + +/** + * Correctly filtering store; `extraBars` / `extraShorts` are appended + * unconditionally to simulate an adapter that leaks rows past its filters. + */ +function createStore( + fixture: Fixture, + options?: { + extraBars?: readonly BarRecord[]; + extraShorts?: readonly TableRow[]; + universe?: (q: UniverseQuery) => number[]; + barsThrow?: unknown; + shortsThrow?: unknown; + } +): FakeStore { + const barsCalls: BarsQuery[] = []; + const shortsCalls: ShortsAsOfQuery[] = []; + const universeCalls: UniverseQuery[] = []; + const store: MarketDataStore = { + bars(q: BarsQuery): AsyncIterable { + barsCalls.push(q); + const ids = new Set(q.listingIds); + const fromMs = parseBound(q.from, false); + const toMs = parseBound(q.to, true); + const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); + const rows = fixture.bars.filter( + b => + ids.has(b.listingId) && + b.ts >= fromMs && + b.ts <= toMs && + b.ts <= asOfMs && + b.knownAt <= asOfMs + ); + const thrown = options?.barsThrow; + return { + async *[Symbol.asyncIterator]() { + if (thrown !== undefined) { + throw thrown; + } + yield { rows: [...rows, ...(options?.extraBars ?? [])] }; + }, + }; + }, + async shortsAsOf(q: ShortsAsOfQuery): Promise
{ + shortsCalls.push(q); + if (options?.shortsThrow !== undefined) { + throw options.shortsThrow; + } + const ids = new Set(q.listingIds); + const fromDate = q.from.slice(0, 10); + const toDate = q.to.slice(0, 10); + const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); + const rows = fixture.shorts.rows.filter( + r => + ids.has(r.listing_id as number) && + (r.report_date as string) >= fromDate && + (r.report_date as string) <= toDate && + (r.known_at as number) <= asOfMs + ); + return { columns: fixture.shorts.columns, rows: [...rows, ...(options?.extraShorts ?? [])] }; + }, + async universe(q: UniverseQuery): Promise { + universeCalls.push(q); + return options?.universe?.(q) ?? []; + }, + crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + events() { + throw new MarketDataStoreNotImplementedError('events'); + }, + macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; + return { store, barsCalls, shortsCalls, universeCalls }; +} + +interface LedgerRow { + readonly trial_id: string; + readonly created_at: Date; + readonly principal_id: string; + readonly campaign_id: string | null; + readonly stage: string; + readonly universe_market: string; + readonly horizon_bucket: string; + readonly hypothesis_id: string | null; + readonly expression_hash: string; + readonly sample_start: string; + readonly sample_end: string; + readonly n_obs: number; + readonly sharpe_unann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly daily_series: readonly number[]; +} + +function createLedger(options?: { insertThrow?: unknown }): { + executor: TrialLedgerExecutor; + rows: LedgerRow[]; +} { + const rows: LedgerRow[] = []; + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + const sql = text.trimStart(); + if (sql.startsWith('INSERT INTO trial_ledger')) { + if (options?.insertThrow !== undefined) { + throw options.insertThrow; + } + const p = params ?? []; + const id = rows.length + 1; + const row: LedgerRow = { + trial_id: String(id), + created_at: new Date(Date.UTC(2024, 0, 1, 0, 0, id)), + principal_id: p[0] as string, + campaign_id: (p[1] as string | null) ?? null, + stage: p[2] as string, + universe_market: p[3] as string, + horizon_bucket: p[4] as string, + hypothesis_id: (p[5] as string | null) ?? null, + expression_hash: p[6] as string, + sample_start: p[7] as string, + sample_end: p[8] as string, + n_obs: p[9] as number, + sharpe_unann: p[10] as number, + skewness: p[11] as number, + kurtosis: p[12] as number, + daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)), + }; + rows.push(row); + return { + rows: [{ trial_id: row.trial_id, created_at: row.created_at } as unknown as Row], + rowCount: 1, + }; + } + if (sql.startsWith('SELECT')) { + if (text.includes('WHERE trial_id = $1::bigint')) { + const m = rows.filter(r => r.trial_id === String(params?.[0])); + return { rows: m as unknown as Row[], rowCount: m.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const m = rows.filter( + r => r.universe_market === params?.[0] && r.horizon_bucket === params?.[1] + ); + return { rows: m as unknown as Row[], rowCount: m.length }; + } + } + return { rows: [], rowCount: 0 }; + }, + }; + return { executor, rows }; +} + +async function call(params: { + store: MarketDataStore; + ledger: TrialLedgerExecutor; + cutoffTs: number; + args: Record; + principalId?: string; +}): Promise<{ raw: string; isError: boolean; text: string }> { + const server = createMcpServer({ + name: 'qa', + version: '0.0.0', + tools: [ + createAnalyzeSignalTool({ + store: params.store, + ledger: params.ledger, + vaultContext: { vaultCutoffTs: params.cutoffTs }, + principalId: params.principalId ?? AGENT_PRINCIPAL, + }), + ], + }); + const raw = (await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'analyze_signal', arguments: params.args }, + }) + )) as string; + const parsed = JSON.parse(raw) as { + result: { isError?: boolean; content: { text: string }[] }; + }; + return { + raw, + isError: parsed.result.isError === true, + text: parsed.result.content[0]?.text ?? '', + }; +} + +function baseArgs(fixture: Fixture): Record { + return { + listingIds: fixture.listingIds, + from: fixture.allDates[0]!, + to: fixture.allDates[fixture.allDates.length - 1]!, + signal: { source: 'shorts', field: 'net_change' }, + horizonSessions: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }; +} + +function poisonBar(listingId: number, ts: number, knownAt: number): BarRecord { + return { + listingId, + ts, + open: POISON, + high: POISON, + low: POISON, + close: POISON, + volume: 1, + knownAt, + }; +} + +function poisonShort(listingId: number, reportDate: string, knownAt: number): TableRow { + return { + listing_id: listingId, + report_date: reportDate, + known_at: knownAt, + shares_short: POISON, + net_change: POISON, + pct_float: POISON, + source: 'poison', + }; +} + +describe('analyze_signal QA: sentinel rows that would fail panel validation if forwarded', () => { + test('positive control: a poison bar or poison shorts row inside the window reaches the panel and maps to a fixed SignalPanelError', async () => { + const fixture = buildFixture(); + const inWindowTs = utcMs(fixture.allDates[50]!, 21); + + expect(() => + shortsTableToSignalRows( + { columns: SHORTS_COLUMNS, rows: [poisonShort(fixture.listingIds[0]!, '2022-10-03', 1)] }, + 'net_change' + ) + ).toThrow(SignalPanelError); + + const leakedBar = await call({ + store: createStore(fixture, { + extraBars: [poisonBar(fixture.listingIds[0]!, inWindowTs + 60_000, inWindowTs + 60_000)], + }).store, + ledger: createLedger().executor, + cutoffTs: fixture.cutoffTs, + args: baseArgs(fixture), + }); + expect(leakedBar.isError).toBe(true); + expect(leakedBar.text).toBe('SignalPanelError: Market bar data failed panel validation.'); + expect(leakedBar.raw).not.toContain('POISON'); + + const ledger = createLedger(); + const leakedShort = await call({ + store: createStore(fixture, { + extraShorts: [poisonShort(fixture.listingIds[0]!, fixture.allDates[50]!, inWindowTs)], + }).store, + ledger: ledger.executor, + cutoffTs: fixture.cutoffTs, + args: baseArgs(fixture), + }); + expect(leakedShort.isError).toBe(true); + expect(leakedShort.text).toBe('SignalPanelError: Signal table data failed panel validation.'); + expect(leakedShort.raw).not.toContain('POISON'); + expect(ledger.rows).toHaveLength(0); + }); + + test('midnight Vault clamp: sentinels at/after the cutoff, before from, or for foreign listings never reach the panel; result equals clean replay', async () => { + const fixture = buildFixture(); + const lid = fixture.listingIds[3]!; + const extraBars = [ + poisonBar(lid, fixture.cutoffTs, fixture.cutoffTs - 1), // exact cutoff ts, backdated knownAt + poisonBar(lid, utcMs(fixture.allDates[100]!, 21), fixture.cutoffTs), // knownAt at cutoff + poisonBar(99_999, utcMs(fixture.allDates[100]!, 15), utcMs(fixture.allDates[100]!, 15)), + poisonBar(lid, utcMs('2022-08-15', 21), utcMs('2022-08-15', 21)), // before from + ]; + const extraShorts = [ + poisonShort(lid, fixture.cutoffDate, fixture.cutoffTs - 1), // cutoff-day report, backdated + poisonShort(lid, fixture.allDates[100]!, fixture.cutoffTs), // known exactly at cutoff + poisonShort(99_999, fixture.allDates[100]!, utcMs(fixture.allDates[105]!, 22)), + poisonShort(lid, '2022-08-15', utcMs('2022-08-19', 22)), // report before from + ]; + + const cleanLedger = createLedger(); + const clean = await call({ + store: createStore(fixture).store, + ledger: cleanLedger.executor, + cutoffTs: fixture.cutoffTs, + args: baseArgs(fixture), + }); + const poisonedLedger = createLedger(); + const poisoned = await call({ + store: createStore(fixture, { extraBars, extraShorts }).store, + ledger: poisonedLedger.executor, + cutoffTs: fixture.cutoffTs, + args: baseArgs(fixture), + }); + + expect(clean.isError).toBe(false); + expect(poisoned.isError).toBe(false); + const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; + expect(payload.status).toBe('ok'); + expect(payload.clampedTo).toBe(true); + // Omitted asOf defaults to the already-clamped `to`, so only `to` reports a clamp. + expect(payload.clampedAsOf).toBe(false); + expect(payload.asOfMs).toBe(fixture.cutoffTs - 1); + if (payload.status === 'ok') { + expect(payload.trial.sampleEnd < fixture.cutoffDate).toBe(true); + } + expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); + expect(poisonedLedger.rows).toEqual(cleanLedger.rows); + }); + + test('intraday Vault cutoff: cutoff-date bars before the cutoff instant and cutoff-date shorts are excluded; result equals clean replay', async () => { + const fixture = buildFixture(); + const cutoffTs = utcMs(fixture.cutoffDate, 15); + const lid = fixture.listingIds[5]!; + const earlyCutoffDay = utcMs(fixture.cutoffDate, 14); + const extraBars = [ + poisonBar(lid, earlyCutoffDay, earlyCutoffDay), // before cutoff instant, same UTC date + poisonBar(lid, cutoffTs, earlyCutoffDay), // exactly at cutoff + ]; + const extraShorts = [ + poisonShort(lid, fixture.cutoffDate, utcMs(fixture.cutoffDate, 10)), // known before cutoff instant + ]; + + const cleanLedger = createLedger(); + const clean = await call({ + store: createStore(fixture).store, + ledger: cleanLedger.executor, + cutoffTs, + args: { ...baseArgs(fixture), asOf: fixture.allDates[fixture.allDates.length - 1]! }, + }); + const poisonedLedger = createLedger(); + const poisoned = await call({ + store: createStore(fixture, { extraBars, extraShorts }).store, + ledger: poisonedLedger.executor, + cutoffTs, + args: { ...baseArgs(fixture), asOf: fixture.allDates[fixture.allDates.length - 1]! }, + }); + + expect(poisoned.isError).toBe(false); + const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; + expect(payload.clampedTo).toBe(true); + expect(payload.clampedAsOf).toBe(true); + expect(payload.effectiveTo).toBe(`${fixture.cutoffDate}T14:59:59.999999Z`); + expect(payload.status).toBe('ok'); + expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); + expect(poisonedLedger.rows).toEqual(cleanLedger.rows); + }); + + test('earlier explicit asOf: shorts known after asOf and bars stamped or known after asOf are excluded; result equals clean replay', async () => { + const fixture = buildFixture(); + const asOfDate = fixture.allDates[120]!; + const asOf = `${asOfDate}T18:00:00.000Z`; + const asOfMs = Date.parse(asOf); + const lid = fixture.listingIds[7]!; + const extraBars = [ + poisonBar(lid, utcMs(asOfDate, 21), utcMs(asOfDate, 0)), // close after asOf, backdated knownAt + poisonBar(lid, utcMs(fixture.allDates[119]!, 22), asOfMs + 1), // known 1ms after asOf + ]; + const extraShorts = [poisonShort(lid, fixture.allDates[100]!, asOfMs + 1)]; + const args = { ...baseArgs(fixture), asOf }; + + const cleanLedger = createLedger(); + const clean = await call({ + store: createStore(fixture).store, + ledger: cleanLedger.executor, + cutoffTs: fixture.cutoffTs, + args, + }); + const poisonedLedger = createLedger(); + const poisoned = await call({ + store: createStore(fixture, { extraBars, extraShorts }).store, + ledger: poisonedLedger.executor, + cutoffTs: fixture.cutoffTs, + args, + }); + + expect(poisoned.isError).toBe(false); + const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; + expect(payload.status).toBe('ok'); + expect(payload.clampedAsOf).toBe(false); + expect(payload.effectiveAsOf).toBe(asOf); + if (payload.status === 'ok') { + expect(payload.trial.sampleEnd < asOfDate).toBe(true); + } + expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); + expect(poisonedLedger.rows).toEqual(cleanLedger.rows); + }); +}); + +describe('analyze_signal QA: store arguments, universe and ledger behaviour', () => { + test('bars and shorts receive identical fenced bounds, 1d timeframe, vault_fenced scope and requested adjustment', async () => { + const fixture = buildFixture(); + const fake = createStore(fixture); + await call({ + store: fake.store, + ledger: createLedger().executor, + cutoffTs: fixture.cutoffTs, + args: { ...baseArgs(fixture), adjustment: 'split' }, + }); + + expect(fake.barsCalls).toHaveLength(1); + expect(fake.shortsCalls).toHaveLength(1); + const bars = fake.barsCalls[0]!; + const shorts = fake.shortsCalls[0]!; + expect(bars.timeframe).toBe('1d'); + expect(bars.scope).toBe('vault_fenced'); + expect(bars.adjustment).toBe('split'); + expect(bars.from).toBe(shorts.from); + expect(bars.to).toBe(shorts.to); + expect(bars.asOf).toBe(shorts.asOf); + expect(bars.listingIds).toEqual(shorts.listingIds); + const lastAllowed = new Date(fixture.cutoffTs - 1).toISOString().replace('Z', '999Z'); + expect(bars.to).toBe(lastAllowed); + expect(bars.asOf).toBe(lastAllowed); + + const defaulted = createStore(fixture); + await call({ + store: defaulted.store, + ledger: createLedger().executor, + cutoffTs: fixture.cutoffTs, + args: baseArgs(fixture), + }); + expect(defaulted.barsCalls[0]?.adjustment).toBe('raw'); + }); + + test('named universe: one snapshot lookup before from; resolved IDs are sorted and deduplicated before the store query', async () => { + const fixture = buildFixture(); + const shuffled = [...fixture.listingIds].reverse(); + const fake = createStore(fixture, { + universe: () => [...shuffled, fixture.listingIds[0]!, fixture.listingIds[1]!], + }); + const ledger = createLedger(); + const args = { ...baseArgs(fixture), universe: 'CA_EQ' } as Record; + delete args.listingIds; + + const res = await call({ store: fake.store, ledger: ledger.executor, cutoffTs: fixture.cutoffTs, args }); + expect(res.isError).toBe(false); + expect(fake.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-31' }]); + expect(fake.barsCalls[0]?.listingIds).toEqual(fixture.listingIds); + expect(fake.shortsCalls[0]?.listingIds).toEqual(fixture.listingIds); + const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; + expect(payload.listingCount).toBe(fixture.listingIds.length); + }); + + test('named-universe expression hash differs from the same IDs selected explicitly', async () => { + const fixture = buildFixture(); + const explicitLedger = createLedger(); + await call({ + store: createStore(fixture).store, + ledger: explicitLedger.executor, + cutoffTs: fixture.cutoffTs, + args: baseArgs(fixture), + }); + const universeLedger = createLedger(); + const args = { ...baseArgs(fixture), universe: 'CA_EQ' } as Record; + delete args.listingIds; + await call({ + store: createStore(fixture, { universe: () => fixture.listingIds }).store, + ledger: universeLedger.executor, + cutoffTs: fixture.cutoffTs, + args, + }); + expect(explicitLedger.rows).toHaveLength(1); + expect(universeLedger.rows).toHaveLength(1); + expect(universeLedger.rows[0]!.expression_hash).not.toBe(explicitLedger.rows[0]!.expression_hash); + expect(universeLedger.rows[0]!.daily_series).toEqual(explicitLedger.rows[0]!.daily_series); + }); + + test('maxSignalAgeSessions is applied to the panel and changes the expression hash', async () => { + const fixture = buildFixture(); + const run = async (extra: Record) => { + const ledger = createLedger(); + const res = await call({ + store: createStore(fixture).store, + ledger: ledger.executor, + cutoffTs: fixture.cutoffTs, + args: { ...baseArgs(fixture), ...extra }, + }); + return { payload: JSON.parse(res.text) as AnalyzeSignalResultPayload, ledger }; + }; + const unbounded = await run({}); + const capped = await run({ maxSignalAgeSessions: 3 }); + + expect(unbounded.payload.panelDiagnostics.droppedStaleSignal).toBe(0); + expect(capped.payload.panelDiagnostics.droppedStaleSignal).toBeGreaterThan(0); + expect(capped.payload.status).toBe('ok'); + expect(capped.ledger.rows[0]!.expression_hash).not.toBe(unbounded.ledger.rows[0]!.expression_hash); + }); + + test('replaying the same request on one ledger appends a second row with the same hash and grows the DSR cluster', async () => { + const fixture = buildFixture(); + const ledger = createLedger(); + const first = await call({ + store: createStore(fixture).store, + ledger: ledger.executor, + cutoffTs: fixture.cutoffTs, + args: baseArgs(fixture), + }); + const second = await call({ + store: createStore(fixture).store, + ledger: ledger.executor, + cutoffTs: fixture.cutoffTs, + args: baseArgs(fixture), + }); + const p1 = JSON.parse(first.text) as AnalyzeSignalResultPayload; + const p2 = JSON.parse(second.text) as AnalyzeSignalResultPayload; + if (p1.status !== 'ok' || p2.status !== 'ok') { + throw new Error('expected ok'); + } + expect(ledger.rows).toHaveLength(2); + expect(p2.trial.expressionHash).toBe(p1.trial.expressionHash); + expect(p2.trial.trialId).not.toBe(p1.trial.trialId); + expect(p1.deflatedSharpe.clusterSize).toBe(1); + expect(p2.deflatedSharpe.clusterSize).toBe(2); + }); + + test('operator principal is accepted and recorded; caller cannot change it', async () => { + const fixture = buildFixture(); + const ledger = createLedger(); + const res = await call({ + store: createStore(fixture).store, + ledger: ledger.executor, + cutoffTs: fixture.cutoffTs, + principalId: 'operator', + args: baseArgs(fixture), + }); + expect(res.isError).toBe(false); + expect(ledger.rows.map(r => r.principal_id)).toEqual(['operator']); + }); + + test('unsupported universe refs accept equity market labels but reject FX before any store call', async () => { + const fixture = buildFixture(); + const args = { ...baseArgs(fixture), universe: 'TSX_COMPOSITE' } as Record; + delete args.listingIds; + + const okStore = createStore(fixture, { universe: () => fixture.listingIds }); + const ok = await call({ store: okStore.store, ledger: createLedger().executor, cutoffTs: fixture.cutoffTs, args }); + expect(ok.isError).toBe(false); + expect(okStore.universeCalls[0]?.ref).toBe('TSX_COMPOSITE'); + + const fxStore = createStore(fixture); + const fxLedger = createLedger(); + const fx = await call({ + store: fxStore.store, + ledger: fxLedger.executor, + cutoffTs: fixture.cutoffTs, + args: { ...args, universeMarket: 'FX' }, + }); + expect(JSON.parse(fx.raw).error ?? JSON.parse(fx.raw).result?.isError).toBeTruthy(); + expect(fxStore.universeCalls).toHaveLength(0); + expect(fxStore.barsCalls).toHaveLength(0); + expect(fxLedger.rows).toHaveLength(0); + }); +}); + +describe('analyze_signal QA: factory validation and error sanitisation', () => { + test('factory rejects invalid principal, ledger, store and cutoff without touching the store', () => { + const fixture = buildFixture(); + const fake = createStore(fixture); + const ledger = createLedger().executor; + const vaultContext = { vaultCutoffTs: fixture.cutoffTs }; + + expect(() => + createAnalyzeSignalTool({ store: fake.store, ledger, vaultContext, principalId: 'agent:not-a-uuid' }) + ).toThrow(TrialLedgerError); + expect(() => + createAnalyzeSignalTool({ + store: fake.store, + ledger: {} as TrialLedgerExecutor, + vaultContext, + principalId: AGENT_PRINCIPAL, + }) + ).toThrow(); + expect(() => + createAnalyzeSignalTool({ + store: { bars: fake.store.bars } as unknown as MarketDataStore, + ledger, + vaultContext, + principalId: AGENT_PRINCIPAL, + }) + ).toThrow(MarketDataStoreValidationError); + for (const bad of [Number.NaN, 1.5, Number.POSITIVE_INFINITY, undefined]) { + expect(() => + createAnalyzeSignalTool({ + store: fake.store, + ledger, + vaultContext: { vaultCutoffTs: bad as number }, + principalId: AGENT_PRINCIPAL, + }) + ).toThrow(MarketDataStoreValidationError); + } + expect(fake.barsCalls).toHaveLength(0); + expect(fake.universeCalls).toHaveLength(0); + }); + + test('unknown errors, non-Error throws and unsafe validation fields return fixed generic text with no secrets', async () => { + const fixture = buildFixture(); + const secret = + 'SELECT * FROM bars_1d WHERE x; /srv/data/parquet/bars.parquet postgres://user:pass@host:5432/db'; + const cases: readonly [string, Parameters[1], { insertThrow?: unknown } | undefined, string][] = [ + ['plain Error from bars stream', { barsThrow: new Error(secret) }, undefined, 'Error: Tool execution failed.'], + ['string thrown from shortsAsOf', { shortsThrow: secret }, undefined, 'Error: Tool execution failed.'], + [ + 'validation error with unsafe field name', + { shortsThrow: new MarketDataStoreValidationError(secret, secret) }, + undefined, + 'MarketDataStoreValidationError: Query parameters failed store validation.', + ], + [ + 'not-implemented error for unknown method', + { barsThrow: new MarketDataStoreNotImplementedError(secret as never) }, + undefined, + 'MarketDataStoreNotImplementedError: Requested store operation is not supported.', + ], + ['plain Error from ledger insert', undefined, { insertThrow: new Error(secret) }, 'Error: Tool execution failed.'], + [ + 'unmapped TrialLedgerError code', + undefined, + { insertThrow: new TrialLedgerError('INVALID_ROW', secret) }, + 'TrialLedgerError: Trial ledger operation failed.', + ], + ]; + + for (const [label, storeOpts, ledgerOpts, expected] of cases) { + const ledger = createLedger(ledgerOpts); + const res = await call({ + store: createStore(fixture, storeOpts).store, + ledger: ledger.executor, + cutoffTs: fixture.cutoffTs, + args: baseArgs(fixture), + }); + expect(res.isError, label).toBe(true); + expect(res.text, label).toBe(expected); + for (const fragment of ['SELECT', 'bars_1d', '/srv/data', 'postgres://', 'user:pass', 'stack']) { + expect(res.raw.includes(fragment), `${label}: ${fragment}`).toBe(false); + } + expect(ledger.rows, label).toHaveLength(0); + } + }); + + test('a poison bar forwarded to the panel builder directly throws, proving the sentinel is meaningful', () => { + const fixture = buildFixture(); + const ts = utcMs(fixture.allDates[10]!, 21); + expect(() => + buildForwardReturnPanel({ + bars: [...fixture.bars.filter(b => b.ts < fixture.cutoffTs), poisonBar(fixture.listingIds[0]!, ts + 1, ts + 1)], + signals: [], + horizonSessions: 5, + vaultCutoffDate: fixture.cutoffDate, + }) + ).toThrow(SignalPanelError); + }); +}); From f9ac7024d39044a91193817b06a9c67960c19f86 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 00:36:15 -0500 Subject: [PATCH 15/21] =?UTF-8?q?T-133:=20M2.1c=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`event=5Fstudy`=20tool:=20vault-fenced=20event=20study=20(b?= =?UTF-8?q?ars=20+=20`events`=20=E2=86=92=20`buildEventStudyInput`=20?= =?UTF-8?q?=E2=86=92=20`runEventStudy`=20+=20trial=20ledger)=20in=20`libs/?= =?UTF-8?q?research/src/mcp/tools/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 8 +- libs/research/src/mcp/index.ts | 1 + libs/research/src/mcp/tools/event-study.ts | 999 ++++++++++++ libs/research/test/mcp-event-study-qa.test.ts | 658 ++++++++ libs/research/test/mcp-event-study.test.ts | 1419 +++++++++++++++++ 5 files changed, 3084 insertions(+), 1 deletion(-) create mode 100644 libs/research/src/mcp/tools/event-study.ts create mode 100644 libs/research/test/mcp-event-study-qa.test.ts create mode 100644 libs/research/test/mcp-event-study.test.ts diff --git a/libs/research/README.md b/libs/research/README.md index fd8e76ad..ffb83567 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -212,8 +212,14 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **`createQueryDataTool({ store, vaultContext })`** — Wraps an injected `MarketDataStore` for explicit `listingIds` (max `QUERY_DATA_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref, with bounded output rows (`QUERY_DATA_DEFAULT_LIMIT = 500`, hard max `QUERY_DATA_MAX_LIMIT = 5_000`). - Always enforces `scope: 'vault_fenced'` via `applyVaultFence` before any store call, omits `scope` / `vault_evaluation_only` from the strict schema (rejecting unknown keys with zero store calls), drops any post-cutoff row (`ts >= vaultCutoffTs` or `knownAt >= vaultCutoffTs`) as defense in depth, and maps `VaultHoldoutFenceError`, `VaultScopeNotAuthorizedError`, `MarketDataStoreValidationError`, `MarketDataStoreNotImplementedError`, and `AdjFactorsSnapshotError` to `isError: true` responses naming the error class. +### `event_study` Tool (Vault-Fenced) + +- **`createEventStudyTool({ store, ledger, vaultContext, principalId, resolveExchangeCalendars })`** — Runs a Vault-fenced event study over daily bars and point-in-time `events` (`filing`, `earnings`, `ceo_post`, `corporate_action`, with optional exact `subtypes` filter) for explicit `listingIds` (max `EVENT_STUDY_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref matching `universeMarket`, across `[-preDays, +postDays]` (`0–60` sessions each; `horizonBucket` must match `postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'`). +- **Injected exchange calendars:** `resolveExchangeCalendars({ listingIds, fromDate, toDate })` supplies actual exchange session close timestamps (including half-days) for `buildEventStudyInput` so events are anchored without synthesizing calendars from bars. +- **Returns, benchmark & Vault fence:** Models daily close-to-close returns with no execution or transaction costs (`adjustment` defaults to `'raw'`; `benchmark` defaults to `'equal_weight'` using available eligible listing returns, or `'none'` for unbenchmarked returns). Enforces `scope: 'vault_fenced'`, clamps `to`/`asOf` strictly below `vaultCutoffTs`, resolves named universes strictly pre-start, defensively excludes any bar or event on or after the Vault cutoff date (or with `known_at > asOf`), and writes eligible trials exclusively to the injected `trial_ledger` (`stage = 'event_study'`) under the server-injected `principalId`. + ### Remaining M2 MCP Items (Later Tasks) -- Additional research tools: `search_symbols`, `analyze_signal`, `event_study`, `file_finding`, and `read_knowledge`. +- Additional research tools: `search_symbols`, `analyze_signal`, `file_finding`, and `read_knowledge`. - SSE/HTTP transport wrapper in `apps/stock/web-api`. - Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters. diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 1838886b..6a966bc9 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -2,4 +2,5 @@ export * from './protocol'; export * from './server'; export * from './stdio'; export * from './tools/analyze-signal'; +export * from './tools/event-study'; export * from './tools/query-data'; diff --git a/libs/research/src/mcp/tools/event-study.ts b/libs/research/src/mcp/tools/event-study.ts new file mode 100644 index 00000000..23faad0e --- /dev/null +++ b/libs/research/src/mcp/tools/event-study.ts @@ -0,0 +1,999 @@ +import type { + EventStudyDiagnostics, + EventStudyRecencyResult, + EventStudyResult, + NeweyWestResult, +} from '@stock-bot/calculations'; +import { z } from 'zod'; +import { + type EventPanelDiagnostics, + EventPanelError, + type EventPanelErrorCode, + type EventStudyBenchmarkMode, + type EventStudyExchangeCalendars, + buildEventStudyInput, + eventsTableToEventRows, +} from '../../event-panel'; +import { + type BarRecord, + type EventKind, + type MarketDataStore, + MarketDataStoreValidationError, + type Table, + type TableRow, + type VaultFenceContext, +} from '../../market-data-store'; +import { EVENT_KINDS } from '../../market-data-store-duckdb'; +import { collectBars } from '../../signal-panel'; +import { + type RunEventStudyInsufficientDataReason, + SignalStudyError, + type SignalStudyErrorCode, + type SignalStudyExpression, + type StudyTrialSummary, + runEventStudy, +} from '../../signal-study'; +import { + type ClusterDeflatedSharpeResult, + HORIZON_BUCKETS, + type HorizonBucket, + TrialLedgerError, + type TrialLedgerErrorCode, + type TrialLedgerExecutor, + UNIVERSE_MARKETS, + type UniverseMarket, +} from '../../trial-ledger'; +import type { McpToolCallResult } from '../protocol'; +import { type McpToolEntry, defineMcpTool } from '../server'; +import { + EXCLUSIVE_LISTING_SELECTOR_MESSAGE, + MAX_ECMASCRIPT_EPOCH_MS, + MCP_MAX_LISTING_IDS, + MS_PER_DAY, + createListingIdsFieldSchema, + createUniverseFieldSchema, + fenceVaultQueryBounds, + formatMappedStoreError, + hasExclusiveListingSelector, + isValidUtcBoundString, + resolvePreStartUniverseDate, + utcDateOf, + validateVaultCutoffTs, +} from './vault-fenced-input'; + +/** Hard maximum number of explicit `listingIds` accepted by `event_study`. */ +export const EVENT_STUDY_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS; + +/** Hard maximum pre-event window length in trading sessions. */ +export const EVENT_STUDY_MAX_PRE_DAYS = 60; + +/** Hard maximum post-event window length in trading sessions. */ +export const EVENT_STUDY_MAX_POST_DAYS = 60; + +const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const AGENT_PRINCIPAL_RE = + /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; +const UTC_BOUND_ERROR_MESSAGE = + 'Expected YYYY-MM-DD calendar date or UTC ISO-8601 timestamp with timezone offset.'; +const EVENT_KIND_SET: ReadonlySet = new Set(EVENT_KINDS); + +function canonicalDailyHorizonBucket(postDays: number): HorizonBucket { + return postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'; +} + +function isValidEpochMs(value: unknown): value is number { + return ( + typeof value === 'number' && + Number.isFinite(value) && + Number.isSafeInteger(value) && + Math.abs(value) < MAX_ECMASCRIPT_EPOCH_MS + ); +} + +const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE); + +const eventFilterSpecSchema = z + .object({ + kinds: z + .array(z.enum(EVENT_KINDS)) + .min(1) + .describe( + 'Non-empty list of event kinds to include (filing, earnings, ceo_post, or corporate_action).' + ), + subtypes: z + .array(z.string().min(1)) + .min(1) + .optional() + .describe('Optional non-empty exact-match allow-list of event subtypes.'), + }) + .strict() + .describe('Event kind and optional subtype filter specification.'); + +/** + * Strict Zod input schema for the `event_study` MCP tool. + * + * Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and + * `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them + * or any other unknown top-level or nested key. + */ +export const eventStudyInputSchema = z + .object({ + listingIds: createListingIdsFieldSchema( + 'Explicit INT32 listing IDs to study (mutually exclusive with universe).' + ), + universe: createUniverseFieldSchema( + 'Survivorship-free universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).' + ), + from: utcBoundStringSchema.describe( + 'Inclusive study start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.' + ), + to: utcBoundStringSchema.describe( + 'Inclusive study end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.' + ), + asOf: utcBoundStringSchema + .optional() + .describe( + 'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.' + ), + event: eventFilterSpecSchema, + preDays: z + .number() + .int() + .min(0) + .max(EVENT_STUDY_MAX_PRE_DAYS) + .describe( + `Pre-event window in trading sessions (0–${EVENT_STUDY_MAX_PRE_DAYS}).` + ), + postDays: z + .number() + .int() + .min(0) + .max(EVENT_STUDY_MAX_POST_DAYS) + .describe( + `Post-event window in trading sessions (0–${EVENT_STUDY_MAX_POST_DAYS}).` + ), + benchmark: z + .enum(['equal_weight', 'none']) + .default('equal_weight') + .describe( + 'Benchmark return mode: equal_weight (cross-sectional mean of eligible listing returns) or none (default equal_weight).' + ), + adjustment: z + .enum(['raw', 'split', 'total']) + .default('raw') + .describe('Bar price adjustment mode (default raw).'), + universeMarket: z + .enum(UNIVERSE_MARKETS) + .describe('Relatedness-cluster market bucket recorded in trial_ledger.'), + horizonBucket: z + .enum(HORIZON_BUCKETS) + .describe('Relatedness-cluster horizon bucket recorded in trial_ledger.'), + campaignId: z + .string() + .regex(LEDGER_UUID_RE, 'Expected a UUID string.') + .optional() + .describe('Optional research campaign UUID recorded in trial_ledger.'), + hypothesisId: z + .string() + .regex(LEDGER_UUID_RE, 'Expected a UUID string.') + .optional() + .describe('Optional research hypothesis UUID recorded in trial_ledger.'), + }) + .strict() + .superRefine((data, ctx) => { + if (!hasExclusiveListingSelector(data)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: EXCLUSIVE_LISTING_SELECTOR_MESSAGE, + }); + } + + const expectedBucket = canonicalDailyHorizonBucket(data.postDays); + if (data.horizonBucket !== expectedBucket) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['horizonBucket'], + message: `Daily postDays=${data.postDays} requires horizonBucket "${expectedBucket}".`, + }); + } + + if (data.universe !== undefined && data.universeMarket !== data.universe) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['universeMarket'], + message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`, + }); + } + }); + +export type EventStudyToolInput = z.infer; + +/** Query passed to the server-injected exchange-calendar resolver. */ +export interface EventStudyExchangeCalendarQuery { + readonly listingIds: readonly number[]; + readonly fromDate: string; + readonly toDate: string; +} + +/** Server-injected exchange-calendar resolver returning actual session close calendars. */ +export type EventStudyExchangeCalendarResolver = ( + query: EventStudyExchangeCalendarQuery +) => Promise | EventStudyExchangeCalendars; + +/** Server-side injected configuration for {@link createEventStudyTool}. */ +export interface EventStudyToolOptions { + readonly store: MarketDataStore; + readonly ledger: TrialLedgerExecutor; + readonly vaultContext: Pick; + readonly principalId: string; + readonly resolveExchangeCalendars: EventStudyExchangeCalendarResolver; +} + +/** Projected CAR/AAR summary for one relative offset in `[-preDays, +postDays]`. */ +export interface EventStudyOffsetSummary { + readonly offset: number; + readonly n: number; + readonly aar: number; + readonly caar: number; + readonly caarFromZero: number | null; +} + +/** Bounded date-clustered CAR summary without raw per-date typed arrays. */ +export interface EventStudyClusteredSummary { + readonly nDates: number; + readonly carMean: number; + readonly neweyWest: NeweyWestResult; +} + +/** Bounded summary projection of {@link EventStudyResult}. */ +export interface EventStudySummary { + readonly preDays: number; + readonly postDays: number; + readonly hasBenchmark: boolean; + readonly offsets: readonly EventStudyOffsetSummary[]; + readonly clustered: EventStudyClusteredSummary | null; + readonly recency: EventStudyRecencyResult | null; + readonly diagnostics: EventStudyDiagnostics; +} + +interface EventStudyResultBase { + readonly scope: 'vault_fenced'; + readonly vaultCutoffTs: number; + readonly vaultCutoffDate: string; + readonly event: { + readonly kinds: readonly EventKind[]; + readonly subtypes: readonly string[] | null; + }; + readonly preDays: number; + readonly postDays: number; + readonly benchmark: EventStudyBenchmarkMode; + readonly adjustment: 'raw' | 'split' | 'total'; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly fromMs: number; + readonly toMs: number; + readonly asOfMs: number; + readonly effectiveFrom: string; + readonly effectiveTo: string; + readonly effectiveAsOf: string; + readonly clampedTo: boolean; + readonly clampedAsOf: boolean; + readonly listingCount: number; + readonly eventCount: number; + readonly vaultExcludedEvents: number; + readonly panelDiagnostics: EventPanelDiagnostics; + readonly study: EventStudySummary; +} + +/** Structured JSON payload serialized into the `event_study` MCP text result. */ +export type EventStudyResultPayload = + | (EventStudyResultBase & { + readonly status: 'ok'; + readonly trial: StudyTrialSummary; + readonly deflatedSharpe: ClusterDeflatedSharpeResult; + }) + | (EventStudyResultBase & { + readonly status: 'insufficient_data'; + readonly reason: RunEventStudyInsufficientDataReason; + }); + +class ExchangeCalendarResolverError extends Error { + override readonly name = 'ExchangeCalendarResolverError'; + override readonly cause?: unknown; + + constructor(cause: unknown) { + super('Exchange calendar resolution failed.', { cause }); + this.cause = cause; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +const ZERO_EVENT_PANEL_DIAGNOSTICS: EventPanelDiagnostics = { + vaultExcludedDates: 0, + vaultExcludedEvents: 0, + droppedUnknownListing: 0, + droppedAfterLastSession: 0, + droppedMissingCalendarSession: 0, + duplicateEvents: 0, + duplicateBars: 0, + nonPositiveCloseReturns: 0, +}; + +const ZERO_EVENT_STUDY_DIAGNOSTICS: EventStudyDiagnostics = { + eventsIn: 0, + eventsUsed: 0, + droppedUnknownEntity: 0, + droppedWindowOutOfRange: 0, + droppedMissingReturns: 0, + duplicateEventsCollapsed: 0, +}; + +const EVENT_PANEL_ERROR_MESSAGES: Readonly> = { + invalid_input: 'Invalid event panel input.', + invalid_date: 'Invalid event panel date.', + invalid_bar: 'Market bar data failed event panel validation.', + invalid_event: 'Event table data failed event panel validation.', + invalid_option: 'Invalid event panel option.', + duplicate_bar: 'Conflicting duplicate daily bars detected.', +}; + +const SIGNAL_STUDY_ERROR_MESSAGES: Readonly> = { + invalid_request: 'Invalid event study request.', + empty_panel: 'Event study session grid is empty.', + invalid_date: 'Invalid event study date.', + unsorted_dates: 'Event study session dates are not strictly ascending.', + duplicate_date: 'Duplicate date detected in event study session grid.', + invalid_panel: 'Event study panel failed validation.', + invalid_option: 'Invalid event study option.', + dsr_read_failed: 'Trial was recorded, but cluster deflated Sharpe evaluation failed.', +}; + +const TRIAL_LEDGER_ERROR_MESSAGES: Readonly>> = { + VAULT_FENCE_VIOLATION: 'Sample window violates the Vault holdout cutoff.', + INVALID_PRINCIPAL: 'Invalid trial ledger principal.', + INVALID_UUID: 'Invalid trial ledger UUID.', + INVALID_SAMPLE_WINDOW: 'Invalid trial ledger sample window.', + INVALID_DATE: 'Invalid trial ledger date.', + SERIES_TOO_SHORT: 'Observation series is too short for trial ledger recording.', + ZERO_VARIANCE_SERIES: 'Observation series has zero variance.', + TRIAL_NOT_FOUND: 'Recorded trial could not be found in trial ledger.', +}; + +function sortAndDedupeListingIds(ids: readonly number[]): number[] { + return [...new Set(ids)].sort((a, b) => a - b); +} + +function sortAndDedupeStrings(items: readonly T[]): T[] { + return [...new Set(items)].sort() as T[]; +} + +function makeEmptyStudySummary( + preDays: number, + postDays: number, + hasBenchmark: boolean +): EventStudySummary { + return { + preDays, + postDays, + hasBenchmark, + offsets: [], + clustered: null, + recency: null, + diagnostics: ZERO_EVENT_STUDY_DIAGNOSTICS, + }; +} + +function projectStudySummary(study: EventStudyResult): EventStudySummary { + if (study.status === 'insufficient_data') { + return { + preDays: study.preDays, + postDays: study.postDays, + hasBenchmark: study.hasBenchmark, + offsets: [], + clustered: null, + recency: null, + diagnostics: study.diagnostics, + }; + } + + return { + preDays: study.preDays, + postDays: study.postDays, + hasBenchmark: study.hasBenchmark, + offsets: study.offsets.map(o => ({ + offset: o.offset, + n: o.n, + aar: o.aar, + caar: o.caar, + caarFromZero: o.caarFromZero, + })), + clustered: { + nDates: study.clustered.nDates, + carMean: study.clustered.carMean, + neweyWest: study.clustered.neweyWest, + }, + recency: study.recency, + diagnostics: study.diagnostics, + }; +} + +function filterEligibleBars( + bars: readonly BarRecord[], + listingIdSet: ReadonlySet, + fromMs: number, + toMs: number, + asOfMs: number, + vaultCutoffTs: number, + vaultCutoffDate: string +): BarRecord[] { + const eligible: BarRecord[] = []; + for (let i = 0; i < bars.length; i += 1) { + const row = bars[i]; + if (typeof row !== 'object' || row === null) { + eligible.push(row as unknown as BarRecord); + continue; + } + if (isValidEpochMs(row.ts)) { + if ( + row.ts < fromMs || + row.ts > toMs || + row.ts > asOfMs || + row.ts >= vaultCutoffTs || + utcDateOf(row.ts) >= vaultCutoffDate + ) { + continue; + } + } + if (isValidEpochMs(row.knownAt)) { + if ( + row.knownAt > asOfMs || + row.knownAt >= vaultCutoffTs || + utcDateOf(row.knownAt) >= vaultCutoffDate + ) { + continue; + } + } + if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) { + continue; + } + eligible.push(row); + } + return eligible; +} + +function filterEligibleEventsTable(params: { + readonly table: Table; + readonly listingIdSet: ReadonlySet; + readonly kindSet: ReadonlySet; + readonly subtypeSet: ReadonlySet | null; + readonly fromMs: number; + readonly toMs: number; + readonly asOfMs: number; + readonly vaultCutoffTs: number; + readonly vaultCutoffDate: string; +}): { readonly table: Table; readonly prePanelVaultExcludedEvents: number } { + const { + table, + listingIdSet, + kindSet, + subtypeSet, + fromMs, + toMs, + asOfMs, + vaultCutoffTs, + vaultCutoffDate, + } = params; + + if ( + typeof table !== 'object' || + table === null || + !Array.isArray(table.columns) || + !Array.isArray(table.rows) + ) { + return { table, prePanelVaultExcludedEvents: 0 }; + } + + const eligibleRows: TableRow[] = []; + let prePanelVaultExcludedEvents = 0; + + for (let i = 0; i < table.rows.length; i += 1) { + const row = table.rows[i]; + if (typeof row !== 'object' || row === null || Array.isArray(row)) { + eligibleRows.push(row as TableRow); + continue; + } + + const listingId = row.listing_id; + if (typeof listingId === 'number' && !listingIdSet.has(listingId)) { + continue; + } + + // Drop valid but unrequested kinds/subtypes without counting them as Vault exclusions. + // Malformed kind/subtype values fall through so eventsTableToEventRows rejects them. + const kind = row.kind; + if (typeof kind === 'string' && EVENT_KIND_SET.has(kind) && !kindSet.has(kind)) { + continue; + } + if (subtypeSet !== null) { + const subtype = row.subtype; + if (subtype === null || (typeof subtype === 'string' && !subtypeSet.has(subtype))) { + continue; + } + } + + const knownAt = row.known_at; + const knownAtInVault = + isValidEpochMs(knownAt) && + (knownAt >= vaultCutoffTs || utcDateOf(knownAt) >= vaultCutoffDate); + + const ts = row.ts; + const tsInVault = + isValidEpochMs(ts) && + (ts >= vaultCutoffTs || utcDateOf(ts) >= vaultCutoffDate); + + if (knownAtInVault || tsInVault) { + prePanelVaultExcludedEvents += 1; + continue; + } + + if (isValidEpochMs(knownAt) && knownAt > asOfMs) { + continue; + } + + if (isValidEpochMs(ts)) { + if (ts < fromMs || ts > toMs) { + continue; + } + } else { + throw new EventPanelError( + 'invalid_event', + `Invalid ts in events table row[${i}]: ${String(ts)}.` + ); + } + + eligibleRows.push(row); + } + + return { + table: { + columns: table.columns, + rows: eligibleRows, + }, + prePanelVaultExcludedEvents, + }; +} + +function buildCanonicalEventStudyExpression(params: { + readonly input: EventStudyToolInput; + readonly canonicalKinds: readonly EventKind[]; + readonly canonicalSubtypes: readonly string[] | undefined; + readonly listingIds: readonly number[]; + readonly universeSnapshotDate: string | null; + readonly effectiveFrom: string; + readonly effectiveTo: string; + readonly effectiveAsOf: string; +}): SignalStudyExpression { + const { + input, + canonicalKinds, + canonicalSubtypes, + listingIds, + universeSnapshotDate, + effectiveFrom, + effectiveTo, + effectiveAsOf, + } = params; + + return { + expression: `mcp:event_study:v1:${canonicalKinds.join(',')}`, + params: { + version: 1, + kinds: canonicalKinds, + subtypes: canonicalSubtypes ?? null, + preDays: input.preDays, + postDays: input.postDays, + benchmark: input.benchmark, + adjustment: input.adjustment, + effectiveFrom, + effectiveTo, + effectiveAsOf, + }, + universe: + input.universe !== undefined + ? { + kind: 'universe', + ref: input.universe, + snapshotDate: universeSnapshotDate, + listingIds, + } + : { + kind: 'listingIds', + listingIds, + }, + horizon: `${input.postDays}d`, + }; +} + +function formatMappedEventStudyError(err: unknown): McpToolCallResult { + const storeMapped = formatMappedStoreError(err); + if (storeMapped !== null) { + return storeMapped; + } + + if (err instanceof ExchangeCalendarResolverError) { + return { + content: [{ type: 'text', text: 'Error: Exchange calendar resolution failed.' }], + isError: true, + }; + } + + if (err instanceof EventPanelError) { + const detail = Object.prototype.hasOwnProperty.call(EVENT_PANEL_ERROR_MESSAGES, err.code) + ? EVENT_PANEL_ERROR_MESSAGES[err.code] + : 'Event panel construction failed.'; + return { + content: [{ type: 'text', text: `EventPanelError: ${detail}` }], + isError: true, + }; + } + + if (err instanceof SignalStudyError) { + const detail = Object.prototype.hasOwnProperty.call(SIGNAL_STUDY_ERROR_MESSAGES, err.code) + ? SIGNAL_STUDY_ERROR_MESSAGES[err.code] + : 'Event study execution failed.'; + return { + content: [{ type: 'text', text: `SignalStudyError: ${detail}` }], + isError: true, + }; + } + + if (err instanceof TrialLedgerError) { + const detail = + Object.prototype.hasOwnProperty.call(TRIAL_LEDGER_ERROR_MESSAGES, err.code) && + TRIAL_LEDGER_ERROR_MESSAGES[err.code] !== undefined + ? TRIAL_LEDGER_ERROR_MESSAGES[err.code] + : 'Trial ledger operation failed.'; + return { + content: [{ type: 'text', text: `TrialLedgerError: ${detail}` }], + isError: true, + }; + } + + return { + content: [{ type: 'text', text: 'Error: Tool execution failed.' }], + isError: true, + }; +} + +function validateFactoryOptions(options: EventStudyToolOptions): number { + if (typeof options !== 'object' || options === null) { + throw new MarketDataStoreValidationError( + 'Invalid `options`: expected an EventStudyToolOptions object.', + 'options' + ); + } + + if ( + typeof options.store !== 'object' || + options.store === null || + typeof options.store.bars !== 'function' || + typeof options.store.events !== 'function' || + typeof options.store.universe !== 'function' + ) { + throw new MarketDataStoreValidationError( + 'Invalid `store`: expected a MarketDataStore implementing `bars`, `events`, and `universe`.', + 'store' + ); + } + + if ( + typeof options.ledger !== 'object' || + options.ledger === null || + typeof options.ledger.query !== 'function' + ) { + throw new SignalStudyError( + 'invalid_request', + 'Invalid `ledger`: expected a TrialLedgerExecutor implementing `query`.' + ); + } + + if (typeof options.resolveExchangeCalendars !== 'function') { + throw new EventPanelError( + 'invalid_option', + 'Invalid `resolveExchangeCalendars`: expected a function.' + ); + } + + if ( + typeof options.principalId !== 'string' || + (options.principalId !== 'operator' && !AGENT_PRINCIPAL_RE.test(options.principalId)) + ) { + throw new TrialLedgerError( + 'INVALID_PRINCIPAL', + `Invalid \`principalId\`: "${String(options.principalId)}".` + ); + } + + return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs); +} + +/** + * Creates the Vault-fenced `event_study` MCP tool backed by an injected + * {@link MarketDataStore}, {@link TrialLedgerExecutor}, and exchange-calendar + * resolver. + * + * Enforces `scope: 'vault_fenced'`, fences bounds before any dependency call, + * resolves named universes strictly prior to the study start date, filters + * bars and events defensively against the effective window and Vault cutoff, + * anchors events using actual exchange close calendars, runs `runEventStudy` + * under the injected research principal, and returns a bounded summary payload. + */ +export function createEventStudyTool(options: EventStudyToolOptions): McpToolEntry { + const vaultCutoffTs = validateFactoryOptions(options); + const { store, ledger, principalId, resolveExchangeCalendars } = options; + + return defineMcpTool({ + name: 'event_study', + description: + 'Run a Vault-fenced event study over daily bars and point-in-time events and record eligible trials to trial_ledger.', + inputSchema: eventStudyInputSchema, + async handler(input: EventStudyToolInput): Promise { + try { + const fenced = fenceVaultQueryBounds( + { + from: input.from, + to: input.to, + asOf: input.asOf, + }, + vaultCutoffTs + ); + + const canonicalKinds = sortAndDedupeStrings(input.event.kinds); + const canonicalSubtypes = + input.event.subtypes !== undefined + ? sortAndDedupeStrings(input.event.subtypes) + : undefined; + + let listingIds: number[]; + let universeSnapshotDate: string | null = null; + + if (input.universe !== undefined) { + universeSnapshotDate = resolvePreStartUniverseDate( + fenced.fromMs, + fenced.asOfMs, + fenced.asOfSubMs + ); + const resolved = await store.universe({ + ref: input.universe, + date: universeSnapshotDate, + }); + listingIds = sortAndDedupeListingIds(resolved); + } else { + listingIds = sortAndDedupeListingIds(input.listingIds ?? []); + } + + const hasBenchmark = input.benchmark === 'equal_weight'; + const basePayloadFields = { + scope: 'vault_fenced' as const, + vaultCutoffTs, + vaultCutoffDate: fenced.vaultCutoffDate, + event: { + kinds: canonicalKinds, + subtypes: canonicalSubtypes ?? null, + }, + preDays: input.preDays, + postDays: input.postDays, + benchmark: input.benchmark, + adjustment: input.adjustment, + universeMarket: input.universeMarket, + horizonBucket: input.horizonBucket, + fromMs: fenced.fromMs, + toMs: fenced.toMs, + asOfMs: fenced.asOfMs, + effectiveFrom: fenced.canonicalFrom, + effectiveTo: fenced.canonicalTo, + effectiveAsOf: fenced.canonicalAsOf, + clampedTo: fenced.clampedTo, + clampedAsOf: fenced.clampedAsOf, + listingCount: listingIds.length, + }; + + if (listingIds.length === 0) { + const payload: EventStudyResultPayload = { + ...basePayloadFields, + status: 'insufficient_data', + reason: 'below_min_events', + eventCount: 0, + vaultExcludedEvents: 0, + panelDiagnostics: ZERO_EVENT_PANEL_DIAGNOSTICS, + study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), + }; + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } + + const rawBars = await collectBars( + store.bars({ + listingIds, + timeframe: '1d', + from: fenced.canonicalFrom, + to: fenced.canonicalTo, + adjustment: input.adjustment, + asOf: fenced.canonicalAsOf, + scope: 'vault_fenced', + }) + ); + + const rawEventsTable = await store.events({ + kinds: canonicalKinds, + listingIds, + from: fenced.canonicalFrom, + to: fenced.canonicalTo, + asOf: fenced.canonicalAsOf, + }); + + const listingIdSet = new Set(listingIds); + const kindSet = new Set(canonicalKinds); + const subtypeSet = canonicalSubtypes !== undefined ? new Set(canonicalSubtypes) : null; + + const eligibleBars = filterEligibleBars( + rawBars, + listingIdSet, + fenced.fromMs, + fenced.toMs, + fenced.asOfMs, + vaultCutoffTs, + fenced.vaultCutoffDate + ); + + const { table: eligibleEventsTable, prePanelVaultExcludedEvents } = + filterEligibleEventsTable({ + table: rawEventsTable, + listingIdSet, + kindSet, + subtypeSet, + fromMs: fenced.fromMs, + toMs: fenced.toMs, + asOfMs: fenced.asOfMs, + vaultCutoffTs, + vaultCutoffDate: fenced.vaultCutoffDate, + }); + + const events = eventsTableToEventRows(eligibleEventsTable, { + kinds: canonicalKinds, + ...(canonicalSubtypes !== undefined ? { subtypes: canonicalSubtypes } : {}), + }); + + const fromDate = utcDateOf(fenced.fromMs); + const toDate = utcDateOf(fenced.toMs); + const asOfDate = utcDateOf(fenced.asOfMs); + const vaultCutoffDayStartMs = Math.floor(vaultCutoffTs / MS_PER_DAY) * MS_PER_DAY; + const lastPreVaultDate = utcDateOf(vaultCutoffDayStartMs - MS_PER_DAY); + const calendarToDate = [toDate, asOfDate, lastPreVaultDate].reduce((a, b) => + a < b ? a : b + ); + + if (fromDate > calendarToDate) { + const panelDiagnostics: EventPanelDiagnostics = { + ...ZERO_EVENT_PANEL_DIAGNOSTICS, + vaultExcludedEvents: prePanelVaultExcludedEvents, + droppedUnknownListing: events.length, + }; + const payload: EventStudyResultPayload = { + ...basePayloadFields, + status: 'insufficient_data', + reason: 'below_min_events', + eventCount: 0, + vaultExcludedEvents: prePanelVaultExcludedEvents, + panelDiagnostics, + study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), + }; + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } + + let exchangeCalendars: EventStudyExchangeCalendars; + try { + exchangeCalendars = await resolveExchangeCalendars({ + listingIds, + fromDate, + toDate: calendarToDate, + }); + } catch (err: unknown) { + if (err instanceof EventPanelError) { + throw err; + } + throw new ExchangeCalendarResolverError(err); + } + + const built = buildEventStudyInput({ + bars: eligibleBars, + events, + vaultCutoffDate: fenced.vaultCutoffDate, + benchmark: input.benchmark, + exchangeCalendars, + }); + + const combinedPanelDiagnostics: EventPanelDiagnostics = { + ...built.diagnostics, + vaultExcludedEvents: prePanelVaultExcludedEvents + built.diagnostics.vaultExcludedEvents, + }; + + if (built.input.sessionDates.length === 0) { + const payload: EventStudyResultPayload = { + ...basePayloadFields, + status: 'insufficient_data', + reason: 'below_min_events', + eventCount: 0, + vaultExcludedEvents: combinedPanelDiagnostics.vaultExcludedEvents, + panelDiagnostics: combinedPanelDiagnostics, + study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), + }; + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } + + const expression = buildCanonicalEventStudyExpression({ + input, + canonicalKinds, + canonicalSubtypes, + listingIds, + universeSnapshotDate, + effectiveFrom: fenced.canonicalFrom, + effectiveTo: fenced.canonicalTo, + effectiveAsOf: fenced.canonicalAsOf, + }); + + const studyResult = await runEventStudy(ledger, { + principalId, + ...(input.campaignId !== undefined ? { campaignId: input.campaignId } : {}), + ...(input.hypothesisId !== undefined ? { hypothesisId: input.hypothesisId } : {}), + universeMarket: input.universeMarket, + horizonBucket: input.horizonBucket, + expression, + input: built.input, + vaultCutoffDate: fenced.vaultCutoffDate, + options: { + preDays: input.preDays, + postDays: input.postDays, + }, + }); + + const totalVaultExcludedEvents = + combinedPanelDiagnostics.vaultExcludedEvents + studyResult.vaultExcludedEvents; + const studySummary = projectStudySummary(studyResult.study); + + const payload: EventStudyResultPayload = + studyResult.status === 'ok' + ? { + ...basePayloadFields, + status: 'ok', + eventCount: built.input.events.length, + vaultExcludedEvents: totalVaultExcludedEvents, + panelDiagnostics: combinedPanelDiagnostics, + study: studySummary, + trial: studyResult.trial, + deflatedSharpe: studyResult.deflatedSharpe, + } + : { + ...basePayloadFields, + status: 'insufficient_data', + reason: studyResult.reason, + eventCount: built.input.events.length, + vaultExcludedEvents: totalVaultExcludedEvents, + panelDiagnostics: combinedPanelDiagnostics, + study: studySummary, + }; + + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + } catch (err: unknown) { + return formatMappedEventStudyError(err); + } + }, + }); +} diff --git a/libs/research/test/mcp-event-study-qa.test.ts b/libs/research/test/mcp-event-study-qa.test.ts new file mode 100644 index 00000000..7ebe7ab6 --- /dev/null +++ b/libs/research/test/mcp-event-study-qa.test.ts @@ -0,0 +1,658 @@ +import { describe, expect, test } from 'bun:test'; +import type { EventStudyExchangeCalendars } from '../src/event-panel'; +import type { + BarBatch, + BarRecord, + EventKind, + MarketDataStore, + Table, + TableRow, +} from '../src/market-data-store'; +import { + type BarsQuery, + EVENTS_COLUMNS, + type EventsQuery, + MarketDataStoreNotImplementedError, + type UniverseQuery, +} from '../src/market-data-store-duckdb'; +import { + type EventStudyExchangeCalendarQuery, + type EventStudyResultPayload, + createEventStudyTool, + createMcpServer, +} from '../src/mcp/index'; +import type { TrialLedgerExecutor } from '../src/trial-ledger'; + +// QA fixture: deterministic synthetic equity bars & events with explicit +// half-day closes, intraday Vault cutoffs, exact boundary timestamps, and +// malformed rows. Models gross daily close-to-close returns, raw adjustment, +// no fills or transaction costs. +const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; + +function makeBusinessDates(startDate: string, count: number): string[] { + const out: string[] = []; + const current = new Date(`${startDate}T00:00:00.000Z`); + while (out.length < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out.push(current.toISOString().slice(0, 10)); + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +function utcMs(date: string, hour: number, minute = 0, second = 0, ms = 0): number { + const [y, m, d] = date.split('-').map(Number); + return Date.UTC(y!, m! - 1, d!, hour, minute, second, ms); +} + +function createFakeLedger(): { + executor: TrialLedgerExecutor; + insertCalls: number; + rows: Array<{ expression_hash: string; daily_series: number[] }>; +} { + const rows: Array<{ expression_hash: string; daily_series: number[] }> = []; + let nextId = 1; + const state = { + rows, + insertCalls: 0, + executor: null as unknown as TrialLedgerExecutor, + }; + + state.executor = { + async query>(text: string, params?: readonly unknown[]) { + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + state.insertCalls += 1; + const p = params ?? []; + const id = nextId++; + const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); + rows.push({ + expression_hash: p[6] as string, + daily_series: dailySeries, + }); + return { + rows: [ + { + trial_id: String(id), + created_at: new Date(Date.UTC(2024, 5, 1, 12, 0, id)), + } as unknown as Row, + ], + rowCount: 1, + }; + } + if (trimmed.startsWith('SELECT')) { + const storedRows = rows.map((r, idx) => ({ + trial_id: String(idx + 1), + created_at: new Date(Date.UTC(2024, 5, 1, 12, 0, idx + 1)), + principal_id: AGENT_PRINCIPAL, + campaign_id: null, + stage: 'event_study', + universe_market: 'US_EQ', + horizon_bucket: 'swing_1_10d', + hypothesis_id: null, + expression_hash: r.expression_hash, + sample_start: '2023-01-02', + sample_end: '2023-02-01', + n_obs: r.daily_series.length, + sharpe_unann: 0.5, + skewness: 0, + kurtosis: 3, + daily_series: r.daily_series, + })); + return { rows: storedRows as unknown as Row[], rowCount: storedRows.length }; + } + return { rows: [], rowCount: 0 }; + }, + }; + + return state; +} + +function createPassThroughStore(params: { + bars: readonly BarRecord[]; + eventsTable: Table; +}): MarketDataStore { + return { + bars(_q: BarsQuery): AsyncIterable { + return { + async *[Symbol.asyncIterator]() { + yield { rows: [...params.bars] }; + }, + }; + }, + async events(_q: EventsQuery): Promise
{ + return params.eventsTable; + }, + async universe(_q: UniverseQuery): Promise { + return []; + }, + crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; +} + +async function invoke( + server: ReturnType, + args: Record +): Promise<{ + isError?: boolean; + text: string; + payload?: EventStudyResultPayload; +}> { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'event_study', arguments: args }, + }) + ); + const rpc = JSON.parse(raw!) as { + result: { content: Array<{ type: string; text: string }>; isError?: boolean }; + }; + const text = rpc.result.content[0]!.text; + return { + isError: rpc.result.isError, + text, + payload: rpc.result.isError ? undefined : (JSON.parse(text) as EventStudyResultPayload), + }; +} + +describe('MCP event_study QA edge cases', () => { + test('event released after a half-day close anchors to the next trading session, not the half-day', async () => { + const dates = makeBusinessDates('2023-05-01', 25); + const vaultCutoffDate = dates[24]!; + const vaultCutoffTs = utcMs(vaultCutoffDate, 0); + const listingIds = [101, 102, 103, 104, 105, 106]; + + // Make day index 8 a half-day (closes at 18:00 UTC = 13:00 ET instead of 21:00 UTC). + // Place 6 events across days 8 and 14, released at 19:00 UTC (after 18:00 UTC half-day close, + // before 21:00 UTC bar stamp). For half-day (index 8), events must anchor to index 9! + // Put a +10% jump on index 9 and +20% jump on index 15 (next day after 14, also half-day), + // and 0% return on index 8 and 14 so AAR at offset 0 proves next-session anchoring. + const halfDayIndices = new Set([8, 14]); + const jumpDayReturns = new Map([ + [9, 0.1], + [15, 0.2], + ]); + + const bars: BarRecord[] = []; + for (const id of listingIds) { + let price = 100; + for (let t = 0; t < 24; t += 1) { + const ret = jumpDayReturns.get(t) ?? 0; + price = Number((price * (1 + ret)).toFixed(6)); + const ts = utcMs(dates[t]!, 21); // bars_1d always stamped 16:00 ET (21:00 UTC) + bars.push({ + listingId: id, + ts, + open: price, + high: price, + low: price, + close: price, + volume: 10_000, + knownAt: ts, + }); + } + } + + const eventRows: TableRow[] = []; + for (let i = 0; i < 3; i += 1) { + // Released at 19:00 UTC on half-day index 8 -> anchors to index 9 (+10%) + eventRows.push({ + listing_id: listingIds[i]!, + ts: utcMs(dates[8]!, 19), + known_at: utcMs(dates[8]!, 19), + known_at_source: 'exact', + kind: 'filing' as EventKind, + subtype: '8-K', + payload_json: '{}', + }); + } + for (let i = 3; i < 6; i += 1) { + // Released at 19:00 UTC on half-day index 14 -> anchors to index 15 (+20%) + eventRows.push({ + listing_id: listingIds[i]!, + ts: utcMs(dates[14]!, 19), + known_at: utcMs(dates[14]!, 19), + known_at_source: 'exact', + kind: 'filing' as EventKind, + subtype: '8-K', + payload_json: '{}', + }); + } + + const store = createPassThroughStore({ + bars, + eventsTable: { columns: [...EVENTS_COLUMNS], rows: eventRows }, + }); + const ledger = createFakeLedger(); + + const resolveExchangeCalendars = async ( + q: EventStudyExchangeCalendarQuery + ): Promise => { + const sessions = dates + .filter(d => d >= q.fromDate && d <= q.toDate) + .map((date, _idx) => { + const globalIdx = dates.indexOf(date); + const closeHour = halfDayIndices.has(globalIdx) ? 18 : 21; + return { date, closeTs: utcMs(date, closeHour) }; + }); + const listingCalendarId = new Map(); + for (const id of q.listingIds) { + listingCalendarId.set(id, 'XNYS'); + } + return { + calendars: new Map([['XNYS', sessions]]), + listingCalendarId, + }; + }; + + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars, + }), + ], + }); + + const res = await invoke(server, { + listingIds, + from: dates[0]!, + to: dates[23]!, + event: { kinds: ['filing'] }, + preDays: 1, + postDays: 1, + benchmark: 'none', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + + expect(res.isError).toBeUndefined(); + expect(res.payload?.status).toBe('ok'); + if (res.payload?.status !== 'ok') { + throw new Error('Expected ok'); + } + + // Offset -1 is the half-day itself (0% return); Offset 0 is the next session (mean of +10% and +20% = +15%). + const offsetMinus1 = res.payload.study.offsets.find(o => o.offset === -1)!; + const offset0 = res.payload.study.offsets.find(o => o.offset === 0)!; + expect(offsetMinus1.aar).toBeCloseTo(0, 8); + expect(offset0.aar).toBeCloseTo(0.15, 8); + }); + + test('intraday Vault cutoff excludes rows on the cutoff UTC day and handles start-on-cutoff-day safely', async () => { + const dates = makeBusinessDates('2023-06-01', 25); + const cutoffDate = dates[20]!; + // Intraday Vault cutoff at 12:00 UTC on cutoffDate + const vaultCutoffTs = utcMs(cutoffDate, 12); + const listingIds = [201, 202, 203, 204, 205, 206]; + + const bars: BarRecord[] = []; + for (const id of listingIds) { + let price = 50; + for (let t = 0; t < 22; t += 1) { + price = Number((price * (1 + (t % 3 === 0 ? 0.02 : -0.005))).toFixed(6)); + const ts = t === 20 ? utcMs(dates[t]!, 10) : utcMs(dates[t]!, 21); // Bar on cutoff day at 10:00 UTC (< cutoffTs!) + bars.push({ + listingId: id, + ts, + open: price, + high: price, + low: price, + close: price, + volume: 5_000, + knownAt: ts, + }); + } + } + + const baseEvents: TableRow[] = [ + // 6 valid pre-cutoff events across 2 dates + ...listingIds.slice(0, 3).map(id => ({ + listing_id: id, + ts: utcMs(dates[6]!, 14), + known_at: utcMs(dates[6]!, 14), + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + })), + ...listingIds.slice(3, 6).map(id => ({ + listing_id: id, + ts: utcMs(dates[12]!, 14), + known_at: utcMs(dates[12]!, 14), + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + })), + ]; + + const intradayCutoffEvents: TableRow[] = [ + // Event on cutoff UTC day BEFORE intraday vaultCutoffTs (10:00 UTC < 12:00 UTC) -> MUST be excluded! + { + listing_id: listingIds[0]!, + ts: utcMs(cutoffDate, 10), + known_at: utcMs(cutoffDate, 10), + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + // Valid ts earlier, but known_at on cutoff UTC day at 09:00 UTC (< 12:00 UTC) -> MUST be excluded! + { + listing_id: listingIds[1]!, + ts: utcMs(dates[10]!, 14), + known_at: utcMs(cutoffDate, 9), + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + // Unrequested valid kind on cutoff day -> MUST NOT inflate vaultExcludedEvents + { + listing_id: listingIds[2]!, + ts: utcMs(cutoffDate, 10), + known_at: utcMs(cutoffDate, 10), + known_at_source: 'exact', + kind: 'ceo_post', + subtype: null, + payload_json: '{}', + }, + ]; + + const calendarCalls: EventStudyExchangeCalendarQuery[] = []; + const resolveExchangeCalendars = async ( + q: EventStudyExchangeCalendarQuery + ): Promise => { + calendarCalls.push(q); + const sessions = dates + .filter(d => d >= q.fromDate && d <= q.toDate) + .map(date => ({ date, closeTs: utcMs(date, 21) })); + const listingCalendarId = new Map(); + for (const id of q.listingIds) { + listingCalendarId.set(id, 'XNYS'); + } + return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; + }; + + const store = createPassThroughStore({ + bars, + eventsTable: { + columns: [...EVENTS_COLUMNS], + rows: [...baseEvents, ...intradayCutoffEvents], + }, + }); + const ledger = createFakeLedger(); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars, + }), + ], + }); + + const res = await invoke(server, { + listingIds, + from: dates[0]!, + to: dates[21]!, + event: { kinds: ['filing'] }, + preDays: 2, + postDays: 2, + benchmark: 'none', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + + expect(res.payload?.status).toBe('ok'); + expect(res.payload?.vaultExcludedEvents).toBe(2); + expect(res.payload?.eventCount).toBe(6); + expect(calendarCalls[0]!.toDate < cutoffDate).toBe(true); + + // Request starting on the intraday cutoff day before vaultCutoffTs: + // returns insufficient_data cleanly without calling calendar resolver with inverted dates. + calendarCalls.length = 0; + const ledger2 = createFakeLedger(); + const server2 = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store, + ledger: ledger2.executor, + vaultContext: { vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars, + }), + ], + }); + + const startOnCutoffRes = await invoke(server2, { + listingIds, + from: `${cutoffDate}T01:00:00.000Z`, + to: `${cutoffDate}T11:00:00.000Z`, + event: { kinds: ['filing'] }, + preDays: 1, + postDays: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + + expect(startOnCutoffRes.isError).toBeUndefined(); + expect(startOnCutoffRes.payload?.status).toBe('insufficient_data'); + expect(calendarCalls).toHaveLength(0); + expect(ledger2.insertCalls).toBe(0); + }); + + test('exact boundary timestamps (fromMs, toMs, asOfMs) and malformed ts rejection', async () => { + const dates = makeBusinessDates('2023-07-03', 20); + const vaultCutoffDate = dates[19]!; + const vaultCutoffTs = utcMs(vaultCutoffDate, 0); + const listingIds = [301, 302, 303, 304, 305, 306]; + + const bars: BarRecord[] = []; + for (const id of listingIds) { + let price = 30; + for (let t = 0; t < 19; t += 1) { + price = Number((price * (1 + (t % 2 === 0 ? 0.015 : -0.005))).toFixed(6)); + const ts = utcMs(dates[t]!, 21); + bars.push({ + listingId: id, + ts, + open: price, + high: price, + low: price, + close: price, + volume: 1_000, + knownAt: ts, + }); + } + } + + const fromIso = `${dates[2]}T00:00:00.000Z`; + const toIso = `${dates[15]}T23:59:59.999Z`; + const asOfIso = `${dates[14]}T21:00:00.000Z`; + const fromMs = Date.parse(fromIso); + const toMs = Date.parse(toIso); + const asOfMs = Date.parse(asOfIso); + + const rows: TableRow[] = [ + // Exact fromMs -> included + { + listing_id: listingIds[0]!, + ts: fromMs, + known_at: fromMs, + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + // fromMs - 1 -> excluded + { + listing_id: listingIds[1]!, + ts: fromMs - 1, + known_at: fromMs - 1, + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + // Exact asOfMs -> included + { + listing_id: listingIds[2]!, + ts: utcMs(dates[10]!, 14), + known_at: asOfMs, + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + // asOfMs + 1 -> excluded + { + listing_id: listingIds[3]!, + ts: utcMs(dates[10]!, 14), + known_at: asOfMs + 1, + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + // toMs + 1 -> excluded + { + listing_id: listingIds[4]!, + ts: toMs + 1, + known_at: asOfMs, + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + ]; + + const resolveExchangeCalendars = async ( + q: EventStudyExchangeCalendarQuery + ): Promise => { + const sessions = dates + .filter(d => d >= q.fromDate && d <= q.toDate) + .map(date => ({ date, closeTs: utcMs(date, 21) })); + const listingCalendarId = new Map(); + for (const id of q.listingIds) { + listingCalendarId.set(id, 'XNYS'); + } + return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; + }; + + const store = createPassThroughStore({ + bars, + eventsTable: { columns: [...EVENTS_COLUMNS], rows }, + }); + const ledger = createFakeLedger(); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars, + }), + ], + }); + + const res = await invoke(server, { + listingIds, + from: fromIso, + to: toIso, + asOf: asOfIso, + event: { kinds: ['filing'] }, + preDays: 1, + postDays: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + + // Only 2 events survived the exact boundaries (fromMs and asOfMs) -> insufficient_data (< 5) + expect(res.payload?.status).toBe('insufficient_data'); + expect(res.payload?.eventCount).toBe(2); + expect(ledger.insertCalls).toBe(0); + + // Malformed `ts` on an otherwise eligible event row must fail with sanitized EventPanelError + const malformedStore = createPassThroughStore({ + bars, + eventsTable: { + columns: [...EVENTS_COLUMNS], + rows: [ + { + listing_id: listingIds[0]!, + ts: 'not-a-timestamp' as unknown as number, + known_at: fromMs, + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + ], + }, + }); + const malformedLedger = createFakeLedger(); + const malformedServer = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: malformedStore, + ledger: malformedLedger.executor, + vaultContext: { vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars, + }), + ], + }); + + const badRes = await invoke(malformedServer, { + listingIds, + from: fromIso, + to: toIso, + asOf: asOfIso, + event: { kinds: ['filing'] }, + preDays: 1, + postDays: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + + expect(badRes.isError).toBe(true); + expect(badRes.text).toBe('EventPanelError: Event table data failed event panel validation.'); + expect(malformedLedger.insertCalls).toBe(0); + }); +}); diff --git a/libs/research/test/mcp-event-study.test.ts b/libs/research/test/mcp-event-study.test.ts new file mode 100644 index 00000000..5782c0ff --- /dev/null +++ b/libs/research/test/mcp-event-study.test.ts @@ -0,0 +1,1419 @@ +import { describe, expect, test } from 'bun:test'; +import { + EventPanelError, + type EventStudyExchangeCalendars, + buildEventStudyInput, + eventsTableToEventRows, +} from '../src/event-panel'; +import { + type BarBatch, + type BarRecord, + type EventKind, + type MarketDataStore, + MarketDataStoreValidationError, + type Table, + type TableRow, + VaultHoldoutFenceError, + VaultScopeNotAuthorizedError, +} from '../src/market-data-store'; +import { + AdjFactorsSnapshotError, + type BarsQuery, + EVENTS_COLUMNS, + type EventsQuery, + MarketDataStoreNotImplementedError, + type UniverseQuery, +} from '../src/market-data-store-duckdb'; +import { + EVENT_STUDY_MAX_LISTING_IDS, + EVENT_STUDY_MAX_POST_DAYS, + EVENT_STUDY_MAX_PRE_DAYS, + type EventStudyExchangeCalendarQuery, + type EventStudyResultPayload, + createEventStudyTool, + createMcpServer, +} from '../src/mcp/index'; +import { SignalStudyError, runEventStudy } from '../src/signal-study'; +import { TrialLedgerError, type TrialLedgerExecutor } from '../src/trial-ledger'; + +// Synthetic fixture: seeded (20261201) 8 listings, 60 pre-cutoff + 8 post-cutoff +// business sessions from 2022-11-01, daily close-to-close returns, raw adjustment, +// no fills or transaction costs, XNYS 21:00 UTC close calendar. +const SEED = 20261201; +const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const CAMPAIGN_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; +const HYPOTHESIS_UUID = '12345678-1234-4123-8123-123456789abc'; + +function createSeededRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; + }; +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out: string[] = new Array(count); + const current = new Date(`${startDate}T00:00:00.000Z`); + let written = 0; + while (written < count) { + const day = current.getUTCDay(); + if (day !== 0 && day !== 6) { + out[written] = current.toISOString().slice(0, 10); + written += 1; + } + current.setUTCDate(current.getUTCDate() + 1); + } + return out; +} + +function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0): number { + const [y, m, d] = date.split('-').map(Number); + return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, 0); +} + +function parseBound(raw: string, endOfDay: boolean): number { + if (raw.length === 10) { + return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); + } + return Date.parse(raw); +} + +interface StoredTrialRow { + readonly trial_id: string; + readonly created_at: Date; + readonly principal_id: string; + readonly campaign_id: string | null; + readonly stage: string; + readonly universe_market: string; + readonly horizon_bucket: string; + readonly hypothesis_id: string | null; + readonly expression_hash: string; + readonly sample_start: string; + readonly sample_end: string; + readonly n_obs: number; + readonly sharpe_unann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly daily_series: readonly number[]; +} + +function createFakeTrialLedger(options?: { + insertError?: Error; + dsrReadError?: Error; +}): { + executor: TrialLedgerExecutor; + rows: StoredTrialRow[]; + insertCalls: number; + selectCalls: number; +} { + const rows: StoredTrialRow[] = []; + let nextTrialId = 1; + const state = { + rows, + insertCalls: 0, + selectCalls: 0, + executor: null as unknown as TrialLedgerExecutor, + }; + + state.executor = { + async query>(text: string, params?: readonly unknown[]) { + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + state.insertCalls += 1; + if (options?.insertError !== undefined) { + throw options.insertError; + } + const p = params ?? []; + const trialId = nextTrialId++; + const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); + const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); + const stored: StoredTrialRow = { + trial_id: String(trialId), + created_at: createdAt, + principal_id: p[0] as string, + campaign_id: (p[1] as string | null) ?? null, + stage: p[2] as string, + universe_market: p[3] as string, + horizon_bucket: p[4] as string, + hypothesis_id: (p[5] as string | null) ?? null, + expression_hash: p[6] as string, + sample_start: p[7] as string, + sample_end: p[8] as string, + n_obs: p[9] as number, + sharpe_unann: p[10] as number, + skewness: p[11] as number, + kurtosis: p[12] as number, + daily_series: dailySeries, + }; + rows.push(stored); + return { + rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], + rowCount: 1, + }; + } + + if (trimmed.startsWith('SELECT')) { + state.selectCalls += 1; + if (options?.dsrReadError !== undefined) { + throw options.dsrReadError; + } + if (text.includes('WHERE trial_id = $1::bigint')) { + const targetId = String(params?.[0]); + const matched = rows.filter(r => r.trial_id === targetId); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const market = params?.[0] as string; + const bucket = params?.[1] as string; + const matched = rows.filter( + r => r.universe_market === market && r.horizon_bucket === bucket + ); + return { rows: matched as unknown as Row[], rowCount: matched.length }; + } + } + + return { rows: [], rowCount: 0 }; + }, + }; + + return state; +} + +interface SyntheticEventFixture { + readonly listingIds: number[]; + readonly allDates: string[]; + readonly vaultCutoffDate: string; + readonly vaultCutoffTs: number; + readonly bars: BarRecord[]; + readonly eventsTable: Table; +} + +function buildSyntheticEventFixture(options?: { + preCutoffSessions?: number; + postCutoffSessions?: number; + listingCount?: number; + zeroVariance?: boolean; +}): SyntheticEventFixture { + const rand = createSeededRng(SEED); + const listingCount = options?.listingCount ?? 8; + const preCutoffSessions = options?.preCutoffSessions ?? 65; + const postCutoffSessions = options?.postCutoffSessions ?? 8; + const zeroVariance = options?.zeroVariance ?? false; + + const allDates = makeBusinessDates('2022-11-01', preCutoffSessions + postCutoffSessions); + const vaultCutoffDate = allDates[preCutoffSessions]!; + const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); + const listingIds = Array.from({ length: listingCount }, (_, i) => 60_001 + i); + + const bars: BarRecord[] = []; + const eventRows: TableRow[] = []; + const prices = Array.from({ length: listingCount }, (_, i) => 20 + i * 3); + + // Place filings across multiple pre-cutoff dates (well inside window) and some post-cutoff. + const eventDayIndices = [12, 18, 26, 34, 42, 50]; + const eventSet = new Set(); + for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) { + const t = eventDayIndices[eIdx]!; + if (t >= preCutoffSessions) { + continue; + } + // 2 listings per event date => 12 events across 6 distinct dates (spans pre and post 2023-01-01) + for (let k = 0; k < 2; k += 1) { + const l = (eIdx * 2 + k) % listingCount; + eventSet.add(`${t}:${l}`); + const date = allDates[t]!; + const ts = makeUtcMs(date, 14); // 09:00 ET intraday filing -> anchors on same session + const kind: EventKind = eIdx % 2 === 0 ? 'filing' : 'earnings'; + const subtype = kind === 'filing' ? '8-K' : 'Q4'; + eventRows.push({ + listing_id: listingIds[l]!, + ts, + known_at: ts, + known_at_source: 'exact', + kind, + subtype, + payload_json: '{}', + }); + } + } + + for (let t = 0; t < allDates.length; t += 1) { + const date = allDates[t]!; + const closeTs = makeUtcMs(date, 21); // 16:00 ET close + for (let l = 0; l < listingCount; l += 1) { + let close: number; + if (zeroVariance) { + close = 100; + } else { + const isEvent = eventSet.has(`${t}:${l}`); + const base = (rand() - 0.5) * 0.015; + const dailyRet = isEvent ? base + 0.025 + l * 0.002 : base; + prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet)); + close = Number(prices[l]!.toFixed(6)); + } + bars.push({ + listingId: listingIds[l]!, + ts: closeTs, + open: close, + high: close, + low: close, + close, + volume: 25_000, + vwap: close, + knownAt: closeTs, + }); + } + } + + return { + listingIds, + allDates, + vaultCutoffDate, + vaultCutoffTs, + bars, + eventsTable: { + columns: [...EVENTS_COLUMNS], + rows: eventRows, + }, + }; +} + +interface FakeStoreState { + readonly store: MarketDataStore; + readonly barsCalls: BarsQuery[]; + readonly eventsCalls: EventsQuery[]; + readonly universeCalls: UniverseQuery[]; +} + +function createFakeStore( + fixture: SyntheticEventFixture, + options?: { + extraBars?: readonly BarRecord[]; + extraEvents?: readonly TableRow[]; + universeResolver?: (q: UniverseQuery) => number[]; + barsError?: unknown; + eventsError?: unknown; + universeError?: unknown; + } +): FakeStoreState { + const barsCalls: BarsQuery[] = []; + const eventsCalls: EventsQuery[] = []; + const universeCalls: UniverseQuery[] = []; + + const store: MarketDataStore = { + bars(q: BarsQuery): AsyncIterable { + barsCalls.push(q); + const ids = new Set(q.listingIds); + const fromMs = parseBound(q.from, false); + const toMs = parseBound(q.to, true); + const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); + const rows = fixture.bars.filter( + b => + ids.has(b.listingId) && + b.ts >= fromMs && + b.ts <= toMs && + b.ts <= asOfMs && + b.knownAt <= asOfMs + ); + const thrown = options?.barsError; + return { + async *[Symbol.asyncIterator]() { + if (thrown !== undefined) { + throw thrown; + } + yield { rows: [...rows, ...(options?.extraBars ?? [])] }; + }, + }; + }, + async events(q: EventsQuery): Promise
{ + eventsCalls.push(q); + if (options?.eventsError !== undefined) { + throw options.eventsError; + } + const kinds = new Set(q.kinds); + const ids = q.listingIds !== undefined ? new Set(q.listingIds) : null; + const fromMs = parseBound(q.from, false); + const toMs = parseBound(q.to, true); + const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); + const rows = fixture.eventsTable.rows.filter(r => { + if (!kinds.has(r.kind as string)) { + return false; + } + if (ids !== null && !ids.has(r.listing_id as number)) { + return false; + } + const ts = r.ts as number; + const knownAt = r.known_at as number; + return ts >= fromMs && ts <= toMs && knownAt <= asOfMs; + }); + return { + columns: fixture.eventsTable.columns, + rows: [...rows, ...(options?.extraEvents ?? [])], + }; + }, + async universe(q: UniverseQuery): Promise { + universeCalls.push(q); + if (options?.universeError !== undefined) { + throw options.universeError; + } + return options?.universeResolver ? options.universeResolver(q) : fixture.listingIds; + }, + crossSection() { + throw new MarketDataStoreNotImplementedError('crossSection'); + }, + fundamentalsAsOf() { + throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); + }, + shortsAsOf() { + throw new MarketDataStoreNotImplementedError('shortsAsOf'); + }, + macroAsOf() { + throw new MarketDataStoreNotImplementedError('macroAsOf'); + }, + fx() { + throw new MarketDataStoreNotImplementedError('fx'); + }, + }; + + return { store, barsCalls, eventsCalls, universeCalls }; +} + +function createFakeCalendarResolver( + dates: readonly string[], + options?: { + hourUtc?: number; + error?: unknown; + } +): { + calls: EventStudyExchangeCalendarQuery[]; + resolveExchangeCalendars: ( + q: EventStudyExchangeCalendarQuery + ) => Promise; +} { + const calls: EventStudyExchangeCalendarQuery[] = []; + const hourUtc = options?.hourUtc ?? 21; + + return { + calls, + async resolveExchangeCalendars( + q: EventStudyExchangeCalendarQuery + ): Promise { + calls.push(q); + if (options?.error !== undefined) { + throw options.error; + } + const sessions = dates + .filter(d => d >= q.fromDate && d <= q.toDate) + .map(date => ({ date, closeTs: makeUtcMs(date, hourUtc) })); + const listingCalendarId = new Map(); + for (const id of q.listingIds) { + listingCalendarId.set(id, 'XNYS'); + } + return { + calendars: new Map([['XNYS', sessions]]), + listingCalendarId, + }; + }, + }; +} + +async function callEventStudy( + server: ReturnType, + args: Record, + id = 1 +): Promise<{ + rpc: Record; + result?: { content: Array<{ type: string; text: string }>; isError?: boolean }; + payload?: EventStudyResultPayload; +}> { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'tools/call', + params: { name: 'event_study', arguments: args }, + }) + ); + const rpc = JSON.parse(raw!) as Record; + const result = rpc.result as + | { content: Array<{ type: string; text: string }>; isError?: boolean } + | undefined; + let payload: EventStudyResultPayload | undefined; + if (result !== undefined && !result.isError && result.content[0]?.text) { + payload = JSON.parse(result.content[0].text) as EventStudyResultPayload; + } + return { rpc, result, payload }; +} + +describe('MCP event_study tool', () => { + test('tools/list advertises strict JSON schema and exported bounds constants', async () => { + const fixture = buildSyntheticEventFixture(); + const fakeStore = createFakeStore(fixture); + const ledger = createFakeTrialLedger(); + const cal = createFakeCalendarResolver(fixture.allDates); + + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }), + ], + }); + + expect(EVENT_STUDY_MAX_LISTING_IDS).toBe(500); + expect(EVENT_STUDY_MAX_PRE_DAYS).toBe(60); + expect(EVENT_STUDY_MAX_POST_DAYS).toBe(60); + + const raw = await server.handleMessage( + JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }) + ); + const parsed = JSON.parse(raw!) as { + result: { + tools: Array<{ + name: string; + inputSchema: { + type: string; + additionalProperties: boolean; + properties: Record>; + }; + }>; + }; + }; + + expect(parsed.result.tools).toHaveLength(1); + const tool = parsed.result.tools[0]!; + expect(tool.name).toBe('event_study'); + expect(tool.inputSchema.type).toBe('object'); + expect(tool.inputSchema.additionalProperties).toBe(false); + + const props = tool.inputSchema.properties; + expect(props.scope).toBeUndefined(); + expect(props.principalId).toBeUndefined(); + expect(props.vaultCutoffDate).toBeUndefined(); + expect(props.vault_evaluation_only).toBeUndefined(); + + const eventSchema = props.event as { additionalProperties?: boolean }; + expect(eventSchema.additionalProperties).toBe(false); + }); + + test('happy path matches direct runEventStudy, writes one event_study trial, and omits raw series', async () => { + const fixture = buildSyntheticEventFixture(); + const fakeStore = createFakeStore(fixture); + const ledger = createFakeTrialLedger(); + const cal = createFakeCalendarResolver(fixture.allDates); + + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }), + ], + }); + + const from = fixture.allDates[0]!; + const to = fixture.allDates[64]!; + const preDays = 3; + const postDays = 5; + + const { result, payload } = await callEventStudy(server, { + listingIds: fixture.listingIds, + from, + to, + event: { kinds: ['filing', 'earnings'] }, + preDays, + postDays, + benchmark: 'equal_weight', + adjustment: 'raw', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + campaignId: CAMPAIGN_UUID, + hypothesisId: HYPOTHESIS_UUID, + }); + + expect(result?.isError).toBeUndefined(); + expect(payload).toBeDefined(); + expect(payload?.status).toBe('ok'); + if (!payload || payload.status !== 'ok') { + throw new Error('Expected ok payload'); + } + + expect(payload.scope).toBe('vault_fenced'); + expect(payload.vaultCutoffTs).toBe(fixture.vaultCutoffTs); + expect(payload.vaultCutoffDate).toBe(fixture.vaultCutoffDate); + expect(payload.clampedTo).toBe(false); + expect(payload.clampedAsOf).toBe(false); + expect(payload.listingCount).toBe(fixture.listingIds.length); + expect(payload.eventCount).toBe(12); + expect(payload.vaultExcludedEvents).toBe(0); + expect(payload.study.offsets).toHaveLength(preDays + postDays + 1); + expect(payload.study.hasBenchmark).toBe(true); + expect(payload.study.diagnostics.eventsUsed).toBeGreaterThanOrEqual(5); + expect(payload.study.clustered).not.toBeNull(); + expect(payload.study.recency).not.toBeNull(); + + // Verify no raw arrays or typed series are exposed in the JSON payload. + const serialized = result!.content[0]!.text; + expect(serialized).not.toContain('entityReturns'); + expect(serialized).not.toContain('benchmarkReturns'); + expect(serialized).not.toContain('eventCars'); + expect(serialized).not.toContain('meanCars'); + expect(serialized).not.toContain('eventCounts'); + + // Verify trial_ledger write + expect(ledger.insertCalls).toBe(1); + expect(ledger.rows).toHaveLength(1); + const row = ledger.rows[0]!; + expect(row.stage).toBe('event_study'); + expect(row.principal_id).toBe(AGENT_PRINCIPAL); + expect(row.universe_market).toBe('US_EQ'); + expect(row.horizon_bucket).toBe('swing_1_10d'); + expect(row.campaign_id).toBe(CAMPAIGN_UUID); + expect(row.hypothesis_id).toBe(HYPOTHESIS_UUID); + expect(row.sample_end < fixture.vaultCutoffDate).toBe(true); + expect(payload.trial.trialId).toBe(1); + expect(payload.deflatedSharpe.trialId).toBe(1); + expect(payload.deflatedSharpe.clusterSize).toBe(1); + + // Direct parity check against buildEventStudyInput + runEventStudy + const directLedger = createFakeTrialLedger(); + const directEvents = eventsTableToEventRows(fixture.eventsTable, { + kinds: ['earnings', 'filing'], + }); + const directCal = await cal.resolveExchangeCalendars({ + listingIds: fixture.listingIds, + fromDate: from, + toDate: to, + }); + const directBuilt = buildEventStudyInput({ + bars: fixture.bars.filter(b => b.ts < fixture.vaultCutoffTs), + events: directEvents, + vaultCutoffDate: fixture.vaultCutoffDate, + benchmark: 'equal_weight', + exchangeCalendars: directCal, + }); + const directRun = await runEventStudy(directLedger.executor, { + principalId: AGENT_PRINCIPAL, + campaignId: CAMPAIGN_UUID, + hypothesisId: HYPOTHESIS_UUID, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'mcp:event_study:v1:earnings,filing', + params: { + version: 1, + kinds: ['earnings', 'filing'], + subtypes: null, + preDays, + postDays, + benchmark: 'equal_weight', + adjustment: 'raw', + effectiveFrom: payload.effectiveFrom, + effectiveTo: payload.effectiveTo, + effectiveAsOf: payload.effectiveAsOf, + }, + universe: { + kind: 'listingIds', + listingIds: fixture.listingIds, + }, + horizon: `${postDays}d`, + }, + input: directBuilt.input, + vaultCutoffDate: fixture.vaultCutoffDate, + options: { preDays, postDays }, + }); + + expect(directRun.status).toBe('ok'); + if (directRun.status !== 'ok') { + throw new Error('Expected direct ok'); + } + + expect(payload.trial.expressionHash).toBe(directRun.trial.expressionHash); + expect(row.daily_series).toEqual(directLedger.rows[0]!.daily_series); + expect(payload.study.offsets).toEqual( + directRun.study.offsets.map(o => ({ + offset: o.offset, + n: o.n, + aar: o.aar, + caar: o.caar, + caarFromZero: o.caarFromZero, + })) + ); + }); + + test('replay with reordered/duplicated IDs, kinds, and subtypes yields identical expressionHash and results; param change alters hash', async () => { + const fixture = buildSyntheticEventFixture(); + const from = fixture.allDates[0]!; + const to = fixture.allDates[64]!; + + const runWithArgs = async (args: Record) => { + const fakeStore = createFakeStore(fixture); + const ledger = createFakeTrialLedger(); + const cal = createFakeCalendarResolver(fixture.allDates); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }), + ], + }); + const res = await callEventStudy(server, args); + expect(res.payload?.status).toBe('ok'); + return res.payload as Extract; + }; + + const p1 = await runWithArgs({ + listingIds: fixture.listingIds, + from, + to, + event: { kinds: ['filing', 'earnings'], subtypes: ['8-K', 'Q4'] }, + preDays: 2, + postDays: 4, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + + const p2 = await runWithArgs({ + listingIds: [...fixture.listingIds].reverse().concat(fixture.listingIds[0]!), + from, + to, + event: { kinds: ['earnings', 'filing', 'earnings'], subtypes: ['Q4', '8-K', 'Q4'] }, + preDays: 2, + postDays: 4, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + + expect(p2.trial.expressionHash).toBe(p1.trial.expressionHash); + expect(p2.study.offsets).toEqual(p1.study.offsets); + expect(p2.event.kinds).toEqual(['earnings', 'filing']); + expect(p2.event.subtypes).toEqual(['8-K', 'Q4']); + + // Changing benchmark changes the expressionHash + const p3 = await runWithArgs({ + listingIds: fixture.listingIds, + from, + to, + event: { kinds: ['filing', 'earnings'], subtypes: ['8-K', 'Q4'] }, + preDays: 2, + postDays: 4, + benchmark: 'none', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + + expect(p3.trial.expressionHash).not.toBe(p1.trial.expressionHash); + expect(p3.study.hasBenchmark).toBe(false); + expect(p1.study.hasBenchmark).toBe(true); + // With equal_weight benchmark vs none, AAR values differ when cross-sectional mean return is non-zero + expect(p3.study.offsets[2]!.aar).not.toBeCloseTo(p1.study.offsets[2]!.aar, 8); + }); + + test('Vault fence clamps to/asOf, filters leaky store rows, and matches clean replay', async () => { + const fixture = buildSyntheticEventFixture(); + const from = fixture.allDates[0]!; + const postCutoffTo = fixture.allDates[fixture.allDates.length - 1]!; + const cutoffDate = fixture.vaultCutoffDate; + + const poisonedEvents: TableRow[] = [ + // Post-cutoff ts & known_at + { + listing_id: fixture.listingIds[0]!, + ts: makeUtcMs(cutoffDate, 14), + known_at: makeUtcMs(cutoffDate, 14), + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + // Valid ts in window, but known_at in Vault + { + listing_id: fixture.listingIds[1]!, + ts: makeUtcMs(fixture.allDates[20]!, 14), + known_at: makeUtcMs(cutoffDate, 15), + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + // Foreign listing + { + listing_id: 999_999, + ts: makeUtcMs(fixture.allDates[20]!, 14), + known_at: makeUtcMs(fixture.allDates[20]!, 14), + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + // Before study window + { + listing_id: fixture.listingIds[2]!, + ts: makeUtcMs('2022-01-05', 14), + known_at: makeUtcMs('2022-01-05', 14), + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + ]; + + const poisonedBars: BarRecord[] = [ + // Post-cutoff bar with NaN close (must never be read or affect returns) + { + listingId: fixture.listingIds[0]!, + ts: makeUtcMs(cutoffDate, 21), + open: Number.NaN, + high: Number.NaN, + low: Number.NaN, + close: Number.NaN, + volume: 100, + knownAt: makeUtcMs(cutoffDate, 21), + }, + // Foreign listing bar + { + listingId: 999_999, + ts: makeUtcMs(fixture.allDates[15]!, 21), + open: 50, + high: 50, + low: 50, + close: 50, + volume: 100, + knownAt: makeUtcMs(fixture.allDates[15]!, 21), + }, + ]; + + const leakyStore = createFakeStore(fixture, { + extraBars: poisonedBars, + extraEvents: poisonedEvents, + }); + const leakyLedger = createFakeTrialLedger(); + const leakyCal = createFakeCalendarResolver(fixture.allDates); + + const leakyServer = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: leakyStore.store, + ledger: leakyLedger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: leakyCal.resolveExchangeCalendars, + }), + ], + }); + + const leakyRes = await callEventStudy(leakyServer, { + listingIds: fixture.listingIds, + from, + to: postCutoffTo, + asOf: postCutoffTo, + event: { kinds: ['filing', 'earnings'] }, + preDays: 2, + postDays: 4, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + + expect(leakyRes.payload?.status).toBe('ok'); + const leakyPayload = leakyRes.payload as Extract; + expect(leakyPayload.clampedTo).toBe(true); + expect(leakyPayload.clampedAsOf).toBe(true); + expect(leakyPayload.toMs).toBeLessThan(fixture.vaultCutoffTs); + expect(leakyPayload.asOfMs).toBeLessThan(fixture.vaultCutoffTs); + expect(leakyPayload.vaultExcludedEvents).toBe(2); + expect(leakyPayload.eventCount).toBe(12); + + // Verify no store call received a bound >= vaultCutoffTs + expect(Date.parse(leakyStore.barsCalls[0]!.to)).toBeLessThan(fixture.vaultCutoffTs); + expect(Date.parse(leakyStore.barsCalls[0]!.asOf!)).toBeLessThan(fixture.vaultCutoffTs); + expect(Date.parse(leakyStore.eventsCalls[0]!.to)).toBeLessThan(fixture.vaultCutoffTs); + expect(Date.parse(leakyStore.eventsCalls[0]!.asOf!)).toBeLessThan(fixture.vaultCutoffTs); + expect(leakyCal.calls[0]!.toDate < fixture.vaultCutoffDate).toBe(true); + + // Compare against clean store with same arguments + const cleanStore = createFakeStore(fixture); + const cleanLedger = createFakeTrialLedger(); + const cleanCal = createFakeCalendarResolver(fixture.allDates); + const cleanServer = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: cleanStore.store, + ledger: cleanLedger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cleanCal.resolveExchangeCalendars, + }), + ], + }); + + const cleanRes = await callEventStudy(cleanServer, { + listingIds: fixture.listingIds, + from, + to: postCutoffTo, + asOf: postCutoffTo, + event: { kinds: ['filing', 'earnings'] }, + preDays: 2, + postDays: 4, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + + const cleanPayload = cleanRes.payload as Extract; + expect(leakyPayload.study.offsets).toEqual(cleanPayload.study.offsets); + expect(leakyPayload.trial.expressionHash).toBe(cleanPayload.trial.expressionHash); + expect(leakyLedger.rows[0]!.daily_series).toEqual(cleanLedger.rows[0]!.daily_series); + }); + + test('named universe resolves strictly pre-start and earlier explicit asOf caps calendar & events', async () => { + const fixture = buildSyntheticEventFixture(); + const fakeStore = createFakeStore(fixture); + const ledger = createFakeTrialLedger(); + const cal = createFakeCalendarResolver(fixture.allDates); + + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: 'operator', + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }), + ], + }); + + const from = fixture.allDates[0]!; // 2022-11-01 + const to = fixture.allDates[64]!; + const earlierAsOf = fixture.allDates[40]!; // Excludes events at day 42 and 50 + + const res = await callEventStudy(server, { + universe: 'US_EQ', + from, + to, + asOf: earlierAsOf, + event: { kinds: ['filing', 'earnings'] }, + preDays: 2, + postDays: 4, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + + expect(fakeStore.universeCalls).toHaveLength(1); + expect(fakeStore.universeCalls[0]!.ref).toBe('US_EQ'); + expect(fakeStore.universeCalls[0]!.date).toBe('2022-10-31'); // Strictly before 2022-11-01 + expect(cal.calls[0]!.toDate).toBe(earlierAsOf); + expect(res.payload?.status).toBe('ok'); + expect(res.payload?.eventCount).toBe(8); // Only days 12, 18, 26, 34 (2 listings each) + expect(ledger.rows[0]!.principal_id).toBe('operator'); + }); + + test('strict input schema rejects invalid arguments with zero dependency calls and accepts boundary windows', async () => { + const fixture = buildSyntheticEventFixture(); + const fakeStore = createFakeStore(fixture); + const ledger = createFakeTrialLedger(); + const cal = createFakeCalendarResolver(fixture.allDates); + + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }), + ], + }); + + const validBase = { + listingIds: [60_001], + from: fixture.allDates[0]!, + to: fixture.allDates[64]!, + event: { kinds: ['filing'] }, + preDays: 2, + postDays: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + const invalidCases: Record[] = [ + { ...validBase, scope: 'vault_evaluation_only' }, + { ...validBase, principalId: 'operator' }, + { ...validBase, vaultCutoffDate: '2099-01-01' }, + { ...validBase, vault_evaluation_only: true }, + { ...validBase, extraKey: 123 }, + { ...validBase, event: { kinds: ['filing'], unknownNested: true } }, + { ...validBase, universe: 'US_EQ' }, // both listingIds and universe + { + from: fixture.allDates[0]!, + to: fixture.allDates[64]!, + event: { kinds: ['filing'] }, + preDays: 2, + postDays: 5, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, // neither selector + { ...validBase, event: { kinds: [] } }, + { ...validBase, event: { kinds: ['unknown_kind'] } }, + { ...validBase, event: { kinds: ['filing'], subtypes: [] } }, + { ...validBase, preDays: -1 }, + { ...validBase, preDays: 61 }, + { ...validBase, preDays: 1.5 }, + { ...validBase, postDays: -1 }, + { ...validBase, postDays: 61 }, + { ...validBase, postDays: 2.5 }, + { ...validBase, postDays: 10, horizonBucket: 'position_10d_plus' }, + { ...validBase, postDays: 11, horizonBucket: 'swing_1_10d' }, + { ...validBase, campaignId: 'not-a-uuid' }, + { ...validBase, hypothesisId: 'not-a-uuid' }, + { + universe: 'US_EQ', + from: fixture.allDates[0]!, + to: fixture.allDates[64]!, + event: { kinds: ['filing'] }, + preDays: 2, + postDays: 5, + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }, + ]; + + for (let i = 0; i < invalidCases.length; i += 1) { + const res = await callEventStudy(server, invalidCases[i]!, i + 1); + expect(res.result?.isError).toBe(true); + expect(res.result?.content[0]?.text).toContain('Invalid arguments for tool "event_study"'); + } + + expect(fakeStore.barsCalls).toHaveLength(0); + expect(fakeStore.eventsCalls).toHaveLength(0); + expect(fakeStore.universeCalls).toHaveLength(0); + expect(cal.calls).toHaveLength(0); + expect(ledger.insertCalls).toBe(0); + + // Valid boundary windows: 0, 10 (swing_1_10d), 11, 60 (position_10d_plus) + const boundaryWindows: Array<{ preDays: number; postDays: number; bucket: string }> = [ + { preDays: 0, postDays: 0, bucket: 'swing_1_10d' }, + { preDays: 0, postDays: 10, bucket: 'swing_1_10d' }, + { preDays: 11, postDays: 11, bucket: 'position_10d_plus' }, + { preDays: 60, postDays: 60, bucket: 'position_10d_plus' }, + ]; + for (const w of boundaryWindows) { + const res = await callEventStudy(server, { + ...validBase, + preDays: w.preDays, + postDays: w.postDays, + horizonBucket: w.bucket, + }); + expect(res.result?.isError).toBeUndefined(); + expect(res.payload).toBeDefined(); + } + }); + + test('insufficient_data paths (empty universe, empty grid, below_min_events, zero_variance_series) write zero ledger rows', async () => { + const fixture = buildSyntheticEventFixture(); + + // 1. Empty resolved universe -> zero bars/events/calendar/ledger calls + { + const fakeStore = createFakeStore(fixture, { universeResolver: () => [] }); + const ledger = createFakeTrialLedger(); + const cal = createFakeCalendarResolver(fixture.allDates); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }), + ], + }); + const res = await callEventStudy(server, { + universe: 'US_EQ', + from: fixture.allDates[0]!, + to: fixture.allDates[64]!, + event: { kinds: ['filing'] }, + preDays: 2, + postDays: 4, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + expect(res.payload?.status).toBe('insufficient_data'); + if (res.payload?.status === 'insufficient_data') { + expect(res.payload.reason).toBe('below_min_events'); + } + expect(res.payload?.listingCount).toBe(0); + expect(fakeStore.barsCalls).toHaveLength(0); + expect(fakeStore.eventsCalls).toHaveLength(0); + expect(cal.calls).toHaveLength(0); + expect(ledger.insertCalls).toBe(0); + } + + // 2. Empty session grid (no bars in range) + { + const emptyBarsFixture: SyntheticEventFixture = { ...fixture, bars: [] }; + const fakeStore = createFakeStore(emptyBarsFixture); + const ledger = createFakeTrialLedger(); + const cal = createFakeCalendarResolver(fixture.allDates); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }), + ], + }); + const res = await callEventStudy(server, { + listingIds: fixture.listingIds, + from: fixture.allDates[0]!, + to: fixture.allDates[64]!, + event: { kinds: ['filing'] }, + preDays: 2, + postDays: 4, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + expect(res.payload?.status).toBe('insufficient_data'); + expect(res.payload?.eventCount).toBe(0); + expect(ledger.insertCalls).toBe(0); + } + + // 3. Below minimum events (subtype with no matches) + { + const fakeStore = createFakeStore(fixture); + const ledger = createFakeTrialLedger(); + const cal = createFakeCalendarResolver(fixture.allDates); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }), + ], + }); + const res = await callEventStudy(server, { + listingIds: fixture.listingIds, + from: fixture.allDates[0]!, + to: fixture.allDates[64]!, + event: { kinds: ['filing'], subtypes: ['NONEXISTENT_SUBTYPE'] }, + preDays: 2, + postDays: 4, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + expect(res.payload?.status).toBe('insufficient_data'); + if (res.payload?.status === 'insufficient_data') { + expect(res.payload.reason).toBe('below_min_events'); + } + expect(ledger.insertCalls).toBe(0); + } + + // 4. Zero-variance clustered CAR series + { + const flatFixture = buildSyntheticEventFixture({ zeroVariance: true }); + const fakeStore = createFakeStore(flatFixture); + const ledger = createFakeTrialLedger(); + const cal = createFakeCalendarResolver(flatFixture.allDates); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: flatFixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }), + ], + }); + const res = await callEventStudy(server, { + listingIds: flatFixture.listingIds, + from: flatFixture.allDates[0]!, + to: flatFixture.allDates[64]!, + event: { kinds: ['filing', 'earnings'] }, + preDays: 2, + postDays: 4, + benchmark: 'none', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + expect(res.payload?.status).toBe('insufficient_data'); + if (res.payload?.status === 'insufficient_data') { + expect(res.payload.reason).toBe('zero_variance_series'); + } + // Offsets are still projected when study.status === 'ok' + expect(res.payload?.study.offsets).toHaveLength(7); + expect(ledger.insertCalls).toBe(0); + } + }); + + test('factory option validation, wholly-in-Vault request, and sanitized error mapping without secret leaks', async () => { + const fixture = buildSyntheticEventFixture(); + const fakeStore = createFakeStore(fixture); + const ledger = createFakeTrialLedger(); + const cal = createFakeCalendarResolver(fixture.allDates); + const SECRET = 'SECRET_MARKER_SQL_URI_88421'; + + // Factory option validation + expect(() => + createEventStudyTool({ + store: {} as MarketDataStore, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }) + ).toThrow(MarketDataStoreValidationError); + + expect(() => + createEventStudyTool({ + store: fakeStore.store, + ledger: {} as TrialLedgerExecutor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }) + ).toThrow(SignalStudyError); + + expect(() => + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: null as unknown as typeof cal.resolveExchangeCalendars, + }) + ).toThrow(EventPanelError); + + expect(() => + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: 'invalid-principal', + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }) + ).toThrow(TrialLedgerError); + + expect(() => + createEventStudyTool({ + store: fakeStore.store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: Number.NaN }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: cal.resolveExchangeCalendars, + }) + ).toThrow(MarketDataStoreValidationError); + + // Request wholly in Vault -> zero dependency calls + { + const s = createFakeStore(fixture); + const l = createFakeTrialLedger(); + const c = createFakeCalendarResolver(fixture.allDates); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: s.store, + ledger: l.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: c.resolveExchangeCalendars, + }), + ], + }); + const res = await callEventStudy(server, { + listingIds: fixture.listingIds, + from: fixture.vaultCutoffDate, + to: fixture.allDates[fixture.allDates.length - 1]!, + event: { kinds: ['filing'] }, + preDays: 2, + postDays: 4, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + expect(res.result?.isError).toBe(true); + expect(res.result?.content[0]?.text).toContain('VaultHoldoutFenceError'); + expect(s.barsCalls).toHaveLength(0); + expect(s.eventsCalls).toHaveLength(0); + expect(c.calls).toHaveLength(0); + expect(l.insertCalls).toBe(0); + } + + const baseArgs = { + listingIds: fixture.listingIds, + from: fixture.allDates[0]!, + to: fixture.allDates[64]!, + event: { kinds: ['filing', 'earnings'] }, + preDays: 2, + postDays: 4, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + const errorCases: Array<{ + name: string; + storeOpts?: Parameters[1]; + calError?: unknown; + ledgerOpts?: Parameters[0]; + expectedPrefix: string; + }> = [ + { + name: 'store VaultHoldoutFenceError', + storeOpts: { + barsError: new VaultHoldoutFenceError('2025-01-01', 1, 1, `leak ${SECRET}`), + }, + expectedPrefix: 'VaultHoldoutFenceError:', + }, + { + name: 'store VaultScopeNotAuthorizedError', + storeOpts: { barsError: new VaultScopeNotAuthorizedError(`leak ${SECRET}`) }, + expectedPrefix: 'VaultScopeNotAuthorizedError:', + }, + { + name: 'store MarketDataStoreValidationError', + storeOpts: { + eventsError: new MarketDataStoreValidationError(`leak ${SECRET}`, 'from'), + }, + expectedPrefix: 'MarketDataStoreValidationError:', + }, + { + name: 'store MarketDataStoreNotImplementedError', + storeOpts: { + eventsError: new MarketDataStoreNotImplementedError('events', `leak ${SECRET}`), + }, + expectedPrefix: 'MarketDataStoreNotImplementedError:', + }, + { + name: 'store AdjFactorsSnapshotError', + storeOpts: { + barsError: new AdjFactorsSnapshotError('missing_snapshot', `leak ${SECRET}`), + }, + expectedPrefix: 'AdjFactorsSnapshotError:', + }, + { + name: 'calendar resolver generic Error', + calError: new Error(`calendar db down ${SECRET}`), + expectedPrefix: 'Error: Exchange calendar resolution failed.', + }, + { + name: 'calendar resolver EventPanelError', + calError: new EventPanelError('invalid_option', `bad cal ${SECRET}`), + expectedPrefix: 'EventPanelError:', + }, + { + name: 'SignalStudyError from store/runner', + storeOpts: { + eventsError: new SignalStudyError('invalid_panel', `bad panel ${SECRET}`), + }, + expectedPrefix: 'SignalStudyError:', + }, + { + name: 'TrialLedgerError on INSERT', + ledgerOpts: { + insertError: new TrialLedgerError('VAULT_FENCE_VIOLATION', `pg detail ${SECRET}`), + }, + expectedPrefix: 'TrialLedgerError:', + }, + ]; + + for (const tc of errorCases) { + const s = createFakeStore(fixture, tc.storeOpts); + const l = createFakeTrialLedger(tc.ledgerOpts); + const c = createFakeCalendarResolver(fixture.allDates, { error: tc.calError }); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: s.store, + ledger: l.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: c.resolveExchangeCalendars, + }), + ], + }); + + const res = await callEventStudy(server, baseArgs); + expect(res.result?.isError).toBe(true); + const text = res.result?.content[0]?.text ?? ''; + expect(text).toContain(tc.expectedPrefix); + expect(text).not.toContain(SECRET); + } + + // Post-insert DSR read failure: trial is recorded once (no retry) and sanitized message informs caller + { + const s = createFakeStore(fixture); + const l = createFakeTrialLedger({ + dsrReadError: new Error(`pg select timeout ${SECRET}`), + }); + const c = createFakeCalendarResolver(fixture.allDates); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: s.store, + ledger: l.executor, + vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: c.resolveExchangeCalendars, + }), + ], + }); + + const res = await callEventStudy(server, baseArgs); + expect(res.result?.isError).toBe(true); + const text = res.result?.content[0]?.text ?? ''; + expect(text).toBe( + 'SignalStudyError: Trial was recorded, but cluster deflated Sharpe evaluation failed.' + ); + expect(text).not.toContain(SECRET); + expect(l.insertCalls).toBe(1); + expect(l.rows).toHaveLength(1); + } + }); +}); From 5a36dc8aa6f1aeb4cca0cce6e79a04c80fb6a248 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 00:50:04 -0500 Subject: [PATCH 16/21] =?UTF-8?q?T-133:=20M2.1c=20=E2=80=94=20MCP=20copilo?= =?UTF-8?q?t=20`event=5Fstudy`=20tool:=20vault-fenced=20event=20study=20(b?= =?UTF-8?q?ars=20+=20`events`=20=E2=86=92=20`buildEventStudyInput`=20?= =?UTF-8?q?=E2=86=92=20`runEventStudy`=20+=20trial=20ledger)=20in=20`libs/?= =?UTF-8?q?research/src/mcp/tools/`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/research/README.md | 2 +- libs/research/src/mcp/tools/event-study.ts | 67 ++++++-- libs/research/test/mcp-event-study-qa.test.ts | 161 ++++++++++++++++++ libs/research/test/mcp-event-study.test.ts | 34 +++- 4 files changed, 245 insertions(+), 19 deletions(-) diff --git a/libs/research/README.md b/libs/research/README.md index ffb83567..944b6498 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -214,7 +214,7 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported ### `event_study` Tool (Vault-Fenced) -- **`createEventStudyTool({ store, ledger, vaultContext, principalId, resolveExchangeCalendars })`** — Runs a Vault-fenced event study over daily bars and point-in-time `events` (`filing`, `earnings`, `ceo_post`, `corporate_action`, with optional exact `subtypes` filter) for explicit `listingIds` (max `EVENT_STUDY_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref matching `universeMarket`, across `[-preDays, +postDays]` (`0–60` sessions each; `horizonBucket` must match `postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'`). +- **`createEventStudyTool({ store, ledger, vaultContext, principalId, resolveExchangeCalendars })`** — Runs a Vault-fenced event study over daily bars and point-in-time `events` (`filing`, `earnings`, `ceo_post`, `corporate_action`, with optional exact `subtypes` filter capped at `EVENT_STUDY_MAX_SUBTYPES = 100` entries and `EVENT_STUDY_MAX_SUBTYPE_LENGTH = 128` chars each) for explicit `listingIds` (max `EVENT_STUDY_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref matching `universeMarket`, across `[-preDays, +postDays]` (`0–60` sessions each; `horizonBucket` must match `postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'`). - **Injected exchange calendars:** `resolveExchangeCalendars({ listingIds, fromDate, toDate })` supplies actual exchange session close timestamps (including half-days) for `buildEventStudyInput` so events are anchored without synthesizing calendars from bars. - **Returns, benchmark & Vault fence:** Models daily close-to-close returns with no execution or transaction costs (`adjustment` defaults to `'raw'`; `benchmark` defaults to `'equal_weight'` using available eligible listing returns, or `'none'` for unbenchmarked returns). Enforces `scope: 'vault_fenced'`, clamps `to`/`asOf` strictly below `vaultCutoffTs`, resolves named universes strictly pre-start, defensively excludes any bar or event on or after the Vault cutoff date (or with `known_at > asOf`), and writes eligible trials exclusively to the injected `trial_ledger` (`stage = 'event_study'`) under the server-injected `principalId`. diff --git a/libs/research/src/mcp/tools/event-study.ts b/libs/research/src/mcp/tools/event-study.ts index 23faad0e..68e5266e 100644 --- a/libs/research/src/mcp/tools/event-study.ts +++ b/libs/research/src/mcp/tools/event-study.ts @@ -70,6 +70,12 @@ export const EVENT_STUDY_MAX_PRE_DAYS = 60; /** Hard maximum post-event window length in trading sessions. */ export const EVENT_STUDY_MAX_POST_DAYS = 60; +/** Hard maximum number of event subtype entries accepted in `event.subtypes`. */ +export const EVENT_STUDY_MAX_SUBTYPES = 100; + +/** Hard maximum character length of each event subtype string in `event.subtypes`. */ +export const EVENT_STUDY_MAX_SUBTYPE_LENGTH = 128; + const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const AGENT_PRINCIPAL_RE = /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; @@ -101,10 +107,13 @@ const eventFilterSpecSchema = z 'Non-empty list of event kinds to include (filing, earnings, ceo_post, or corporate_action).' ), subtypes: z - .array(z.string().min(1)) + .array(z.string().min(1).max(EVENT_STUDY_MAX_SUBTYPE_LENGTH)) .min(1) + .max(EVENT_STUDY_MAX_SUBTYPES) .optional() - .describe('Optional non-empty exact-match allow-list of event subtypes.'), + .describe( + `Optional non-empty exact-match allow-list of event subtypes (max ${EVENT_STUDY_MAX_SUBTYPES} entries, ${EVENT_STUDY_MAX_SUBTYPE_LENGTH} chars each).` + ), }) .strict() .describe('Event kind and optional subtype filter specification.'); @@ -421,29 +430,40 @@ function filterEligibleBars( bars: readonly BarRecord[], listingIdSet: ReadonlySet, fromMs: number, + fromSubMs: number, toMs: number, asOfMs: number, vaultCutoffTs: number, vaultCutoffDate: string -): BarRecord[] { +): { readonly bars: BarRecord[]; readonly prePanelVaultExcludedDates: number } { const eligible: BarRecord[] = []; + const vaultExcludedDates = new Set(); + const minTsMs = fromSubMs > 0 ? fromMs + 1 : fromMs; + for (let i = 0; i < bars.length; i += 1) { const row = bars[i]; if (typeof row !== 'object' || row === null) { eligible.push(row as unknown as BarRecord); continue; } - if (isValidEpochMs(row.ts)) { - if ( - row.ts < fromMs || - row.ts > toMs || - row.ts > asOfMs || - row.ts >= vaultCutoffTs || - utcDateOf(row.ts) >= vaultCutoffDate - ) { + if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) { + continue; + } + + const tsValid = isValidEpochMs(row.ts); + const tsDate = tsValid ? utcDateOf(row.ts) : null; + const tsInVault = tsValid && (row.ts >= vaultCutoffTs || (tsDate as string) >= vaultCutoffDate); + if (tsInVault) { + vaultExcludedDates.add(tsDate as string); + continue; + } + + if (tsValid) { + if (row.ts < minTsMs || row.ts > toMs || row.ts > asOfMs) { continue; } } + if (isValidEpochMs(row.knownAt)) { if ( row.knownAt > asOfMs || @@ -453,12 +473,14 @@ function filterEligibleBars( continue; } } - if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) { - continue; - } + eligible.push(row); } - return eligible; + + return { + bars: eligible, + prePanelVaultExcludedDates: vaultExcludedDates.size, + }; } function filterEligibleEventsTable(params: { @@ -467,6 +489,7 @@ function filterEligibleEventsTable(params: { readonly kindSet: ReadonlySet; readonly subtypeSet: ReadonlySet | null; readonly fromMs: number; + readonly fromSubMs: number; readonly toMs: number; readonly asOfMs: number; readonly vaultCutoffTs: number; @@ -478,6 +501,7 @@ function filterEligibleEventsTable(params: { kindSet, subtypeSet, fromMs, + fromSubMs, toMs, asOfMs, vaultCutoffTs, @@ -495,6 +519,11 @@ function filterEligibleEventsTable(params: { const eligibleRows: TableRow[] = []; let prePanelVaultExcludedEvents = 0; + // TableRow timestamps carry integer epoch-ms precision. When the effective start + // has non-zero microseconds (fromSubMs > 0), any row stamped at `fromMs` is either + // strictly earlier (e.g. `.123Z < .123456Z`) or ambiguous at the boundary ms, so + // require `ts >= fromMs + 1` conservatively. + const minTsMs = fromSubMs > 0 ? fromMs + 1 : fromMs; for (let i = 0; i < table.rows.length; i += 1) { const row = table.rows[i]; @@ -541,7 +570,7 @@ function filterEligibleEventsTable(params: { } if (isValidEpochMs(ts)) { - if (ts < fromMs || ts > toMs) { + if (ts < minTsMs || ts > toMs) { continue; } } else { @@ -837,10 +866,11 @@ export function createEventStudyTool(options: EventStudyToolOptions): McpToolEnt const kindSet = new Set(canonicalKinds); const subtypeSet = canonicalSubtypes !== undefined ? new Set(canonicalSubtypes) : null; - const eligibleBars = filterEligibleBars( + const { bars: eligibleBars, prePanelVaultExcludedDates } = filterEligibleBars( rawBars, listingIdSet, fenced.fromMs, + fenced.fromSubMs, fenced.toMs, fenced.asOfMs, vaultCutoffTs, @@ -854,6 +884,7 @@ export function createEventStudyTool(options: EventStudyToolOptions): McpToolEnt kindSet, subtypeSet, fromMs: fenced.fromMs, + fromSubMs: fenced.fromSubMs, toMs: fenced.toMs, asOfMs: fenced.asOfMs, vaultCutoffTs, @@ -877,6 +908,7 @@ export function createEventStudyTool(options: EventStudyToolOptions): McpToolEnt if (fromDate > calendarToDate) { const panelDiagnostics: EventPanelDiagnostics = { ...ZERO_EVENT_PANEL_DIAGNOSTICS, + vaultExcludedDates: prePanelVaultExcludedDates, vaultExcludedEvents: prePanelVaultExcludedEvents, droppedUnknownListing: events.length, }; @@ -918,6 +950,7 @@ export function createEventStudyTool(options: EventStudyToolOptions): McpToolEnt const combinedPanelDiagnostics: EventPanelDiagnostics = { ...built.diagnostics, + vaultExcludedDates: prePanelVaultExcludedDates + built.diagnostics.vaultExcludedDates, vaultExcludedEvents: prePanelVaultExcludedEvents + built.diagnostics.vaultExcludedEvents, }; diff --git a/libs/research/test/mcp-event-study-qa.test.ts b/libs/research/test/mcp-event-study-qa.test.ts index 7ebe7ab6..e45ec584 100644 --- a/libs/research/test/mcp-event-study-qa.test.ts +++ b/libs/research/test/mcp-event-study-qa.test.ts @@ -434,6 +434,7 @@ describe('MCP event_study QA edge cases', () => { expect(res.payload?.status).toBe('ok'); expect(res.payload?.vaultExcludedEvents).toBe(2); + expect(res.payload?.panelDiagnostics.vaultExcludedDates).toBe(2); expect(res.payload?.eventCount).toBe(6); expect(calendarCalls[0]!.toDate < cutoffDate).toBe(true); @@ -655,4 +656,164 @@ describe('MCP event_study QA edge cases', () => { expect(badRes.text).toBe('EventPanelError: Event table data failed event panel validation.'); expect(malformedLedger.insertCalls).toBe(0); }); + + test('microsecond-precision from rejects leaked boundary-millisecond event and matches clean run', async () => { + const dates = makeBusinessDates('2023-07-03', 24); + const vaultCutoffDate = dates[23]!; + const vaultCutoffTs = utcMs(vaultCutoffDate, 0); + const listingIds = [401, 402, 403, 404, 405, 406]; + + const bars: BarRecord[] = []; + for (let l = 0; l < listingIds.length; l += 1) { + const id = listingIds[l]!; + let price = 40 + l * 2; + for (let t = 0; t < 23; t += 1) { + // Distinct per-listing returns on dates[3] so admitting listingIds[1] at .123Z + // measurably shifts eventCount, eventsUsed, CAR, and ledger daily_series. + const ret = + t === 3 + ? l === 1 + ? 0.25 + : 0.05 + : t === 9 + ? 0.03 + l * 0.004 + : t === 15 + ? -0.02 + l * 0.003 + : 0.002; + price = Number((price * (1 + ret)).toFixed(6)); + const ts = utcMs(dates[t]!, 21); + bars.push({ + listingId: id, + ts, + open: price, + high: price, + low: price, + close: price, + volume: 10_000, + knownAt: ts, + }); + } + } + + // Researcher sets microsecond-precision start on half-day dates[2] (18:00 UTC close, 21:00 UTC bar stamp): + // bars from dates[2]..dates[22] enter the panel, so dates[3] (session index 1) has finite close-to-close returns. + // A leaked filing at 19:00:00.123Z (< .123456Z) would anchor to dates[3] and shift CAR/daily_series if admitted. + // A valid filing at 19:00:00.124Z (> .123456Z) must be admitted and anchored to dates[3]. + const microFromIso = `${dates[2]}T19:00:00.123456Z`; + const leakedBoundaryMs = Date.parse(`${dates[2]}T19:00:00.123Z`); + const admittedNextMs = Date.parse(`${dates[2]}T19:00:00.124Z`); + + const validRows: TableRow[] = [ + // Admitted event at fromMs + 1 (.124Z) -> anchors to dates[3] (after dates[2] 18:00 UTC half-day close) + { + listing_id: listingIds[0]!, + ts: admittedNextMs, + known_at: admittedNextMs, + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }, + // 3 events on dates[9] + ...listingIds.slice(0, 3).map(id => ({ + listing_id: id, + ts: utcMs(dates[9]!, 14), + known_at: utcMs(dates[9]!, 14), + known_at_source: 'exact', + kind: 'filing' as EventKind, + subtype: '8-K', + payload_json: '{}', + })), + // 3 events on dates[15] + ...listingIds.slice(3, 6).map(id => ({ + listing_id: id, + ts: utcMs(dates[15]!, 14), + known_at: utcMs(dates[15]!, 14), + known_at_source: 'exact', + kind: 'filing' as EventKind, + subtype: '8-K', + payload_json: '{}', + })), + ]; + + // Leaked out-of-window filing at .123Z (strictly before .123456Z) on listingIds[1] (+25% on dates[3]). + const leakedRow: TableRow = { + listing_id: listingIds[1]!, + ts: leakedBoundaryMs, + known_at: leakedBoundaryMs, + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + }; + + const resolveExchangeCalendars = async ( + q: EventStudyExchangeCalendarQuery + ): Promise => { + const sessions = dates + .filter(d => d >= q.fromDate && d <= q.toDate) + .map(date => ({ + date, + closeTs: utcMs(date, date === dates[2] ? 18 : 21), + })); + const listingCalendarId = new Map(); + for (const id of q.listingIds) { + listingCalendarId.set(id, 'XNYS'); + } + return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; + }; + + const runWithRows = async (rows: readonly TableRow[]) => { + const store = createPassThroughStore({ + bars, + eventsTable: { columns: [...EVENTS_COLUMNS], rows: [...rows] }, + }); + const ledger = createFakeLedger(); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store, + ledger: ledger.executor, + vaultContext: { vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars, + }), + ], + }); + const res = await invoke(server, { + listingIds, + from: microFromIso, + to: dates[22]!, + event: { kinds: ['filing'] }, + preDays: 0, + postDays: 1, + benchmark: 'none', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + return { res, ledger }; + }; + + const leaky = await runWithRows([leakedRow, ...validRows]); + const clean = await runWithRows(validRows); + + expect(leaky.res.isError).toBeUndefined(); + expect(clean.res.isError).toBeUndefined(); + expect(leaky.res.payload?.status).toBe('ok'); + expect(clean.res.payload?.status).toBe('ok'); + if (leaky.res.payload?.status !== 'ok' || clean.res.payload?.status !== 'ok') { + throw new Error('Expected ok payloads'); + } + + // Leaked .123Z row must be excluded; admitted .124Z row + 6 later events = 7 anchored & used events. + expect(leaky.res.payload.eventCount).toBe(7); + expect(clean.res.payload.eventCount).toBe(7); + expect(leaky.res.payload.study.diagnostics.eventsUsed).toBe(7); + expect(clean.res.payload.study.diagnostics.eventsUsed).toBe(7); + expect(leaky.res.payload.study.offsets).toEqual(clean.res.payload.study.offsets); + expect(leaky.res.payload.trial.expressionHash).toBe(clean.res.payload.trial.expressionHash); + expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series); + }); }); diff --git a/libs/research/test/mcp-event-study.test.ts b/libs/research/test/mcp-event-study.test.ts index 5782c0ff..30729c3b 100644 --- a/libs/research/test/mcp-event-study.test.ts +++ b/libs/research/test/mcp-event-study.test.ts @@ -28,6 +28,8 @@ import { EVENT_STUDY_MAX_LISTING_IDS, EVENT_STUDY_MAX_POST_DAYS, EVENT_STUDY_MAX_PRE_DAYS, + EVENT_STUDY_MAX_SUBTYPES, + EVENT_STUDY_MAX_SUBTYPE_LENGTH, type EventStudyExchangeCalendarQuery, type EventStudyResultPayload, createEventStudyTool, @@ -472,6 +474,8 @@ describe('MCP event_study tool', () => { expect(EVENT_STUDY_MAX_LISTING_IDS).toBe(500); expect(EVENT_STUDY_MAX_PRE_DAYS).toBe(60); expect(EVENT_STUDY_MAX_POST_DAYS).toBe(60); + expect(EVENT_STUDY_MAX_SUBTYPES).toBe(100); + expect(EVENT_STUDY_MAX_SUBTYPE_LENGTH).toBe(128); const raw = await server.handleMessage( JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }) @@ -501,8 +505,20 @@ describe('MCP event_study tool', () => { expect(props.vaultCutoffDate).toBeUndefined(); expect(props.vault_evaluation_only).toBeUndefined(); - const eventSchema = props.event as { additionalProperties?: boolean }; + const eventSchema = props.event as { + additionalProperties?: boolean; + properties?: { + subtypes?: { + maxItems?: number; + items?: { maxLength?: number }; + }; + }; + }; expect(eventSchema.additionalProperties).toBe(false); + expect(eventSchema.properties?.subtypes?.maxItems).toBe(EVENT_STUDY_MAX_SUBTYPES); + expect(eventSchema.properties?.subtypes?.items?.maxLength).toBe( + EVENT_STUDY_MAX_SUBTYPE_LENGTH + ); }); test('happy path matches direct runEventStudy, writes one event_study trial, and omits raw series', async () => { @@ -843,6 +859,7 @@ describe('MCP event_study tool', () => { expect(leakyPayload.toMs).toBeLessThan(fixture.vaultCutoffTs); expect(leakyPayload.asOfMs).toBeLessThan(fixture.vaultCutoffTs); expect(leakyPayload.vaultExcludedEvents).toBe(2); + expect(leakyPayload.panelDiagnostics.vaultExcludedDates).toBe(1); expect(leakyPayload.eventCount).toBe(12); // Verify no store call received a bound >= vaultCutoffTs @@ -883,6 +900,7 @@ describe('MCP event_study tool', () => { }); const cleanPayload = cleanRes.payload as Extract; + expect(cleanPayload.panelDiagnostics.vaultExcludedDates).toBe(0); expect(leakyPayload.study.offsets).toEqual(cleanPayload.study.offsets); expect(leakyPayload.trial.expressionHash).toBe(cleanPayload.trial.expressionHash); expect(leakyLedger.rows[0]!.daily_series).toEqual(cleanLedger.rows[0]!.daily_series); @@ -984,6 +1002,20 @@ describe('MCP event_study tool', () => { { ...validBase, event: { kinds: [] } }, { ...validBase, event: { kinds: ['unknown_kind'] } }, { ...validBase, event: { kinds: ['filing'], subtypes: [] } }, + { + ...validBase, + event: { + kinds: ['filing'], + subtypes: Array.from({ length: EVENT_STUDY_MAX_SUBTYPES + 1 }, (_, i) => `SUB_${i}`), + }, + }, + { + ...validBase, + event: { + kinds: ['filing'], + subtypes: ['x'.repeat(EVENT_STUDY_MAX_SUBTYPE_LENGTH + 1)], + }, + }, { ...validBase, preDays: -1 }, { ...validBase, preDays: 61 }, { ...validBase, preDays: 1.5 }, From f0f55acef2b45ee40fa478e0e1b69a2bf18dd943 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 00:56:58 -0500 Subject: [PATCH 17/21] T-133: tests --- libs/research/test/mcp-event-study-qa.test.ts | 297 ++++++++++++++++++ 1 file changed, 297 insertions(+) diff --git a/libs/research/test/mcp-event-study-qa.test.ts b/libs/research/test/mcp-event-study-qa.test.ts index e45ec584..fca76a34 100644 --- a/libs/research/test/mcp-event-study-qa.test.ts +++ b/libs/research/test/mcp-event-study-qa.test.ts @@ -817,3 +817,300 @@ describe('MCP event_study QA edge cases', () => { expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series); }); }); + +// --------------------------------------------------------------------------- +// Quant QA additions (T-133): exact benchmark economics, late-revised bars, +// subtype-filter accounting, resolver contract edges, and microsecond upper bounds. +// Fixture "qa-t133-v1": 6 listings, weekday sessions, flat prices except +// explicit jump days; gross close-to-close returns, raw adjustment, no costs. +// --------------------------------------------------------------------------- + +const QA_LISTINGS = [701, 702, 703, 704, 705, 706]; + +function qaXnysResolver(dates: readonly string[]) { + const calls: EventStudyExchangeCalendarQuery[] = []; + const resolve = (q: EventStudyExchangeCalendarQuery): EventStudyExchangeCalendars => { + calls.push(q); + const sessions = dates + .filter(d => d >= q.fromDate && d <= q.toDate) + .map(date => ({ date, closeTs: utcMs(date, 21) })); + const listingCalendarId = new Map(); + for (const id of q.listingIds) { + listingCalendarId.set(id, 'XNYS'); + } + return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; + }; + return { calls, resolve }; +} + +/** Flat 100 prices; `jumps` maps `${listingIndex}:${dayIndex}` -> daily return. */ +function qaBars(dates: readonly string[], days: number, jumps: ReadonlyMap) { + const bars: BarRecord[] = []; + for (let l = 0; l < QA_LISTINGS.length; l += 1) { + let price = 100; + for (let t = 0; t < days; t += 1) { + price = Number((price * (1 + (jumps.get(`${l}:${t}`) ?? 0))).toFixed(6)); + const ts = utcMs(dates[t]!, 21); + bars.push({ + listingId: QA_LISTINGS[l]!, + ts, + open: price, + high: price, + low: price, + close: price, + volume: 1_000, + knownAt: ts, + }); + } + } + return bars; +} + +function qaEvent(l: number, ts: number, extra?: Partial): TableRow { + return { + listing_id: QA_LISTINGS[l]!, + ts, + known_at: ts, + known_at_source: 'exact', + kind: 'filing', + subtype: '8-K', + payload_json: '{}', + ...extra, + }; +} + +function qaServer(params: { + bars: readonly BarRecord[]; + rows: readonly TableRow[]; + vaultCutoffTs: number; + resolveExchangeCalendars: ( + q: EventStudyExchangeCalendarQuery + ) => EventStudyExchangeCalendars | Promise; +}) { + const ledger = createFakeLedger(); + const server = createMcpServer({ + name: 'research-mcp', + version: '1.0.0', + tools: [ + createEventStudyTool({ + store: createPassThroughStore({ + bars: params.bars, + eventsTable: { columns: [...EVENTS_COLUMNS], rows: [...params.rows] }, + }), + ledger: ledger.executor, + vaultContext: { vaultCutoffTs: params.vaultCutoffTs }, + principalId: AGENT_PRINCIPAL, + resolveExchangeCalendars: params.resolveExchangeCalendars, + }), + ], + }); + return { server, ledger }; +} + +describe('MCP event_study QA additions', () => { + // Day 6: listings 0-2 get +10% with events; day 12: listings 3-5 get +20% with events. + // Other listings are flat, so the equal-weight benchmark on day 6 is 0.05 and on day 12 is 0.10. + const dates = makeBusinessDates('2023-03-01', 22); + const vaultCutoffTs = utcMs(dates[21]!, 0); + const jumps = new Map([ + ['0:6', 0.1], + ['1:6', 0.1], + ['2:6', 0.1], + ['3:12', 0.2], + ['4:12', 0.2], + ['5:12', 0.2], + ]); + const bars = qaBars(dates, 21, jumps); + const eventRows: TableRow[] = [ + ...[0, 1, 2].map(l => qaEvent(l, utcMs(dates[6]!, 14))), + ...[3, 4, 5].map(l => qaEvent(l, utcMs(dates[12]!, 14))), + ]; + const baseArgs = { + listingIds: QA_LISTINGS, + from: dates[0]!, + to: dates[20]!, + event: { kinds: ['filing'] }, + preDays: 1, + postDays: 1, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }; + + test('benchmark "none" reports raw event-day returns and "equal_weight" subtracts the cross-sectional mean', async () => { + const none = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + const ew = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + + const resNone = await invoke(none.server, { ...baseArgs, benchmark: 'none' }); + const resEw = await invoke(ew.server, { ...baseArgs, benchmark: 'equal_weight' }); + + if (resNone.payload?.status !== 'ok' || resEw.payload?.status !== 'ok') { + throw new Error(`Expected ok payloads: ${resNone.text} | ${resEw.text}`); + } + const at = (p: typeof resNone.payload, offset: number) => + p.study.offsets.find(o => o.offset === offset)!; + + // none: mean(+10% x3, +20% x3) = 0.15; flat neighbours. + expect(at(resNone.payload, 0).aar).toBeCloseTo(0.15, 10); + expect(at(resNone.payload, -1).aar).toBeCloseTo(0, 10); + expect(at(resNone.payload, 1).aar).toBeCloseTo(0, 10); + // equal_weight: mean(0.10-0.05 x3, 0.20-0.10 x3) = 0.075. + expect(at(resEw.payload, 0).aar).toBeCloseTo(0.075, 10); + expect(at(resEw.payload, 0).n).toBe(6); + expect(resNone.payload.study.hasBenchmark).toBe(false); + expect(resEw.payload.study.hasBenchmark).toBe(true); + expect(none.ledger.insertCalls).toBe(1); + expect(ew.ledger.insertCalls).toBe(1); + expect(resNone.payload.trial.expressionHash).not.toBe(resEw.payload.trial.expressionHash); + }); + + test('a late-revised bar (knownAt > asOf) leaked by the store is dropped before the panel', async () => { + const asOfIso = `${dates[18]!}T21:00:00.000Z`; + // Same (listing, ts) as an original bar but a different close and knownAt after asOf. + // If admitted, the panel would throw duplicate_bar or change returns. + const revised: BarRecord = { + ...bars.find(b => b.listingId === QA_LISTINGS[0] && b.ts === utcMs(dates[6]!, 21))!, + close: 999, + open: 999, + high: 999, + low: 999, + knownAt: utcMs(dates[19]!, 12), + }; + const clean = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + const leaky = qaServer({ + bars: [...bars, revised], + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + + const resClean = await invoke(clean.server, { ...baseArgs, asOf: asOfIso, benchmark: 'none' }); + const resLeaky = await invoke(leaky.server, { ...baseArgs, asOf: asOfIso, benchmark: 'none' }); + + expect(resLeaky.isError).toBeUndefined(); + if (resLeaky.payload?.status !== 'ok' || resClean.payload?.status !== 'ok') { + throw new Error(`Expected ok payloads: ${resLeaky.text}`); + } + expect(resLeaky.payload.study.offsets).toEqual(resClean.payload.study.offsets); + expect(resLeaky.payload.panelDiagnostics).toEqual(resClean.payload.panelDiagnostics); + expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series); + }); + + test('subtype filter drops null and non-matching subtypes (even in the Vault) without counting Vault exclusions', async () => { + const noise: TableRow[] = [ + qaEvent(0, utcMs(dates[9]!, 14), { subtype: null }), + qaEvent(1, utcMs(dates[9]!, 14), { subtype: '10-Q' }), + // Non-matching subtype on the cutoff day: filtered as unrequested, not as a Vault exclusion. + qaEvent(2, utcMs(dates[21]!, 14), { subtype: '10-K' }), + // Matching subtype on the cutoff day: a genuine Vault exclusion. + qaEvent(3, utcMs(dates[21]!, 14)), + ]; + const { server, ledger } = qaServer({ + bars, + rows: [...eventRows, ...noise], + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + + const res = await invoke(server, { + ...baseArgs, + event: { kinds: ['filing'], subtypes: ['8-K'] }, + benchmark: 'none', + }); + + if (res.payload?.status !== 'ok') { + throw new Error(`Expected ok: ${res.text}`); + } + expect(res.payload.eventCount).toBe(6); + expect(res.payload.vaultExcludedEvents).toBe(1); + expect(res.payload.event.subtypes).toEqual(['8-K']); + expect(res.payload.study.offsets.find(o => o.offset === 0)!.aar).toBeCloseTo(0.15, 10); + expect(ledger.insertCalls).toBe(1); + }); + + test('synchronous calendar resolver is accepted and a non-Error throw maps to the fixed resolver message', async () => { + const sync = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + const syncRes = await invoke(sync.server, { ...baseArgs, benchmark: 'none' }); + expect(syncRes.payload?.status).toBe('ok'); + + const SECRET = 'SECRET_CAL_DSN_55120'; + const failing = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: () => { + throw `postgres://calendar:${SECRET}@db/cal`; + }, + }); + const failRes = await invoke(failing.server, { ...baseArgs, benchmark: 'none' }); + expect(failRes.isError).toBe(true); + expect(failRes.text).toBe('Error: Exchange calendar resolution failed.'); + expect(failRes.text).not.toContain(SECRET); + expect(failing.ledger.insertCalls).toBe(0); + + const rejecting = qaServer({ + bars, + rows: eventRows, + vaultCutoffTs, + resolveExchangeCalendars: () => Promise.reject(new TypeError(`/srv/cal/${SECRET}.parquet`)), + }); + const rejectRes = await invoke(rejecting.server, { ...baseArgs, benchmark: 'none' }); + expect(rejectRes.isError).toBe(true); + expect(rejectRes.text).toBe('Error: Exchange calendar resolution failed.'); + expect(rejectRes.text).not.toContain(SECRET); + }); + + test('microsecond-precision to/asOf keep rows at the boundary millisecond and drop the next millisecond', async () => { + // to/asOf at dates[14] 15:00:00.123456Z. Base events (days 6, 12) are inside the window. + const boundaryIso = `${dates[14]!}T15:00:00.123456Z`; + const boundaryMs = Date.parse(`${dates[14]!}T15:00:00.123Z`); + const extra: TableRow[] = [ + qaEvent(0, boundaryMs), // ts == toMs, known_at == asOfMs (.123 <= .123456) -> kept + qaEvent(1, boundaryMs + 1), // .124 > .123456 -> dropped + qaEvent(2, utcMs(dates[10]!, 14), { known_at: boundaryMs + 1 }), // known after asOf -> dropped + ]; + const { server } = qaServer({ + bars, + rows: [...eventRows, ...extra], + vaultCutoffTs, + resolveExchangeCalendars: qaXnysResolver(dates).resolve, + }); + + const res = await invoke(server, { + ...baseArgs, + to: boundaryIso, + asOf: boundaryIso, + benchmark: 'none', + }); + + expect(res.isError).toBeUndefined(); + expect(res.payload?.effectiveTo).toBe(boundaryIso); + expect(res.payload?.effectiveAsOf).toBe(boundaryIso); + // The boundary-ms event passes the defensive filter and reaches the panel, which drops it + // as after-last-session (its dates[14] close is after asOf). The .124 rows never reach the + // panel: if they did, droppedAfterLastSession would be > 1 or eventCount would change. + expect(res.payload?.panelDiagnostics.droppedAfterLastSession).toBe(1); + expect(res.payload?.eventCount).toBe(6); + expect(res.payload?.study.diagnostics.eventsUsed).toBe(6); + expect(res.payload?.vaultExcludedEvents).toBe(0); + }); +}); From 7f2d5c46d75547ae9dfa50a367c4eb0ed7ae6a7f Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 00:16:33 -0500 Subject: [PATCH 18/21] =?UTF-8?q?T-132:=20M2.2a=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20point-in-time=20fundamentals=20builder=20(`qmF?= =?UTF-8?q?inancials`=20=C3=97=20`qmFilings`=20`known=5Fat`=20link=20+=20s?= =?UTF-8?q?tatutory-lag=20fallback=20=E2=86=92=20bitemporal=20rows=20?= =?UTF-8?q?=E2=86=92=202D=20PIT=20snapshots=20+=20TTM)=20with=20restatemen?= =?UTF-8?q?t=20fixture=20test=20and=20local=20benchmark=20(no=20new=20crat?= =?UTF-8?q?es)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 35 + tools/curate-etl/src/bench.rs | 305 +++++++ tools/curate-etl/src/cli.rs | 31 +- tools/curate-etl/src/fundamentals.rs | 944 +++++++++++++++++++++ tools/curate-etl/src/fundamentals_tests.rs | 739 ++++++++++++++++ tools/curate-etl/src/lib.rs | 12 + tools/curate-etl/src/main.rs | 46 +- 7 files changed, 2110 insertions(+), 2 deletions(-) create mode 100644 tools/curate-etl/src/fundamentals.rs create mode 100644 tools/curate-etl/src/fundamentals_tests.rs diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 1b9ab54e..9bed4735 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1553,6 +1553,41 @@ Measured locally (`2026-11-30`, two back-to-back offline runs on the final code - **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress. - **Live QA MongoDB cursor throughput on `quant`:** not run (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the driver/CLI wiring and live-host verification tasks). +## Point-in-Time Fundamentals Core (`M2.2a`) + +Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals.rs`, tested in `src/fundamentals_tests.rs`) generic over listing key `K`. BSON decoding, Zstd Parquet writing, CLI `curate-*` wiring, and `MarketDataStore.fundamentalsAsOf` are deferred to follow-up tasks. + +### Public API & Field Set + +- **Single field definition (`FundamentalsFields`):** + - Flow fields (4-quarter TTM-eligible): `revenue`, `net_income`, `operating_cash_flow`. + - Stock fields (point-in-time values, never summed for TTM): `total_assets`, `total_equity`, `shares_outstanding`. +- **Stage 1 (`build_fundamentals_rows`):** joins `FinancialObservation` against periodic `events::QmFiling` records (reusing `events::classify_form_type`, `FilingFormGroup::is_periodic_financial_report`, and `events::parse_filing_timefiled`) using an ordered `BTreeMap` (`UsTsx` vs `TsxvCse`). + - `10-Q` / SEDAR `Interim financial statements` map to `FiscalPeriod::Quarterly`; `10-K` / `40-F` / SEDAR `Annual financial statements` map to `FiscalPeriod::Annual`; non-periodic forms (`8-K`, `News release`, `MD&A`, etc.) are never linked. + - **Dated observations (`report_date: Some(rd)`):** links to the earliest matching periodic filing (amended or unamended) on that Eastern calendar date (`et_date == rd`, strictly after `period_end`), allowing late restatements/amendments beyond the inference window. If unlinked and `rd > lag_date`, the observation is dropped (`observations_dropped_unanchored_vintage`) rather than backdated. + - **Undated observations (`report_date: None`):** links to the earliest matching **non-amended** periodic filing strictly after `period_end` within inclusive heuristic windows of `QUARTERLY_FILING_LINK_WINDOW_DAYS = 75` or `ANNUAL_FILING_LINK_WINDOW_DAYS = 150` calendar days (sampled `qmFilings` carries no statement-period field). + - **Statutory-lag fallback:** unlinked rows receive `period_end + lag_days` (`+45d` Q / `+90d` FY for `UsTsx`; `+60d` Q / `+120d` FY for `TsxvCse`) at `16:05:00 America/Toronto` via `shorts::et_to_utc_micros`, tagged `known_at_source = "statutory_lag_estimate"`. + - **Validation, deduplication & determinism:** validates dates against `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE` (`2008-01-01..=2030-12-31`), drops bad rows into per-category `FundamentalsStats` counters without panicking, normalizes `-0.0` to `0.0`, collapses exact duplicates, discards conflicting `(key, period_end, known_at_utc_micros)` groups, preserves distinct `known_at_utc_micros` restatement versions, and emits rows strictly sorted by `(key, period_end, known_at_utc_micros)`. +- **Stage 2 (`build_fundamentals_snapshots`, `fundamentals_as_of` / `fundamentals::as_of`):** + - Sweeps rows in `(key, known_at_utc_micros, period_end)` order, applying all updates at a timestamp before emitting one `FundamentalsSnapshot` with the latest `k` (`k >= 1`) visible periods in descending `period_end` order. + - Carries `None` fields forward only from the prior visible version of the same `(period_end, fiscal_period, currency)`, retaining per-field provenance so a snapshot is flagged `has_estimated_lag = true` (`known_at_source = "statutory_lag_estimate"`) whenever any visible slot or any quarter contributing to TTM used an estimate. + - Computes 4-quarter TTM flow sums independently of `k` from the 4 latest visible standalone quarters when adjacent `period_end` gaps are `77..=105` calendar days (`TTM_CONSECUTIVE_QUARTER_MIN_DAYS..=TTM_CONSECUTIVE_QUARTER_MAX_DAYS`) and all 4 share one currency. + - `as_of(snapshots, key, as_of_micros)` performs an inclusive `O(log N)` binary search on `(key, effective_known_at_utc_micros)`. + +### `bench-fundamentals` + +Fixed-seed (`SplitMix64`), offline benchmark exercising both venue classes, linked periodic filings, statutory-lag fallback, exact duplicates, complete 4-quarter TTM histories, and late Q1 amendments across both stages (`k = 4`): + +```bash +cargo run -p curate-etl --release --offline -- bench-fundamentals [rows] +``` + +Measured locally (`2026-12-01`, default `rows = 100000`, `filings = 79157`, `keys = 2500`, `rows_out = 97106`, `snapshots_out = 97105`, deterministic checksum `0x078d99c42d5f200b`): + +- **Run 1:** Stage 1 `47.19 ms`, Stage 2 `35.75 ms`, total `82.94 ms` (`1,205,683 rows/s`, `829.41 ns/row`) +- **Run 2:** Stage 1 `43.89 ms`, Stage 2 `37.88 ms`, total `81.78 ms` (`1,222,862 rows/s`, `817.75 ns/row`) +- **500k scale check (`rows = 500000`, `filings = 395406`, `keys = 12500`, `rows_out = 485524`, `snapshots_out = 485518`, checksum `0x44fda3cd5f82ce5e`):** Stage 1 `277.89 ms`, Stage 2 `212.92 ms`, total `490.81 ms` (`1,018,714 rows/s`, `981.63 ns/row`) + ## Exporting Input Files (`data-pipeline`) All `curate-*` commands read local TSV and concatenated raw-BSON files produced by the read-only exporters in `@stock-bot/data-pipeline`: diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 6fea2441..89369cbb 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -1,6 +1,7 @@ //! Fixed-seed, std-only benchmark for the split-factor lookup and un-adjustment hot loop. use std::borrow::Cow; +use std::collections::BTreeMap; use std::fs::{self, File}; use std::hint::black_box; use std::io; @@ -38,6 +39,10 @@ use crate::events::{ EventsStats, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, }; +use crate::fundamentals::{ + build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, + FundamentalsError, FundamentalsFields, FundamentalsStats, StatutoryLagVenue, +}; use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar, FxSource, FX_PAIR_USDCAD}; use crate::parquet_adj::{ write_adj_factors_dataset, AdjFactorsParquetRow, AdjFactorsWriteOptions, ParquetAdjError, @@ -76,6 +81,7 @@ pub const DEFAULT_FX_BENCH_ROWS: usize = 20_000; pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000; pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000; pub const DEFAULT_EVENTS_BENCH_ROWS: usize = 500_000; +pub const DEFAULT_FUNDAMENTALS_BENCH_ROWS: usize = 100_000; pub const DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS: usize = 10_000_000; pub const DEFAULT_PARQUET_BARS_BENCH_ROWS: usize = 5_000_000; pub const PARQUET_BARS_RAW_ROW_BYTES: usize = 84; @@ -117,6 +123,9 @@ const BARS_1M_BENCH_EVENT_COUNT: usize = 2_000; const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE; const SHORTS_BENCH_SEED: u64 = 0x570C_4B07_5404_7500; const EVENTS_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7500; +const FUNDAMENTALS_BENCH_SEED: u64 = 0x570C_4B07_F04D_A001; +const FUNDAMENTALS_BENCH_TARGET_OBS_PER_KEY: usize = 40; +const FUNDAMENTALS_BENCH_SNAPSHOT_K: usize = 4; const PROVIDER_MAPPING_BENCH_SEED: u64 = 0x570C_4B07_9407_1D00; const PARQUET_BARS_BENCH_SEED: u64 = 0x570C_4B07_9A49_BA45; const PARQUET_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_5404; @@ -10934,6 +10943,261 @@ pub fn run_curate_events_cmd_benchmark( Ok(report) } +/// Summary metrics produced by [`run_fundamentals_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct FundamentalsBenchReport { + pub rows: usize, + pub filings_in: usize, + pub key_count: usize, + pub rows_out: usize, + pub keys_out: usize, + pub snapshots_out: usize, + pub rows_elapsed_ms: f64, + pub snapshots_elapsed_ms: f64, + pub total_elapsed_ms: f64, + pub rows_per_sec: f64, + pub ns_per_row: f64, + pub checksum: u64, + pub stats: FundamentalsStats, +} + +fn format_bench_filing_timefiled(epoch_day: i32, hour: u8, minute: u8, second: u8) -> String { + let (y, m, d) = epoch_days_to_ymd(epoch_day); + let zone = if (4..=10).contains(&m) { "EDT" } else { "EST" }; + format!("{y:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02} {zone}") +} + +/// Runs the fixed-seed two-stage `fundamentals` benchmark (`build_fundamentals_rows` + +/// `build_fundamentals_snapshots`) for `rows` synthetic statement observations. +/// +/// Generates filings and observations before timing, exercising both `UsTsx` and `TsxvCse` venue +/// classes, linked periodic filings (10-Q/10-K/40-F/SEDAR), statutory-lag fallback, exact +/// duplicates, complete 4-quarter histories for TTM, and late Q1-style amendments. +pub fn run_fundamentals_benchmark( + rows: usize, +) -> Result { + if rows == 0 { + return Ok(FundamentalsBenchReport { + rows: 0, + filings_in: 0, + key_count: 0, + rows_out: 0, + keys_out: 0, + snapshots_out: 0, + rows_elapsed_ms: 0.0, + snapshots_elapsed_ms: 0.0, + total_elapsed_ms: 0.0, + rows_per_sec: 0.0, + ns_per_row: 0.0, + checksum: 0, + stats: FundamentalsStats::default(), + }); + } + + let key_count = (rows / FUNDAMENTALS_BENCH_TARGET_OBS_PER_KEY).max(1); + let mut venues: BTreeMap = BTreeMap::new(); + for k in 1..=(key_count as i32) { + let venue = if k % 10 < 7 { + StatutoryLagVenue::UsTsx + } else { + StatutoryLagVenue::TsxvCse + }; + venues.insert(k, venue); + } + + let base_start = ymd_to_epoch_days(2015, 3, 31).unwrap_or(16_525); + let mut rng = SplitMix64::new(FUNDAMENTALS_BENCH_SEED); + let mut observations: Vec> = Vec::with_capacity(rows); + let mut filings: Vec> = Vec::with_capacity(rows); + + let mut period_step: i32 = 0; + while observations.len() < rows { + for key in 1..=(key_count as i32) { + if observations.len() >= rows { + break; + } + let venue = venues[&key]; + let currency = match venue { + StatutoryLagVenue::UsTsx => { + if key % 5 == 0 { + "CAD" + } else { + "USD" + } + } + StatutoryLagVenue::TsxvCse => "CAD", + }; + + let is_annual = period_step % 5 == 4; + let quarter_index = period_step - (period_step / 5); + let period_end = if is_annual { + base_start + (quarter_index - 1) * 91 + 1 + } else { + base_start + quarter_index * 91 + }; + let fiscal_period = if is_annual { + FiscalPeriod::Annual + } else { + FiscalPeriod::Quarterly + }; + + let rev = ((rng.next_u64() % 50_000) + 1_000) as f64; + let fields = FundamentalsFields { + revenue: Some(rev), + net_income: Some(rev * 0.12), + operating_cash_flow: Some(rev * 0.18), + total_assets: Some(rev * 4.5), + total_equity: Some(rev * 2.1), + shares_outstanding: Some(1_000_000.0 + (key as f64) * 100.0), + }; + + let roll = rng.next_u64() % 100; + let report_date = if roll < 75 { + let lag = 25 + (rng.next_u64() % 30) as i32; + let file_day = period_end + lag; + let form_type = match (venue, fiscal_period) { + (StatutoryLagVenue::UsTsx, FiscalPeriod::Quarterly) => "10-Q", + (StatutoryLagVenue::UsTsx, FiscalPeriod::Annual) => { + if key % 5 == 0 { + "40-F" + } else { + "10-K" + } + } + (StatutoryLagVenue::TsxvCse, FiscalPeriod::Quarterly) => { + "Interim financial statements/report - English" + } + (StatutoryLagVenue::TsxvCse, FiscalPeriod::Annual) => { + "Annual financial statements - English" + } + }; + let hour = 8 + (rng.next_u64() % 10) as u8; + let minute = (rng.next_u64() % 60) as u8; + filings.push(QmFiling { + key, + timefiled: format_bench_filing_timefiled(file_day, hour, minute, 0), + form_type: form_type.to_string(), + filing_id: None, + url: None, + }); + if roll < 50 { + Some(file_day) + } else { + None + } + } else { + None + }; + + if roll % 19 == 0 { + filings.push(QmFiling { + key, + timefiled: format_bench_filing_timefiled(period_end + 10, 16, 15, 0), + form_type: "8-K".to_string(), + filing_id: None, + url: None, + }); + } + + let obs = FinancialObservation { + key, + period_end, + fiscal_period, + currency: currency.to_string(), + report_date, + fields, + }; + observations.push(obs.clone()); + + // ~3% exact duplicate + if observations.len() < rows && roll < 3 { + observations.push(obs); + } + + // ~2% late amendment of prior quarter (after current quarter's filing) + if observations.len() < rows && !is_annual && quarter_index >= 1 && (3..5).contains(&roll) + { + let prior_pe = period_end - 91; + let amend_day = period_end + 60; + filings.push(QmFiling { + key, + timefiled: format_bench_filing_timefiled(amend_day, 17, 0, 0), + form_type: "10-Q/A".to_string(), + filing_id: None, + url: None, + }); + observations.push(FinancialObservation { + key, + period_end: prior_pe, + fiscal_period: FiscalPeriod::Quarterly, + currency: currency.to_string(), + report_date: Some(amend_day), + fields: FundamentalsFields { + revenue: Some(rev * 1.03), + net_income: Some(rev * 0.13), + operating_cash_flow: None, + total_assets: None, + total_equity: Some(rev * 2.15), + shares_outstanding: None, + }, + }); + } + } + period_step += 1; + } + + let filings_in = filings.len(); + + let rows_start = Instant::now(); + let built = build_fundamentals_rows(observations, filings, &venues); + let rows_elapsed_secs = rows_start.elapsed().as_secs_f64(); + + let snaps_start = Instant::now(); + let snapshots = build_fundamentals_snapshots(&built.rows, FUNDAMENTALS_BENCH_SNAPSHOT_K)?; + let snaps_elapsed_secs = snaps_start.elapsed().as_secs_f64(); + + let total_elapsed_secs = rows_elapsed_secs + snaps_elapsed_secs; + let (rows_per_sec, ns_per_row) = compute_rates(rows, total_elapsed_secs); + + let mut hash = 0u64; + for row in &built.rows { + hash = mix_u64(hash, row.key as u64); + hash = mix_u64(hash, row.period_end as u64); + hash = mix_u64(hash, row.known_at_utc_micros as u64); + hash = mix_u64(hash, row.fiscal_period as u64); + hash = mix_u64(hash, row.fields.revenue.map_or(0, f64::to_bits)); + hash = mix_u64(hash, row.fields.total_assets.map_or(0, f64::to_bits)); + } + for snap in &snapshots { + hash = mix_u64(hash, snap.key as u64); + hash = mix_u64(hash, snap.effective_known_at_utc_micros as u64); + hash = mix_u64(hash, u64::from(snap.has_estimated_lag)); + hash = mix_u64(hash, snap.periods.len() as u64); + if let Some(ttm) = &snap.ttm { + hash = mix_u64(hash, ttm.ending_period_end as u64); + hash = mix_u64(hash, ttm.flows.revenue.map_or(0, f64::to_bits)); + hash = mix_u64(hash, u64::from(ttm.has_estimated_lag)); + } + } + let checksum = black_box(hash); + + Ok(FundamentalsBenchReport { + rows, + filings_in, + key_count, + rows_out: built.stats.rows_out, + keys_out: built.stats.keys_out, + snapshots_out: snapshots.len(), + rows_elapsed_ms: rows_elapsed_secs * 1_000.0, + snapshots_elapsed_ms: snaps_elapsed_secs * 1_000.0, + total_elapsed_ms: total_elapsed_secs * 1_000.0, + rows_per_sec, + ns_per_row, + checksum, + stats: built.stats, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -13077,4 +13341,45 @@ mod tests { assert_eq!(report.rows_per_sec, 0.0); assert_eq!(report.ns_per_row, 0.0); } + + #[test] + fn fundamentals_benchmark_small_run_is_deterministic_and_conserves_counts() { + let a = run_fundamentals_benchmark(1_000).unwrap(); + let b = run_fundamentals_benchmark(1_000).unwrap(); + + assert_eq!(a.rows, 1_000); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.snapshots_out, b.snapshots_out); + assert_eq!(a.stats, b.stats); + assert!(a.rows_out > 0); + assert!(a.snapshots_out > 0); + assert!(a.stats.rows_linked_to_filing > 0); + assert!(a.stats.rows_statutory_lag_estimate > 0); + assert!(a.stats.duplicate_collapsed > 0); + assert_eq!( + a.stats.observations_in, + a.stats.rows_out + + a.stats.observations_dropped_unknown_key + + a.stats.observations_dropped_non_finite + + a.stats.observations_dropped_date_out_of_range + + a.stats.observations_dropped_report_date_not_after_period_end + + a.stats.observations_dropped_unanchored_vintage + + a.stats.duplicate_collapsed + + a.stats.duplicate_conflict_dropped + ); + } + + #[test] + fn fundamentals_benchmark_zero_rows_handles_cleanly() { + let report = run_fundamentals_benchmark(0).unwrap(); + assert_eq!(report.rows, 0); + assert_eq!(report.filings_in, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.snapshots_out, 0); + assert_eq!(report.checksum, 0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.ns_per_row, 0.0); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 64a26b81..bd7a2ffd 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -18,7 +18,8 @@ use crate::bench::{ DEFAULT_CURATE_CORPORATE_ACTIONS_CMD_BENCH_EVENTS, DEFAULT_CURATE_EVENTS_BENCH_ROWS, DEFAULT_CURATE_EVENTS_CMD_BENCH_ROWS, DEFAULT_CURATE_FX_BENCH_ROWS, DEFAULT_CURATE_FX_CMD_BENCH_ROWS, DEFAULT_CURATE_SHORTS_BENCH_ROWS, - DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, + DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_BENCH_ROWS, + DEFAULT_FUNDAMENTALS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, DEFAULT_MONGO_STREAM_BENCH_ROWS, DEFAULT_PARQUET_ADJ_BENCH_ROWS, DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PARQUET_CORPORATE_ACTIONS_BENCH_ROWS, DEFAULT_PARQUET_EVENTS_BENCH_ROWS, @@ -75,6 +76,7 @@ pub enum CliAction { BenchFx(usize), BenchShorts(usize), BenchEvents(usize), + BenchFundamentals(usize), BenchProviderMapping(usize), BenchParquetBars(usize), BenchParquetShorts(usize), @@ -134,6 +136,7 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-fx [rows] Run fixed-seed fx_1d build + lookup benchmark (default: {DEFAULT_FX_BENCH_ROWS})\n\ {name} bench-shorts [rows] Run fixed-seed shorts build benchmark (default: {DEFAULT_SHORTS_BENCH_ROWS})\n\ {name} bench-events [rows] Run fixed-seed events build benchmark (default: {DEFAULT_EVENTS_BENCH_ROWS})\n\ + {name} bench-fundamentals [rows] Run fixed-seed fundamentals bitemporal + PIT snapshot benchmark (default: {DEFAULT_FUNDAMENTALS_BENCH_ROWS})\n\ {name} bench-provider-mapping [lookups] Run fixed-seed provider_mapping build + lookup benchmark (default: {DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS})\n\ {name} bench-parquet-bars [rows] Run fixed-seed bars_1d Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_BARS_BENCH_ROWS})\n\ {name} bench-parquet-shorts [rows] Run fixed-seed shorts Zstd Parquet write benchmark (default: {DEFAULT_PARQUET_SHORTS_BENCH_ROWS})\n\ @@ -180,6 +183,7 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-fx [rows]\n\ {name} bench-shorts [rows]\n\ {name} bench-events [rows]\n\ + {name} bench-fundamentals [rows]\n\ {name} bench-provider-mapping [lookups]\n\ {name} bench-parquet-bars [rows]\n\ {name} bench-parquet-shorts [rows]\n\ @@ -1498,6 +1502,18 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-events", _, ..] => Err("too many arguments for bench-events".to_string()), + ["bench-fundamentals"] => Ok(CliAction::BenchFundamentals( + DEFAULT_FUNDAMENTALS_BENCH_ROWS, + )), + ["bench-fundamentals", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchFundamentals(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-fundamentals", _, ..] => { + Err("too many arguments for bench-fundamentals".to_string()) + } ["bench-provider-mapping"] => Ok(CliAction::BenchProviderMapping( DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, )), @@ -3404,5 +3420,18 @@ mod tests { assert!(parse_args(&to_args(&["bench-curate-events-cmd", "0"])).is_err()); assert!(parse_args(&to_args(&["bench-curate-events-cmd", "abc"])).is_err()); assert!(parse_args(&to_args(&["bench-curate-events-cmd", "1", "2"])).is_err()); + + // bench-fundamentals + assert_eq!( + parse_args(&to_args(&["bench-fundamentals"])), + Ok(CliAction::BenchFundamentals(DEFAULT_FUNDAMENTALS_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-fundamentals", "2500"])), + Ok(CliAction::BenchFundamentals(2_500)) + ); + assert!(parse_args(&to_args(&["bench-fundamentals", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-fundamentals", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-fundamentals", "1", "2"])).is_err()); } } diff --git a/tools/curate-etl/src/fundamentals.rs b/tools/curate-etl/src/fundamentals.rs new file mode 100644 index 00000000..44c72169 --- /dev/null +++ b/tools/curate-etl/src/fundamentals.rs @@ -0,0 +1,944 @@ +//! Pure, in-memory point-in-time `fundamentals` builder (`qmFinancials` × `qmFilings` → +//! `fundamentals_bitemporal` rows → 2D `fundamentals_pit` snapshots + 4-quarter TTM). +//! +//! Aligned with `design/DATA-CONTRACTS.md` (§1 `qmFinancials`/`qmFilings` and §3A +//! `fundamentals_bitemporal` / `fundamentals_pit`): +//! +//! ## Stage 1 — Bitemporal Rows (`build_fundamentals_rows`) +//! - **Filing classification & timestamp parsing:** reuses [`crate::events::classify_form_type`], +//! [`FilingFormGroup::is_periodic_financial_report`], and +//! [`crate::events::parse_filing_timefiled`]. `10-Q` and SEDAR `Interim financial statements` +//! map to [`FiscalPeriod::Quarterly`]; `10-K`, `40-F`, and SEDAR `Annual financial statements` +//! map to [`FiscalPeriod::Annual`]. Non-periodic forms (such as `8-K`, `4`, `144`, `MD&A`, +//! `News release`) are never linked. +//! - **Heuristic filing-link rules (sampled `qmFilings` carries no statement-period field):** +//! - **Dated observation (`report_date: Some(rd)`):** `report_date` is assumed to identify the +//! observation's Eastern Time filing/vintage date. Links to the earliest matching periodic +//! filing (amended or unamended) for the same `(key, fiscal_period)` with `et_date == rd` +//! (strictly after `period_end`, because `rd <= period_end` is rejected). A same-day match can +//! anchor a late restatement/amendment beyond the inference windows below. +//! - **Undated observation (`report_date: None`):** links to the earliest matching +//! **non-amended** periodic filing for the same `(key, fiscal_period)` strictly after +//! `period_end` and within an inclusive calendar-day window of +//! [`QUARTERLY_FILING_LINK_WINDOW_DAYS`] (`75` days) for quarterly reports or +//! [`ANNUAL_FILING_LINK_WINDOW_DAYS`] (`150` days) for annual reports. +//! - Linked rows carry `known_at_utc_micros = parsed.utc_micros` and +//! `known_at_source = "filing_timestamp"`. +//! - **Statutory-lag fallback (unlinked observations):** +//! - `lag_date = period_end + venue.lag_days(fiscal_period)`: +//! - US & TSX ([`StatutoryLagVenue::UsTsx`]): `+45` calendar days (Q) / `+90` calendar days (FY). +//! - TSXV & CSE ([`StatutoryLagVenue::TsxvCse`]): `+60` calendar days (Q) / `+120` calendar days (FY). +//! - If a dated observation (`report_date: Some(rd)`) has no same-day filing link and +//! `rd > lag_date`, it is dropped and counted as an unanchored vintage +//! (`observations_dropped_unanchored_vintage`) rather than backdating `known_at` before its +//! observed `report_date`. +//! - Otherwise `known_at_utc_micros` is `lag_date` at `16:05:00 America/Toronto` +//! ([`FUNDAMENTALS_FALLBACK_HOUR_ET`]:[`FUNDAMENTALS_FALLBACK_MINUTE_ET`]) via +//! [`crate::shorts::et_to_utc_micros`], tagged `known_at_source = "statutory_lag_estimate"`. +//! - **Calendar bounds & bad-row resilience:** statement `period_end`, optional `report_date`, +//! periodic filing Eastern days, and computed `lag_date` are validated against +//! [`MIN_SUPPORTED_DATE`]..=[`MAX_SUPPORTED_DATE`] (`2008-01-01..=2030-12-31`). Periodic filings +//! with `et_date <= earliest_period_end` for that `(key, fiscal_period)` are excluded and counted +//! in `filings_dropped_before_period_end`. Bad rows never panic; each category is counted in +//! [`FundamentalsStats`]. +//! - **Normalization, deduplication & sort:** `-0.0` normalizes to `0.0`. Rows are sorted by +//! `(key, period_end, known_at_utc_micros)`. Bitwise-identical duplicates at the same +//! `(key, period_end, known_at_utc_micros)` collapse (`duplicate_collapsed`); conflicting groups +//! (differing values, currency, fiscal period, or provenance) are discarded entirely +//! (`duplicate_conflict_dropped`). Distinct `known_at_utc_micros` versions for the same +//! `(key, period_end)` are preserved as separate restatement versions. +//! +//! ## Stage 2 — 2D PIT Snapshots & TTM (`build_fundamentals_snapshots`, `as_of`) +//! - Sweeps rows in `(key, known_at_utc_micros, period_end)` order, applying all updates sharing +//! `(key, effective_known_at_utc_micros)` before emitting one [`FundamentalsSnapshot`]. +//! - Maintains the latest visible version per `period_end`, carrying `None` fields forward from +//! the previous visible version of the **same** `(period_end, fiscal_period, currency)` along +//! with per-field provenance. +//! - Emits the latest `k` visible periods in descending `period_end` order (annual rows may occupy +//! slots; stock fields remain reported period values). +//! - Independently of `k`, computes 4-quarter TTM sums for flow fields (`revenue`, `net_income`, +//! `operating_cash_flow`) from the 4 latest visible standalone quarterly periods when adjacent +//! `period_end` spacing is within [`TTM_CONSECUTIVE_QUARTER_MIN_DAYS`]..=[`TTM_CONSECUTIVE_QUARTER_MAX_DAYS`] +//! (`77..=105` calendar days, a heuristic given the input lacks a fiscal-quarter ordinal) and +//! all 4 share one currency. Missing flow inputs or non-finite sums produce `None` for that +//! field. +//! - Flags `has_estimated_lag = true` (and `known_at_source = "statutory_lag_estimate"`) if any +//! visible period slot or any quarter contributing to `ttm` used `statutory_lag_estimate` +//! (directly or via an inherited field). + +use std::borrow::Borrow; +use std::cmp::Ordering; +use std::collections::BTreeMap; +use std::error::Error; +use std::fmt; + +use crate::events::{ + classify_form_type, parse_filing_timefiled, FilingFormGroup, QmFiling, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +use crate::shorts::{et_to_utc_micros, MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE}; + +/// Statutory quarterly reporting lag (calendar days) for US & TSX listings (`design/DATA-CONTRACTS.md` §1). +pub const STATUTORY_LAG_US_TSX_QUARTERLY_DAYS: i32 = 45; + +/// Statutory annual reporting lag (calendar days) for US & TSX listings (`design/DATA-CONTRACTS.md` §1). +pub const STATUTORY_LAG_US_TSX_ANNUAL_DAYS: i32 = 90; + +/// Statutory quarterly reporting lag (calendar days) for TSXV & CSE listings (`design/DATA-CONTRACTS.md` §1). +pub const STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS: i32 = 60; + +/// Statutory annual reporting lag (calendar days) for TSXV & CSE listings (`design/DATA-CONTRACTS.md` §1). +pub const STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS: i32 = 120; + +/// Conservative fallback hour (`16:05 America/Toronto`) for statutory-lag `known_at` timestamps. +pub const FUNDAMENTALS_FALLBACK_HOUR_ET: u8 = 16; + +/// Conservative fallback minute (`16:05 America/Toronto`) for statutory-lag `known_at` timestamps. +pub const FUNDAMENTALS_FALLBACK_MINUTE_ET: u8 = 5; + +/// Inclusive heuristic filing-link window (calendar days strictly after `period_end`) for undated +/// quarterly observations when `qmFilings` carries no statement-period field. +pub const QUARTERLY_FILING_LINK_WINDOW_DAYS: i32 = 75; + +/// Inclusive heuristic filing-link window (calendar days strictly after `period_end`) for undated +/// annual observations when `qmFilings` carries no statement-period field. +pub const ANNUAL_FILING_LINK_WINDOW_DAYS: i32 = 150; + +/// Minimum inclusive calendar-day gap between adjacent quarterly `period_end` dates to be treated +/// as consecutive for 4-quarter TTM summation. +pub const TTM_CONSECUTIVE_QUARTER_MIN_DAYS: i32 = 77; + +/// Maximum inclusive calendar-day gap between adjacent quarterly `period_end` dates to be treated +/// as consecutive for 4-quarter TTM summation. +pub const TTM_CONSECUTIVE_QUARTER_MAX_DAYS: i32 = 105; + +/// Number of consecutive standalone quarters required to compute TTM flow sums. +pub const TTM_QUARTER_COUNT: usize = 4; + +/// Fiscal statement period kind. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum FiscalPeriod { + Quarterly, + Annual, +} + +impl FiscalPeriod { + /// Canonical contract label (`"Q"` or `"FY"`). + #[inline] + pub const fn as_str(self) -> &'static str { + match self { + Self::Quarterly => "Q", + Self::Annual => "FY", + } + } + + /// Inclusive heuristic link window in calendar days for undated observations. + #[inline] + pub const fn undated_link_window_days(self) -> i32 { + match self { + Self::Quarterly => QUARTERLY_FILING_LINK_WINDOW_DAYS, + Self::Annual => ANNUAL_FILING_LINK_WINDOW_DAYS, + } + } +} + +/// Per-listing venue class governing statutory deadline lag fallback. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum StatutoryLagVenue { + /// US exchanges and Toronto Stock Exchange (`+45d` Q / `+90d` FY). + UsTsx, + /// TSX Venture Exchange and Canadian Securities Exchange (`+60d` Q / `+120d` FY). + TsxvCse, +} + +impl StatutoryLagVenue { + /// Exact calendar-day statutory deadline lag for `(self, fiscal_period)`. + #[inline] + pub const fn lag_days(self, fiscal_period: FiscalPeriod) -> i32 { + match (self, fiscal_period) { + (Self::UsTsx, FiscalPeriod::Quarterly) => STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, + (Self::UsTsx, FiscalPeriod::Annual) => STATUTORY_LAG_US_TSX_ANNUAL_DAYS, + (Self::TsxvCse, FiscalPeriod::Quarterly) => STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, + (Self::TsxvCse, FiscalPeriod::Annual) => STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, + } + } +} + +/// Standardized numeric statement fields (single source of truth for Stage 1 and Stage 2). +/// +/// Flow fields (`revenue`, `net_income`, `operating_cash_flow`) are summed across 4 consecutive +/// standalone quarters for TTM. Stock fields (`total_assets`, `total_equity`, `shares_outstanding`) +/// are point-in-time balance/count values and are never summed for TTM. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct FundamentalsFields { + // Flow fields (TTM-eligible) + pub revenue: Option, + pub net_income: Option, + pub operating_cash_flow: Option, + // Stock fields (never TTM-summed) + pub total_assets: Option, + pub total_equity: Option, + pub shares_outstanding: Option, +} + +impl FundamentalsFields { + #[inline] + fn all_finite(&self) -> bool { + opt_is_finite(self.revenue) + && opt_is_finite(self.net_income) + && opt_is_finite(self.operating_cash_flow) + && opt_is_finite(self.total_assets) + && opt_is_finite(self.total_equity) + && opt_is_finite(self.shares_outstanding) + } + + #[inline] + fn normalize_zeros(self) -> Self { + Self { + revenue: self.revenue.map(normalize_zero), + net_income: self.net_income.map(normalize_zero), + operating_cash_flow: self.operating_cash_flow.map(normalize_zero), + total_assets: self.total_assets.map(normalize_zero), + total_equity: self.total_equity.map(normalize_zero), + shares_outstanding: self.shares_outstanding.map(normalize_zero), + } + } + + #[inline] + fn bit_eq(&self, other: &Self) -> bool { + self.revenue.map(f64::to_bits) == other.revenue.map(f64::to_bits) + && self.net_income.map(f64::to_bits) == other.net_income.map(f64::to_bits) + && self.operating_cash_flow.map(f64::to_bits) + == other.operating_cash_flow.map(f64::to_bits) + && self.total_assets.map(f64::to_bits) == other.total_assets.map(f64::to_bits) + && self.total_equity.map(f64::to_bits) == other.total_equity.map(f64::to_bits) + && self.shares_outstanding.map(f64::to_bits) + == other.shares_outstanding.map(f64::to_bits) + } +} + +/// 4-quarter trailing twelve months (TTM) sums for flow fields. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct TtmFlowFields { + pub revenue: Option, + pub net_income: Option, + pub operating_cash_flow: Option, +} + +/// Precomputed 4-quarter TTM summary attached to a [`FundamentalsSnapshot`]. +#[derive(Debug, Clone, PartialEq)] +pub struct FundamentalsTtm { + /// `period_end` epoch day of the latest (4th) quarter in the TTM window. + pub ending_period_end: i32, + /// Shared currency across all 4 contributing quarters. + pub currency: String, + /// Trailing 4-quarter sums for each flow field (`None` if any quarter lacks the field or if + /// the sum overflows to non-finite). + pub flows: TtmFlowFields, + /// `true` if any of the 4 contributing quarters used `statutory_lag_estimate` (directly or via + /// an inherited field). + pub has_estimated_lag: bool, +} + +/// A single raw financial-statement observation input (`qmFinancials`-shaped, BSON-free). +#[derive(Debug, Clone, PartialEq)] +pub struct FinancialObservation { + pub key: K, + /// Fiscal period end date as days since `1970-01-01` (UTC Gregorian). + pub period_end: i32, + pub fiscal_period: FiscalPeriod, + /// ISO currency code (e.g. `"USD"`, `"CAD"`). + pub currency: String, + /// Optional Eastern Time report/vintage date as days since `1970-01-01`. + pub report_date: Option, + pub fields: FundamentalsFields, +} + +/// A single curated bitemporal fundamentals row matching `fundamentals_bitemporal` in +/// `design/DATA-CONTRACTS.md` §3A, sorted and unique by `(key, period_end, known_at_utc_micros)`. +#[derive(Debug, Clone, PartialEq)] +pub struct FundamentalsRow { + pub key: K, + pub period_end: i32, + pub fiscal_period: FiscalPeriod, + pub currency: String, + pub known_at_utc_micros: i64, + pub known_at_source: &'static str, + pub fields: FundamentalsFields, +} + +/// A single resolved period entry inside a [`FundamentalsSnapshot`]. +#[derive(Debug, Clone, PartialEq)] +pub struct FundamentalsPeriodSlot { + pub period_end: i32, + pub fiscal_period: FiscalPeriod, + pub currency: String, + pub known_at_utc_micros: i64, + pub known_at_source: &'static str, + /// `true` if this period's latest version used `statutory_lag_estimate` or any field was + /// carried forward from an earlier `statutory_lag_estimate` version. + pub has_estimated_lag: bool, + pub fields: FundamentalsFields, +} + +/// A single 2D point-in-time snapshot matching `fundamentals_pit` in `design/DATA-CONTRACTS.md` +/// §3A, keyed by `(key, effective_known_at_utc_micros)`. +#[derive(Debug, Clone, PartialEq)] +pub struct FundamentalsSnapshot { + pub key: K, + pub effective_known_at_utc_micros: i64, + /// `"statutory_lag_estimate"` if [`Self::has_estimated_lag`] is `true`, otherwise + /// `"filing_timestamp"`. + pub known_at_source: &'static str, + /// `true` if any visible period slot or any quarter contributing to [`Self::ttm`] used + /// `statutory_lag_estimate` (directly or via an inherited field). + pub has_estimated_lag: bool, + /// Latest `k` visible periods ordered by `period_end` descending (`periods[0]` is latest). + pub periods: Vec, + /// Precomputed 4-quarter TTM flow sums, computed independently of `k`. + pub ttm: Option, +} + +/// Summary accounting counters produced alongside [`FundamentalsBuild::rows`]. +/// +/// Conservation invariants: +/// - Observations: +/// `observations_in == rows_out + observations_dropped_unknown_key + observations_dropped_non_finite + observations_dropped_date_out_of_range + observations_dropped_report_date_not_after_period_end + observations_dropped_unanchored_vintage + duplicate_collapsed + duplicate_conflict_dropped` +/// - Output provenance: +/// `rows_out == rows_linked_to_filing + rows_statutory_lag_estimate` +/// - Filings: +/// `filings_in == filings_eligible + filings_dropped_unknown_key + filings_ignored_non_periodic + filings_dropped_invalid_timestamp + filings_dropped_date_out_of_range + filings_dropped_before_period_end` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct FundamentalsStats { + pub observations_in: usize, + pub rows_out: usize, + pub keys_out: usize, + pub rows_linked_to_filing: usize, + pub rows_statutory_lag_estimate: usize, + pub observations_dropped_unknown_key: usize, + pub observations_dropped_non_finite: usize, + pub observations_dropped_date_out_of_range: usize, + pub observations_dropped_report_date_not_after_period_end: usize, + pub observations_dropped_unanchored_vintage: usize, + pub duplicate_collapsed: usize, + pub duplicate_conflict_dropped: usize, + pub filings_in: usize, + pub filings_eligible: usize, + pub filings_dropped_unknown_key: usize, + pub filings_ignored_non_periodic: usize, + pub filings_dropped_invalid_timestamp: usize, + pub filings_dropped_date_out_of_range: usize, + pub filings_dropped_before_period_end: usize, +} + +/// Output of [`build_fundamentals_rows`]: sorted, unique bitemporal rows and reconciling stats. +#[derive(Debug, Clone, PartialEq)] +pub struct FundamentalsBuild { + pub rows: Vec>, + pub stats: FundamentalsStats, +} + +/// Typed caller errors returned by [`build_fundamentals_snapshots`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FundamentalsError { + /// Caller-supplied `k` (maximum periods retained per snapshot) was zero. + InvalidPeriodLimit { k: usize }, +} + +impl fmt::Display for FundamentalsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::InvalidPeriodLimit { k } => { + write!(f, "invalid snapshot period limit k={k}: must be >= 1") + } + } + } +} + +impl Error for FundamentalsError {} + +#[inline] +fn opt_is_finite(v: Option) -> bool { + v.is_none_or(f64::is_finite) +} + +#[inline] +fn normalize_zero(v: f64) -> f64 { + if v == 0.0 { + 0.0 + } else { + v + } +} + +#[inline] +fn is_supported_date(epoch_day: i32) -> bool { + (MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&epoch_day) +} + +#[inline] +fn periodic_group_to_fiscal_period(group: FilingFormGroup) -> Option { + if !group.is_periodic_financial_report() { + return None; + } + match group { + FilingFormGroup::Form10Q | FilingFormGroup::InterimFinancials => { + Some(FiscalPeriod::Quarterly) + } + FilingFormGroup::Form10K + | FilingFormGroup::Form40F + | FilingFormGroup::AnnualFinancials => Some(FiscalPeriod::Annual), + _ => None, + } +} + +struct EligibleObservation { + key: K, + period_end: i32, + fiscal_period: FiscalPeriod, + currency: String, + report_date: Option, + venue: StatutoryLagVenue, + fields: FundamentalsFields, +} + +#[derive(Debug, Clone, Copy)] +struct IndexedFiling { + et_date: i32, + utc_micros: i64, + is_amendment: bool, +} + +struct ParsedPeriodicFiling { + key: K, + fiscal_period: FiscalPeriod, + et_date: i32, + utc_micros: i64, + is_amendment: bool, +} + +/// Builds sorted, unique bitemporal fundamentals rows from financial observations, periodic +/// filings, and per-listing statutory-lag venue classes. +/// +/// Any permutation of `observations` or `filings` yields bitwise-identical `rows` and `stats`. +pub fn build_fundamentals_rows( + observations: IO, + filings: IF, + venues: &BTreeMap, +) -> FundamentalsBuild +where + K: Ord + Clone, + IO: IntoIterator>, + IF: IntoIterator>, +{ + let obs_iter = observations.into_iter(); + let mut stats = FundamentalsStats::default(); + let mut eligible_obs: Vec> = Vec::with_capacity(obs_iter.size_hint().0); + let mut earliest_period_by_key_kind: BTreeMap<(K, FiscalPeriod), i32> = BTreeMap::new(); + + for obs in obs_iter { + stats.observations_in += 1; + + let Some(&venue) = venues.get(&obs.key) else { + stats.observations_dropped_unknown_key += 1; + continue; + }; + + if !obs.fields.all_finite() { + stats.observations_dropped_non_finite += 1; + continue; + } + + if !is_supported_date(obs.period_end) + || obs.report_date.is_some_and(|rd| !is_supported_date(rd)) + { + stats.observations_dropped_date_out_of_range += 1; + continue; + } + + if obs.report_date.is_some_and(|rd| rd <= obs.period_end) { + stats.observations_dropped_report_date_not_after_period_end += 1; + continue; + } + + earliest_period_by_key_kind + .entry((obs.key.clone(), obs.fiscal_period)) + .and_modify(|min_pe| { + if obs.period_end < *min_pe { + *min_pe = obs.period_end; + } + }) + .or_insert(obs.period_end); + + eligible_obs.push(EligibleObservation { + key: obs.key, + period_end: obs.period_end, + fiscal_period: obs.fiscal_period, + currency: obs.currency, + report_date: obs.report_date, + venue, + fields: obs.fields.normalize_zeros(), + }); + } + + let filings_iter = filings.into_iter(); + let mut parsed_filings: Vec> = Vec::new(); + + for filing in filings_iter { + stats.filings_in += 1; + + if !venues.contains_key(&filing.key) { + stats.filings_dropped_unknown_key += 1; + continue; + } + + let (group, is_amendment) = classify_form_type(&filing.form_type); + let Some(fiscal_period) = periodic_group_to_fiscal_period(group) else { + stats.filings_ignored_non_periodic += 1; + continue; + }; + + let Ok(parsed) = parse_filing_timefiled(&filing.timefiled) else { + stats.filings_dropped_invalid_timestamp += 1; + continue; + }; + + if !is_supported_date(parsed.et_date) { + stats.filings_dropped_date_out_of_range += 1; + continue; + } + + parsed_filings.push(ParsedPeriodicFiling { + key: filing.key, + fiscal_period, + et_date: parsed.et_date, + utc_micros: parsed.utc_micros, + is_amendment, + }); + } + + let mut filing_index: BTreeMap<(K, FiscalPeriod), Vec> = BTreeMap::new(); + for pf in parsed_filings { + let key_kind = (pf.key, pf.fiscal_period); + if let Some(&min_pe) = earliest_period_by_key_kind.get(&key_kind) { + if pf.et_date <= min_pe { + stats.filings_dropped_before_period_end += 1; + continue; + } + } + stats.filings_eligible += 1; + filing_index.entry(key_kind).or_default().push(IndexedFiling { + et_date: pf.et_date, + utc_micros: pf.utc_micros, + is_amendment: pf.is_amendment, + }); + } + + for bucket in filing_index.values_mut() { + bucket.sort_unstable_by(|a, b| { + a.et_date + .cmp(&b.et_date) + .then_with(|| a.utc_micros.cmp(&b.utc_micros)) + .then_with(|| a.is_amendment.cmp(&b.is_amendment)) + }); + } + + let mut candidates: Vec> = Vec::with_capacity(eligible_obs.len()); + + for obs in eligible_obs { + let linked_micros = filing_index + .get(&(obs.key.clone(), obs.fiscal_period)) + .and_then(|bucket| match obs.report_date { + Some(rd) => { + // Earliest matching periodic filing (amended or unamended) on Eastern day `rd`. + // `rd > obs.period_end` is guaranteed by validation above. + let pos = bucket.partition_point(|f| f.et_date < rd); + bucket + .get(pos) + .filter(|f| f.et_date == rd) + .map(|f| f.utc_micros) + } + None => { + // Earliest matching non-amended periodic filing strictly after `period_end` + // and within the inclusive calendar-day inference window. + let window_end = i64::from(obs.period_end) + + i64::from(obs.fiscal_period.undated_link_window_days()); + let pos = bucket.partition_point(|f| f.et_date <= obs.period_end); + bucket[pos..] + .iter() + .take_while(|f| i64::from(f.et_date) <= window_end) + .find(|f| !f.is_amendment) + .map(|f| f.utc_micros) + } + }); + + let (known_at_utc_micros, known_at_source) = if let Some(micros) = linked_micros { + (micros, KNOWN_AT_SOURCE_FILING_TIMESTAMP) + } else { + let lag_days = obs.venue.lag_days(obs.fiscal_period); + let lag_date_i64 = i64::from(obs.period_end) + i64::from(lag_days); + + if let Some(rd) = obs.report_date { + if i64::from(rd) > lag_date_i64 { + stats.observations_dropped_unanchored_vintage += 1; + continue; + } + } + + let Ok(lag_date) = i32::try_from(lag_date_i64) else { + stats.observations_dropped_date_out_of_range += 1; + continue; + }; + let Ok(micros) = et_to_utc_micros( + lag_date, + FUNDAMENTALS_FALLBACK_HOUR_ET, + FUNDAMENTALS_FALLBACK_MINUTE_ET, + 0, + ) else { + stats.observations_dropped_date_out_of_range += 1; + continue; + }; + (micros, KNOWN_AT_SOURCE_STATUTORY_LAG) + }; + + candidates.push(FundamentalsRow { + key: obs.key, + period_end: obs.period_end, + fiscal_period: obs.fiscal_period, + currency: obs.currency, + known_at_utc_micros, + known_at_source, + fields: obs.fields, + }); + } + + candidates.sort_unstable_by(|a, b| { + a.key + .cmp(&b.key) + .then_with(|| a.period_end.cmp(&b.period_end)) + .then_with(|| a.known_at_utc_micros.cmp(&b.known_at_utc_micros)) + }); + + let mut rows: Vec> = Vec::with_capacity(candidates.len()); + let total = candidates.len(); + let mut idx = 0usize; + + while idx < total { + let mut group_end = idx + 1; + while group_end < total + && candidates[group_end].key == candidates[idx].key + && candidates[group_end].period_end == candidates[idx].period_end + && candidates[group_end].known_at_utc_micros == candidates[idx].known_at_utc_micros + { + group_end += 1; + } + + let group_len = group_end - idx; + let first = &candidates[idx]; + let all_identical = candidates[idx + 1..group_end].iter().all(|other| { + first.fiscal_period == other.fiscal_period + && first.currency == other.currency + && first.known_at_source == other.known_at_source + && first.fields.bit_eq(&other.fields) + }); + + if all_identical { + stats.duplicate_collapsed += group_len - 1; + if first.known_at_source == KNOWN_AT_SOURCE_FILING_TIMESTAMP { + stats.rows_linked_to_filing += 1; + } else { + stats.rows_statutory_lag_estimate += 1; + } + if rows.last().is_none_or(|prev| prev.key != first.key) { + stats.keys_out += 1; + } + rows.push(first.clone()); + } else { + stats.duplicate_conflict_dropped += group_len; + } + + idx = group_end; + } + + stats.rows_out = rows.len(); + FundamentalsBuild { rows, stats } +} + +#[derive(Clone)] +struct ResolvedPeriod { + period_end: i32, + fiscal_period: FiscalPeriod, + currency: String, + known_at_utc_micros: i64, + known_at_source: &'static str, + fields: FundamentalsFields, + /// Per-field flag: `true` iff that `Some` field originated from a `statutory_lag_estimate` row. + field_estimated: [bool; 6], +} + +impl ResolvedPeriod { + #[inline] + fn from_row(row: &FundamentalsRow) -> Self { + let est = row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG; + let fields = row.fields.normalize_zeros(); + let field_estimated = [ + est && fields.revenue.is_some(), + est && fields.net_income.is_some(), + est && fields.operating_cash_flow.is_some(), + est && fields.total_assets.is_some(), + est && fields.total_equity.is_some(), + est && fields.shares_outstanding.is_some(), + ]; + Self { + period_end: row.period_end, + fiscal_period: row.fiscal_period, + currency: row.currency.clone(), + known_at_utc_micros: row.known_at_utc_micros, + known_at_source: row.known_at_source, + fields, + field_estimated, + } + } + + #[inline] + fn apply_update(&mut self, row: &FundamentalsRow) { + if self.fiscal_period != row.fiscal_period || self.currency != row.currency { + *self = Self::from_row(row); + return; + } + + let est = row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG; + let incoming = row.fields.normalize_zeros(); + + if let Some(v) = incoming.revenue { + self.fields.revenue = Some(v); + self.field_estimated[0] = est; + } + if let Some(v) = incoming.net_income { + self.fields.net_income = Some(v); + self.field_estimated[1] = est; + } + if let Some(v) = incoming.operating_cash_flow { + self.fields.operating_cash_flow = Some(v); + self.field_estimated[2] = est; + } + if let Some(v) = incoming.total_assets { + self.fields.total_assets = Some(v); + self.field_estimated[3] = est; + } + if let Some(v) = incoming.total_equity { + self.fields.total_equity = Some(v); + self.field_estimated[4] = est; + } + if let Some(v) = incoming.shares_outstanding { + self.fields.shares_outstanding = Some(v); + self.field_estimated[5] = est; + } + + self.known_at_utc_micros = row.known_at_utc_micros; + self.known_at_source = row.known_at_source; + } + + #[inline] + fn has_estimated_lag(&self) -> bool { + self.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG + || self.field_estimated.iter().any(|&e| e) + } + + #[inline] + fn to_slot(&self) -> FundamentalsPeriodSlot { + FundamentalsPeriodSlot { + period_end: self.period_end, + fiscal_period: self.fiscal_period, + currency: self.currency.clone(), + known_at_utc_micros: self.known_at_utc_micros, + known_at_source: self.known_at_source, + has_estimated_lag: self.has_estimated_lag(), + fields: self.fields, + } + } +} + +#[inline] +fn sum_4_flows(values: [Option; 4]) -> Option { + let [v0, v1, v2, v3] = values; + let sum = v3? + v2? + v1? + v0?; + if sum.is_finite() { + Some(normalize_zero(sum)) + } else { + None + } +} + +fn compute_ttm(visible_periods: &BTreeMap) -> Option { + let quarters: [&ResolvedPeriod; TTM_QUARTER_COUNT] = { + let mut iter = visible_periods + .values() + .rev() + .filter(|p| p.fiscal_period == FiscalPeriod::Quarterly); + let q0 = iter.next()?; + let q1 = iter.next()?; + let q2 = iter.next()?; + let q3 = iter.next()?; + [q0, q1, q2, q3] + }; + + let min_gap = i64::from(TTM_CONSECUTIVE_QUARTER_MIN_DAYS); + let max_gap = i64::from(TTM_CONSECUTIVE_QUARTER_MAX_DAYS); + for pair in quarters.windows(2) { + let gap = i64::from(pair[0].period_end) - i64::from(pair[1].period_end); + if gap < min_gap || gap > max_gap { + return None; + } + } + + let currency = &quarters[0].currency; + if !quarters[1..].iter().all(|q| &q.currency == currency) { + return None; + } + + let flows = TtmFlowFields { + revenue: sum_4_flows([ + quarters[0].fields.revenue, + quarters[1].fields.revenue, + quarters[2].fields.revenue, + quarters[3].fields.revenue, + ]), + net_income: sum_4_flows([ + quarters[0].fields.net_income, + quarters[1].fields.net_income, + quarters[2].fields.net_income, + quarters[3].fields.net_income, + ]), + operating_cash_flow: sum_4_flows([ + quarters[0].fields.operating_cash_flow, + quarters[1].fields.operating_cash_flow, + quarters[2].fields.operating_cash_flow, + quarters[3].fields.operating_cash_flow, + ]), + }; + + let has_estimated_lag = quarters.iter().any(|q| q.has_estimated_lag()); + + Some(FundamentalsTtm { + ending_period_end: quarters[0].period_end, + currency: currency.clone(), + flows, + has_estimated_lag, + }) +} + +/// Builds 2D point-in-time [`FundamentalsSnapshot`] records sorted by +/// `(key, effective_known_at_utc_micros)` from bitemporal [`FundamentalsRow`] inputs. +/// +/// Returns [`FundamentalsError::InvalidPeriodLimit`] if `k == 0`. +pub fn build_fundamentals_snapshots( + rows: &[FundamentalsRow], + k: usize, +) -> Result>, FundamentalsError> +where + K: Ord + Clone, +{ + if k == 0 { + return Err(FundamentalsError::InvalidPeriodLimit { k }); + } + if rows.is_empty() { + return Ok(Vec::new()); + } + + let mut order: Vec = (0..rows.len()).collect(); + order.sort_unstable_by(|&a, &b| { + rows[a] + .key + .cmp(&rows[b].key) + .then_with(|| rows[a].known_at_utc_micros.cmp(&rows[b].known_at_utc_micros)) + .then_with(|| rows[a].period_end.cmp(&rows[b].period_end)) + }); + + let mut snapshots: Vec> = Vec::new(); + let total = order.len(); + let mut idx = 0usize; + + while idx < total { + let key = &rows[order[idx]].key; + let mut visible_periods: BTreeMap = BTreeMap::new(); + + while idx < total && &rows[order[idx]].key == key { + let effective_ts = rows[order[idx]].known_at_utc_micros; + + while idx < total + && &rows[order[idx]].key == key + && rows[order[idx]].known_at_utc_micros == effective_ts + { + let row = &rows[order[idx]]; + match visible_periods.get_mut(&row.period_end) { + Some(existing) => existing.apply_update(row), + None => { + visible_periods.insert(row.period_end, ResolvedPeriod::from_row(row)); + } + } + idx += 1; + } + + let periods: Vec = visible_periods + .values() + .rev() + .take(k) + .map(ResolvedPeriod::to_slot) + .collect(); + let ttm = compute_ttm(&visible_periods); + let has_estimated_lag = periods.iter().any(|p| p.has_estimated_lag) + || ttm.as_ref().is_some_and(|t| t.has_estimated_lag); + let known_at_source = if has_estimated_lag { + KNOWN_AT_SOURCE_STATUTORY_LAG + } else { + KNOWN_AT_SOURCE_FILING_TIMESTAMP + }; + + snapshots.push(FundamentalsSnapshot { + key: key.clone(), + effective_known_at_utc_micros: effective_ts, + known_at_source, + has_estimated_lag, + periods, + ttm, + }); + } + } + + Ok(snapshots) +} + +/// Returns the latest [`FundamentalsSnapshot`] for `key` with +/// `effective_known_at_utc_micros <= as_of_micros` (inclusive). +/// +/// Requires `snapshots` to be sorted by `(key, effective_known_at_utc_micros)` (as returned by +/// [`build_fundamentals_snapshots`]). +pub fn as_of<'a, K, Q>( + snapshots: &'a [FundamentalsSnapshot], + key: &Q, + as_of_micros: i64, +) -> Option<&'a FundamentalsSnapshot> +where + K: Borrow + Ord, + Q: Ord + ?Sized, +{ + let pos = snapshots.partition_point(|s| match s.key.borrow().cmp(key) { + Ordering::Less => true, + Ordering::Equal => s.effective_known_at_utc_micros <= as_of_micros, + Ordering::Greater => false, + }); + if pos == 0 { + return None; + } + let candidate = &snapshots[pos - 1]; + if candidate.key.borrow() == key { + Some(candidate) + } else { + None + } +} + +#[cfg(test)] +#[path = "fundamentals_tests.rs"] +mod tests; diff --git a/tools/curate-etl/src/fundamentals_tests.rs b/tools/curate-etl/src/fundamentals_tests.rs new file mode 100644 index 00000000..1d9e0b9d --- /dev/null +++ b/tools/curate-etl/src/fundamentals_tests.rs @@ -0,0 +1,739 @@ +use super::*; +use crate::split::ymd_to_epoch_days; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid test date") +} + +fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8) -> i64 { + let epoch_day = day(y, m, d); + let secs = i64::from(epoch_day) * 86_400 + + i64::from(hour) * 3_600 + + i64::from(minute) * 60 + + i64::from(second); + secs * 1_000_000 +} + +fn filing(key: &str, timefiled: &str, form_type: &str) -> QmFiling { + QmFiling { + key: key.to_string(), + timefiled: timefiled.to_string(), + form_type: form_type.to_string(), + filing_id: None, + url: None, + } +} + +fn obs( + key: &str, + period_end: i32, + fiscal_period: FiscalPeriod, + currency: &str, + report_date: Option, + fields: FundamentalsFields, +) -> FinancialObservation { + FinancialObservation { + key: key.to_string(), + period_end, + fiscal_period, + currency: currency.to_string(), + report_date, + fields, + } +} + +fn fields_rev(rev: f64) -> FundamentalsFields { + FundamentalsFields { + revenue: Some(rev), + net_income: Some(rev * 0.1), + operating_cash_flow: Some(rev * 0.15), + total_assets: Some(rev * 5.0), + total_equity: Some(rev * 2.0), + shares_outstanding: Some(1_000.0), + } +} + +fn venues_map(entries: &[(&str, StatutoryLagVenue)]) -> BTreeMap { + entries + .iter() + .map(|&(k, v)| (k.to_string(), v)) + .collect() +} + +fn assert_reconciliation(build: &FundamentalsBuild) { + let s = &build.stats; + assert_eq!(s.rows_out, build.rows.len()); + assert_eq!( + s.rows_out, + s.rows_linked_to_filing + s.rows_statutory_lag_estimate, + "output provenance mismatch: {s:?}" + ); + assert_eq!( + s.observations_in, + s.rows_out + + s.observations_dropped_unknown_key + + s.observations_dropped_non_finite + + s.observations_dropped_date_out_of_range + + s.observations_dropped_report_date_not_after_period_end + + s.observations_dropped_unanchored_vintage + + s.duplicate_collapsed + + s.duplicate_conflict_dropped, + "observation reconciliation failed: {s:?}" + ); + assert_eq!( + s.filings_in, + s.filings_eligible + + s.filings_dropped_unknown_key + + s.filings_ignored_non_periodic + + s.filings_dropped_invalid_timestamp + + s.filings_dropped_date_out_of_range + + s.filings_dropped_before_period_end, + "filing reconciliation failed: {s:?}" + ); + for pair in build.rows.windows(2) { + assert!( + (&pair[0].key, pair[0].period_end, pair[0].known_at_utc_micros) + < (&pair[1].key, pair[1].period_end, pair[1].known_at_utc_micros), + "rows must be strictly sorted and unique by (key, period_end, known_at_utc_micros)" + ); + } +} + +#[test] +fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + + let p_2023_q3 = day(2023, 9, 30); + let p_2023_q4 = day(2023, 12, 31); + let p_2024_q1 = day(2024, 3, 31); + let p_2024_q2 = day(2024, 6, 30); + + let initial_filings = vec![ + filing("ACME", "2023-11-01T16:15:00 EDT", "10-Q"), + filing("ACME", "2024-02-01T16:15:00 EST", "10-Q"), + filing("ACME", "2024-05-01T16:15:00 EDT", "10-Q"), + filing("ACME", "2024-08-01T16:15:00 EDT", "10-Q"), + ]; + let amendment_filing = filing("ACME", "2024-09-15T17:00:00 EDT", "10-Q/A"); + + let initial_obs = vec![ + obs( + "ACME", + p_2023_q3, + FiscalPeriod::Quarterly, + "USD", + Some(day(2023, 11, 1)), + FundamentalsFields { + revenue: Some(70.0), + net_income: Some(7.0), + operating_cash_flow: Some(10.0), + total_assets: Some(500.0), + total_equity: Some(200.0), + shares_outstanding: Some(100.0), + }, + ), + obs( + "ACME", + p_2023_q4, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 2, 1)), + FundamentalsFields { + revenue: Some(80.0), + net_income: Some(8.0), + operating_cash_flow: Some(12.0), + total_assets: Some(520.0), + total_equity: Some(210.0), + shares_outstanding: Some(100.0), + }, + ), + obs( + "ACME", + p_2024_q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + FundamentalsFields { + revenue: Some(100.0), + net_income: Some(10.0), + operating_cash_flow: Some(15.0), + total_assets: Some(540.0), + total_equity: Some(220.0), + shares_outstanding: Some(100.0), + }, + ), + obs( + "ACME", + p_2024_q2, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 8, 1)), + FundamentalsFields { + revenue: Some(120.0), + net_income: Some(12.0), + operating_cash_flow: Some(18.0), + total_assets: Some(560.0), + total_equity: Some(230.0), + shares_outstanding: Some(100.0), + }, + ), + ]; + + // Q1 amendment filed on 2024-09-15 (168 days after Q1 period end, beyond 75d window) + // Restates revenue from 100 -> 110 and omits operating_cash_flow & total_assets (None). + let q1_amendment = obs( + "ACME", + p_2024_q1, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 9, 15)), + FundamentalsFields { + revenue: Some(110.0), + net_income: Some(11.0), + operating_cash_flow: None, + total_assets: None, + total_equity: Some(225.0), + shares_outstanding: None, + }, + ); + + let mut full_obs = initial_obs.clone(); + full_obs.push(q1_amendment); + let mut full_filings = initial_filings.clone(); + full_filings.push(amendment_filing); + + let full_build = build_fundamentals_rows(full_obs, full_filings, &venues); + assert_reconciliation(&full_build); + assert_eq!(full_build.stats.rows_out, 5); + assert_eq!(full_build.stats.rows_linked_to_filing, 5); + assert_eq!(full_build.stats.rows_statutory_lag_estimate, 0); + + let full_snaps = build_fundamentals_snapshots(&full_build.rows, 4).unwrap(); + assert_eq!(full_snaps.len(), 5); + + let ts_q2 = utc_micros(2024, 8, 1, 20, 15, 0); + let ts_amend = utc_micros(2024, 9, 15, 21, 0, 0); + + // As-of strictly between Q2 filing and Q1 restatement (also check exact Q2 timestamp). + for probe in [ts_q2, ts_amend - 1] { + let snap = as_of(&full_snaps, "ACME", probe).expect("snapshot visible after Q2"); + assert_eq!(snap.effective_known_at_utc_micros, ts_q2); + assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!snap.has_estimated_lag); + assert_eq!(snap.periods[0].period_end, p_2024_q2); + assert_eq!(snap.periods[0].fields.revenue, Some(120.0)); + assert_eq!(snap.periods[1].period_end, p_2024_q1); + assert_eq!(snap.periods[1].fields.revenue, Some(100.0)); + assert_eq!(snap.periods[1].fields.operating_cash_flow, Some(15.0)); + let ttm = snap.ttm.as_ref().expect("4 consecutive quarters"); + assert_eq!(ttm.ending_period_end, p_2024_q2); + assert_eq!(ttm.flows.revenue, Some(370.0)); + assert_eq!(ttm.flows.net_income, Some(37.0)); + assert_eq!(ttm.flows.operating_cash_flow, Some(55.0)); + } + + // As-of at and after the Q1 restatement: Q2 stays latest and unchanged, Q1 updated + inherited, TTM updated. + for probe in [ts_amend, ts_amend + 1_000_000] { + let snap = as_of(&full_snaps, "ACME", probe).expect("snapshot visible at/after amendment"); + assert_eq!(snap.effective_known_at_utc_micros, ts_amend); + assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!snap.has_estimated_lag); + assert_eq!(snap.periods[0].period_end, p_2024_q2); + assert_eq!(snap.periods[0].fields.revenue, Some(120.0)); + assert_eq!(snap.periods[0].fields.total_assets, Some(560.0)); + assert_eq!(snap.periods[1].period_end, p_2024_q1); + assert_eq!(snap.periods[1].known_at_utc_micros, ts_amend); + assert_eq!(snap.periods[1].fields.revenue, Some(110.0)); + assert_eq!(snap.periods[1].fields.net_income, Some(11.0)); + // Omitted fields inherited from original Q1 + assert_eq!(snap.periods[1].fields.operating_cash_flow, Some(15.0)); + assert_eq!(snap.periods[1].fields.total_assets, Some(540.0)); + assert_eq!(snap.periods[1].fields.shares_outstanding, Some(100.0)); + assert_eq!(snap.periods[1].fields.total_equity, Some(225.0)); + let ttm = snap.ttm.as_ref().expect("4 consecutive quarters"); + assert_eq!(ttm.ending_period_end, p_2024_q2); + assert_eq!(ttm.flows.revenue, Some(380.0)); + assert_eq!(ttm.flows.net_income, Some(38.0)); + assert_eq!(ttm.flows.operating_cash_flow, Some(55.0)); + } + + // Truncation test: rebuild without future amendment and its filing; all earlier snapshots identical. + let trunc_build = build_fundamentals_rows(initial_obs, initial_filings, &venues); + assert_reconciliation(&trunc_build); + let trunc_snaps = build_fundamentals_snapshots(&trunc_build.rows, 4).unwrap(); + assert_eq!(trunc_snaps.len(), 4); + assert_eq!(&full_snaps[..4], &trunc_snaps[..]); +} + +#[test] +fn known_at_filing_linking_covers_all_periodic_forms_zones_windows_and_exclusions() { + let venues = venues_map(&[ + ("US_Q", StatutoryLagVenue::UsTsx), + ("US_A", StatutoryLagVenue::UsTsx), + ("CA_40F", StatutoryLagVenue::UsTsx), + ("SEDAR_Q", StatutoryLagVenue::TsxvCse), + ("SEDAR_A", StatutoryLagVenue::TsxvCse), + ("WIN_Q", StatutoryLagVenue::UsTsx), + ("WIN_A", StatutoryLagVenue::UsTsx), + ("NOISE", StatutoryLagVenue::UsTsx), + ]); + + let filings = vec![ + // Late-evening EDT filing whose UTC date is the next day (2024-05-11T01:30:00Z) + filing("US_Q", "2024-05-10T21:30:00 EDT", "10-Q"), + // EST annual 10-K + filing("US_A", "2024-03-01T08:15:30 EST", "10-K"), + // 40-F annual + filing("CA_40F", "2024-03-15T14:00:00 EDT", "40-F"), + // SEDAR interim & annual + filing("SEDAR_Q", "2024-05-20T18:00:00 EDT", "Interim financial statements/report - English"), + filing("SEDAR_A", "2024-04-20T12:30:00 EDT", "Annual financial statements - English"), + // Window boundary filings for undated quarterly (period_end = 2024-03-31 -> +75d = 2024-06-14, +76d = 2024-06-15) + // Also add an earlier 10-Q/A on 2024-05-01 which undated observation must ignore! + filing("WIN_Q", "2024-05-01T10:00:00 EDT", "10-Q/A"), + filing("WIN_Q", "2024-06-14T11:00:00 EDT", "10-Q"), + // Window boundary for undated annual (period_end = 2023-12-31 -> +150d = 2024-05-29, +151d = 2024-05-30) + filing("WIN_A", "2024-05-29T15:00:00 EDT", "10-K"), + // Non-periodic 8-K, wrong kind (10-K for quarterly), and wrong listing + filing("NOISE", "2024-05-05T09:00:00 EDT", "8-K"), + filing("NOISE", "2024-05-05T09:30:00 EDT", "News release"), + filing("NOISE", "2024-05-05T10:00:00 EDT", "10-K"), + ]; + + let observations = vec![ + // Same-day match across UTC midnight rollover (ET date = 2024-05-10) + obs("US_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", Some(day(2024, 5, 10)), fields_rev(10.0)), + obs("US_A", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(20.0)), + obs("CA_40F", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(30.0)), + obs("SEDAR_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(40.0)), + obs("SEDAR_A", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(50.0)), + // Exact +75d inclusive boundary -> links to 2024-06-14 10-Q (skipping 2024-05-01 10-Q/A) + obs("WIN_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(60.0)), + // Exact +76d (period_end = 2024-03-30 -> 2024-06-14 is +76d) -> outside window, falls back! + obs("WIN_Q", day(2024, 3, 30), FiscalPeriod::Quarterly, "USD", None, fields_rev(61.0)), + // Exact +150d inclusive boundary -> links to 2024-05-29 10-K + obs("WIN_A", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(70.0)), + // Exact +151d (period_end = 2023-12-30 -> 2024-05-29 is +151d) -> outside window, falls back! + obs("WIN_A", day(2023, 12, 30), FiscalPeriod::Annual, "USD", None, fields_rev(71.0)), + // NOISE quarterly: 8-K, News release, and 10-K must NOT link -> statutory lag fallback + obs("NOISE", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(80.0)), + ]; + + let built = build_fundamentals_rows(observations, filings, &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.filings_ignored_non_periodic, 2); + assert_eq!(built.stats.rows_linked_to_filing, 7); + assert_eq!(built.stats.rows_statutory_lag_estimate, 3); + + let find = |k: &str, pe: i32| { + built + .rows + .iter() + .find(|r| r.key == k && r.period_end == pe) + .expect("row present") + }; + + assert_eq!(find("US_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 11, 1, 30, 0)); + assert_eq!(find("US_Q", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(find("US_A", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 1, 13, 15, 30)); + assert_eq!(find("CA_40F", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 15, 18, 0, 0)); + assert_eq!(find("SEDAR_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 20, 22, 0, 0)); + assert_eq!(find("SEDAR_A", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 4, 20, 16, 30, 0)); + + // Window boundaries + assert_eq!(find("WIN_Q", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(find("WIN_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 6, 14, 15, 0, 0)); + assert_eq!(find("WIN_Q", day(2024, 3, 30)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert_eq!(find("WIN_A", day(2023, 12, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(find("WIN_A", day(2023, 12, 30)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + + // 8-K and wrong-kind 10-K did not link + assert_eq!(find("NOISE", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); +} + +#[test] +fn statutory_lag_fallback_exact_offsets_dst_boundary_and_unanchored_vintage() { + let venues = venues_map(&[ + ("US", StatutoryLagVenue::UsTsx), + ("VN", StatutoryLagVenue::TsxvCse), + ]); + + // Spring DST 2024 is Sunday 2024-03-10: + // - 2024-01-24 + 45d = 2024-03-09 (EST, UTC-5) -> 16:05 ET == 21:05 UTC + // - 2024-01-25 + 45d = 2024-03-10 (EDT, UTC-4) -> 16:05 ET == 20:05 UTC + let observations = vec![ + // US/TSX Quarterly (+45d) before DST + obs("US", day(2024, 1, 24), FiscalPeriod::Quarterly, "USD", None, fields_rev(10.0)), + // US/TSX Quarterly (+45d) on spring DST Sunday + obs("US", day(2024, 1, 25), FiscalPeriod::Quarterly, "USD", None, fields_rev(11.0)), + // US/TSX Annual (+90d): 2023-12-31 + 90d = 2024-03-30 (EDT, 2024 is leap year) + obs("US", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(20.0)), + // TSXV/CSE Quarterly (+60d): 2024-03-31 + 60d = 2024-05-30 (EDT) + obs("VN", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(30.0)), + // TSXV/CSE Annual (+120d): 2023-12-31 + 120d = 2024-04-29 (EDT) + obs("VN", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(40.0)), + // Dated record with no same-day filing and report_date == lag_date -> allowed fallback + obs( + "US", + day(2024, 6, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 6, 30) + 45), + fields_rev(50.0), + ), + // Dated record with no same-day filing and report_date > lag_date -> dropped as unanchored vintage! + obs( + "US", + day(2024, 9, 30), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 9, 30) + 46), + fields_rev(60.0), + ), + ]; + + let built = build_fundamentals_rows(observations, Vec::>::new(), &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.rows_out, 6); + assert_eq!(built.stats.rows_statutory_lag_estimate, 6); + assert_eq!(built.stats.observations_dropped_unanchored_vintage, 1); + + let find = |k: &str, pe: i32| { + built + .rows + .iter() + .find(|r| r.key == k && r.period_end == pe) + .expect("row present") + }; + + assert_eq!(find("US", day(2024, 1, 24)).known_at_utc_micros, utc_micros(2024, 3, 9, 21, 5, 0)); + assert_eq!(find("US", day(2024, 1, 25)).known_at_utc_micros, utc_micros(2024, 3, 10, 20, 5, 0)); + assert_eq!(find("US", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 30, 20, 5, 0)); + assert_eq!(find("VN", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 30, 20, 5, 0)); + assert_eq!(find("VN", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 4, 29, 20, 5, 0)); + assert_eq!( + find("US", day(2024, 6, 30)).known_at_utc_micros, + et_to_utc_micros(day(2024, 6, 30) + 45, 16, 5, 0).unwrap() + ); +} + +#[test] +fn ttm_handles_gaps_fy_rows_currency_missing_overflow_carry_forward_and_provenance() { + // 1. Quarter spacing boundaries (76 rejected, 77 accepted, 105 accepted, 106 rejected) + let make_row = |key: &str, pe: i32, kind: FiscalPeriod, curr: &str, ts: i64, src: &'static str, fields: FundamentalsFields| { + FundamentalsRow { + key: key.to_string(), + period_end: pe, + fiscal_period: kind, + currency: curr.to_string(), + known_at_utc_micros: ts, + known_at_source: src, + fields, + } + }; + + let base = day(2023, 1, 1); + // Exact 77-day spacing -> TTM computed + let rows_77 = vec![ + make_row("G77", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), + make_row("G77", base + 77, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), + make_row("G77", base + 154, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), + make_row("G77", base + 231, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), + ]; + let snaps_77 = build_fundamentals_snapshots(&rows_77, 2).unwrap(); + assert!(snaps_77[2].ttm.is_none()); // only 3 quarters + let ttm_77 = snaps_77[3].ttm.as_ref().expect("77d spacing is consecutive"); + assert_eq!(ttm_77.flows.revenue, Some(100.0)); + assert_eq!(ttm_77.ending_period_end, base + 231); + // Stock fields remain period values (not summed) + assert_eq!(snaps_77[3].periods[0].fields.total_assets, Some(200.0)); + assert_eq!(snaps_77[3].periods[0].fields.shares_outstanding, Some(1_000.0)); + + // 76-day gap -> None + let mut rows_76 = rows_77.clone(); + rows_76[3].period_end = base + 154 + 76; + assert!(build_fundamentals_snapshots(&rows_76, 4).unwrap()[3].ttm.is_none()); + + // 105-day spacing -> Some, 106-day gap -> None + let rows_105 = vec![ + make_row("G105", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), + make_row("G105", base + 105, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), + make_row("G105", base + 210, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), + make_row("G105", base + 315, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), + ]; + assert!(build_fundamentals_snapshots(&rows_105, 4).unwrap()[3].ttm.is_some()); + let mut rows_106 = rows_105.clone(); + rows_106[3].period_end = base + 210 + 106; + assert!(build_fundamentals_snapshots(&rows_106, 4).unwrap()[3].ttm.is_none()); + + // 2. Intervening FY row occupies a snapshot slot while TTM still uses the 4 standalone quarters + let rows_fy = vec![ + make_row("FY", day(2023, 3, 31), FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), + make_row("FY", day(2023, 6, 30), FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), + make_row("FY", day(2023, 9, 30), FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), + make_row("FY", day(2023, 12, 31), FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), + make_row("FY", day(2024, 1, 1), FiscalPeriod::Annual, "USD", 5, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)), + ]; + let snaps_fy = build_fundamentals_snapshots(&rows_fy, 2).unwrap(); + let last_fy = snaps_fy.last().unwrap(); + assert_eq!(last_fy.periods[0].fiscal_period, FiscalPeriod::Annual); + assert_eq!(last_fy.ttm.as_ref().unwrap().flows.revenue, Some(100.0)); + + // 3. Currency mismatch across 4 quarters -> TTM is None + let mut rows_curr = rows_77.clone(); + rows_curr[2].currency = "CAD".to_string(); + assert!(build_fundamentals_snapshots(&rows_curr, 4).unwrap()[3].ttm.is_none()); + + // 4. Missing flow input & overflow -> per-field None while other flow fields still sum + let mut rows_edge = rows_77.clone(); + rows_edge[1].fields.net_income = None; + rows_edge[0].fields.operating_cash_flow = Some(f64::MAX); + rows_edge[1].fields.operating_cash_flow = Some(f64::MAX); + let ttm_edge = build_fundamentals_snapshots(&rows_edge, 4).unwrap()[3] + .ttm + .clone() + .expect("ttm present"); + assert_eq!(ttm_edge.flows.revenue, Some(100.0)); + assert_eq!(ttm_edge.flows.net_income, None); + assert_eq!(ttm_edge.flows.operating_cash_flow, None); + + // 5. Carry-forward stays within same (period_end, kind, currency) and retains estimated provenance + let rows_cf = vec![ + // Initial Q1 with statutory_lag_estimate + make_row( + "CF", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "USD", + 10, + KNOWN_AT_SOURCE_STATUTORY_LAG, + FundamentalsFields { + revenue: Some(100.0), + net_income: Some(10.0), + operating_cash_flow: None, + total_assets: Some(500.0), + total_equity: None, + shares_outstanding: None, + }, + ), + // Filing restatement leaves net_income=None -> inherits net_income from estimated version -> still estimated! + make_row( + "CF", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "USD", + 20, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + FundamentalsFields { + revenue: Some(105.0), + net_income: None, + operating_cash_flow: Some(15.0), + total_assets: Some(505.0), + total_equity: None, + shares_outstanding: None, + }, + ), + // Currency change to CAD at t=30 -> does NOT carry forward USD fields; now purely filing_timestamp! + make_row( + "CF", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "CAD", + 30, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + FundamentalsFields { + revenue: Some(140.0), + net_income: None, + operating_cash_flow: None, + total_assets: None, + total_equity: None, + shares_outstanding: None, + }, + ), + ]; + let snaps_cf = build_fundamentals_snapshots(&rows_cf, 2).unwrap(); + assert!(snaps_cf[0].has_estimated_lag); + assert_eq!(snaps_cf[1].periods[0].fields.net_income, Some(10.0)); + assert!(snaps_cf[1].periods[0].has_estimated_lag); + assert!(snaps_cf[1].has_estimated_lag); + assert_eq!(snaps_cf[1].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + // After currency change, no carry-forward from USD estimated row + assert_eq!(snaps_cf[2].periods[0].fields.net_income, None); + assert!(!snaps_cf[2].periods[0].has_estimated_lag); + assert!(!snaps_cf[2].has_estimated_lag); + assert_eq!(snaps_cf[2].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + + // 6. Estimated TTM contributor outside displayed k=2 slots flags the snapshot as estimated + let rows_ttm_est = vec![ + make_row("EST", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_STATUTORY_LAG, fields_rev(10.0)), + make_row("EST", base + 90, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), + make_row("EST", base + 180, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), + make_row("EST", base + 270, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), + ]; + let snaps_est = build_fundamentals_snapshots(&rows_ttm_est, 2).unwrap(); + let s4 = &snaps_est[3]; + assert_eq!(s4.periods.len(), 2); + assert!(s4.periods.iter().all(|p| !p.has_estimated_lag)); + assert!(s4.ttm.as_ref().unwrap().has_estimated_lag); + assert!(s4.has_estimated_lag); + assert_eq!(s4.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + + // 7. Multiple updates at the same timestamp produce one combined snapshot + as_of edge cases + let rows_same_ts = vec![ + make_row("M", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), + make_row("M", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), + ]; + let snaps_same = build_fundamentals_snapshots(&rows_same_ts, 4).unwrap(); + assert_eq!(snaps_same.len(), 1); + assert_eq!(snaps_same[0].periods.len(), 2); + assert!(as_of(&snaps_same, "M", 99).is_none()); + assert_eq!(as_of(&snaps_same, "M", 100), Some(&snaps_same[0])); + assert!(as_of(&snaps_same, "UNKNOWN", 100).is_none()); + + // 8. k == 0 rejected with typed error + assert_eq!( + build_fundamentals_snapshots(&rows_same_ts, 0), + Err(FundamentalsError::InvalidPeriodLimit { k: 0 }) + ); +} + +#[test] +fn robustness_bad_rows_dedup_conflicts_and_input_order_determinism() { + let venues = venues_map(&[ + ("A", StatutoryLagVenue::UsTsx), + ("B", StatutoryLagVenue::TsxvCse), + ]); + + let observations = vec![ + // Valid linked observation (with -0.0 normalized to 0.0) + exact duplicate + obs( + "A", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + FundamentalsFields { + revenue: Some(-0.0), + net_income: Some(5.0), + operating_cash_flow: Some(6.0), + total_assets: Some(100.0), + total_equity: Some(50.0), + shares_outstanding: Some(10.0), + }, + ), + obs( + "A", + day(2024, 3, 31), + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 1)), + FundamentalsFields { + revenue: Some(0.0), + net_income: Some(5.0), + operating_cash_flow: Some(6.0), + total_assets: Some(100.0), + total_equity: Some(50.0), + shares_outstanding: Some(10.0), + }, + ), + // Conflicting duplicate pair on B (same period_end & known_at, differing revenue) + obs("B", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(10.0)), + obs("B", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(11.0)), + // Unknown key + obs("UNKNOWN", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)), + // Non-finite values (NaN, +inf, -inf) + obs( + "A", + day(2024, 6, 30), + FiscalPeriod::Quarterly, + "USD", + None, + FundamentalsFields { + revenue: Some(f64::NAN), + ..Default::default() + }, + ), + obs( + "A", + day(2024, 6, 30), + FiscalPeriod::Quarterly, + "USD", + None, + FundamentalsFields { + total_assets: Some(f64::INFINITY), + ..Default::default() + }, + ), + // Out-of-range period_end, report_date, and lag_date + obs("A", day(2007, 12, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)), + obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2031, 1, 1)), fields_rev(1.0)), + obs("A", day(2030, 12, 1), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)), + // Explicit report_date <= period_end + obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2024, 6, 30)), fields_rev(1.0)), + // Valid second period for A to verify early filing anchored earlier period, not dropped + obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2024, 8, 1)), fields_rev(25.0)), + ]; + + let filings = vec![ + // Legitimate filings for A Q1 and Q2 (Q1 filing predates Q2 period_end, must NOT be dropped!) + filing("A", "2024-05-01T16:10:00 EDT", "10-Q"), + filing("A", "2024-08-01T16:10:00 EDT", "10-Q"), + // Early filing on or before A's earliest quarterly period_end (2024-03-31) -> dropped + filing("A", "2024-03-31T16:00:00 EDT", "10-Q"), + // Unknown key + filing("UNKNOWN", "2024-05-01T16:10:00 EDT", "10-Q"), + // Non-periodic + filing("A", "2024-05-02T16:10:00 EDT", "8-K"), + // Invalid timestamps (malformed, unknown zone, invalid date) + filing("A", "not-a-date", "10-Q"), + filing("A", "2024-05-01T16:10:00 UTC", "10-Q"), + filing("A", "2024-02-30T16:10:00 EST", "10-Q"), + // Out-of-range Eastern filing date + filing("A", "2007-12-31T16:10:00 EST", "10-Q"), + ]; + + let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); + assert_reconciliation(&built); + + assert_eq!(built.stats.observations_in, 12); + assert_eq!(built.stats.rows_out, 2); + assert_eq!(built.stats.keys_out, 1); + assert_eq!(built.stats.rows_linked_to_filing, 2); + assert_eq!(built.stats.rows_statutory_lag_estimate, 0); + assert_eq!(built.stats.observations_dropped_unknown_key, 1); + assert_eq!(built.stats.observations_dropped_non_finite, 2); + assert_eq!(built.stats.observations_dropped_date_out_of_range, 3); + assert_eq!(built.stats.observations_dropped_report_date_not_after_period_end, 1); + assert_eq!(built.stats.duplicate_collapsed, 1); + assert_eq!(built.stats.duplicate_conflict_dropped, 2); + + assert_eq!(built.stats.filings_in, 9); + assert_eq!(built.stats.filings_eligible, 2); + assert_eq!(built.stats.filings_dropped_unknown_key, 1); + assert_eq!(built.stats.filings_ignored_non_periodic, 1); + assert_eq!(built.stats.filings_dropped_invalid_timestamp, 3); + assert_eq!(built.stats.filings_dropped_date_out_of_range, 1); + assert_eq!(built.stats.filings_dropped_before_period_end, 1); + + // -0.0 normalized to +0.0 + assert_eq!(built.rows[0].fields.revenue.unwrap().to_bits(), 0.0_f64.to_bits()); + + // Input-order determinism: reversed and rotated inputs yield identical rows, snapshots, and stats + let mut obs_rev = observations.clone(); + obs_rev.reverse(); + let mut fil_rev = filings.clone(); + fil_rev.reverse(); + let built_rev = build_fundamentals_rows(obs_rev, fil_rev, &venues); + assert_eq!(built, built_rev); + + let mut obs_rot = observations; + obs_rot.rotate_left(5); + let mut fil_rot = filings; + fil_rot.rotate_left(4); + let built_rot = build_fundamentals_rows(obs_rot, fil_rot, &venues); + assert_eq!(built, built_rot); + + let snaps_a = build_fundamentals_snapshots(&built.rows, 4).unwrap(); + let snaps_b = build_fundamentals_snapshots(&built_rev.rows, 4).unwrap(); + assert_eq!(snaps_a, snaps_b); +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index eaefb854..83d63a85 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -14,6 +14,7 @@ pub mod bson_te_market_data; pub mod cli; pub mod corporate_actions; pub mod events; +pub mod fundamentals; pub mod fx; pub mod mongo_safety; pub mod mongo_stream; @@ -100,6 +101,17 @@ pub use events::{ EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, }; +pub use fundamentals::{ + as_of as fundamentals_as_of, build_fundamentals_rows, build_fundamentals_snapshots, + FinancialObservation, FiscalPeriod, FundamentalsBuild, FundamentalsError, FundamentalsFields, + FundamentalsPeriodSlot, FundamentalsRow, FundamentalsSnapshot, FundamentalsStats, + FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, ANNUAL_FILING_LINK_WINDOW_DAYS, + FUNDAMENTALS_FALLBACK_HOUR_ET, FUNDAMENTALS_FALLBACK_MINUTE_ET, + QUARTERLY_FILING_LINK_WINDOW_DAYS, STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, + STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, STATUTORY_LAG_US_TSX_ANNUAL_DAYS, + STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, TTM_CONSECUTIVE_QUARTER_MAX_DAYS, + TTM_CONSECUTIVE_QUARTER_MIN_DAYS, TTM_QUARTER_COUNT, +}; pub use fx::{ build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource, FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index aa9acace..04d3c213 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -11,7 +11,7 @@ use curate_etl::bench::{ run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark, run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark, run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark, - run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark, + run_fundamentals_benchmark, run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark, run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark, @@ -482,6 +482,50 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchFundamentals(rows)) => { + let report = match run_fundamentals_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: fundamentals benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-fundamentals"); + println!( + " input: rows={} filings={} keys={}", + report.rows, report.filings_in, report.key_count + ); + println!( + " build: rows_out={} keys_out={} snapshots_out={} rows={:.2} ms snapshots={:.2} ms total={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", + report.rows_out, + report.keys_out, + report.snapshots_out, + report.rows_elapsed_ms, + report.snapshots_elapsed_ms, + report.total_elapsed_ms, + report.rows_per_sec, + report.ns_per_row, + report.checksum + ); + println!( + " stats: linked={} statutory_lag={} dup_collapsed={} dup_conflict={} obs_unknown_key={} obs_non_finite={} obs_oor={} obs_rd_le_pe={} obs_unanchored={} filings_eligible={} filings_non_periodic={} filings_bad_ts={} filings_oor={} filings_before_pe={}", + report.stats.rows_linked_to_filing, + report.stats.rows_statutory_lag_estimate, + report.stats.duplicate_collapsed, + report.stats.duplicate_conflict_dropped, + report.stats.observations_dropped_unknown_key, + report.stats.observations_dropped_non_finite, + report.stats.observations_dropped_date_out_of_range, + report.stats.observations_dropped_report_date_not_after_period_end, + report.stats.observations_dropped_unanchored_vintage, + report.stats.filings_eligible, + report.stats.filings_ignored_non_periodic, + report.stats.filings_dropped_invalid_timestamp, + report.stats.filings_dropped_date_out_of_range, + report.stats.filings_dropped_before_period_end + ); + ExitCode::SUCCESS + } Ok(CliAction::BenchProviderMapping(lookups)) => { let report = match run_provider_mapping_benchmark(lookups) { Ok(report) => report, From bf65712a380d07b369c7484f6bc69027ed6bc3d7 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 00:29:11 -0500 Subject: [PATCH 19/21] =?UTF-8?q?T-132:=20M2.2a=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20point-in-time=20fundamentals=20builder=20(`qmF?= =?UTF-8?q?inancials`=20=C3=97=20`qmFilings`=20`known=5Fat`=20link=20+=20s?= =?UTF-8?q?tatutory-lag=20fallback=20=E2=86=92=20bitemporal=20rows=20?= =?UTF-8?q?=E2=86=92=202D=20PIT=20snapshots=20+=20TTM)=20with=20restatemen?= =?UTF-8?q?t=20fixture=20test=20and=20local=20benchmark=20(no=20new=20crat?= =?UTF-8?q?es)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/README.md | 11 +- tools/curate-etl/src/bench.rs | 156 +++++++++++++++--- tools/curate-etl/src/fundamentals.rs | 181 +++++++++++++++------ tools/curate-etl/src/fundamentals_tests.rs | 169 +++++++++++++++++++ tools/curate-etl/src/main.rs | 3 +- 5 files changed, 439 insertions(+), 81 deletions(-) diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 9bed4735..15034a84 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1564,14 +1564,14 @@ Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals. - Stock fields (point-in-time values, never summed for TTM): `total_assets`, `total_equity`, `shares_outstanding`. - **Stage 1 (`build_fundamentals_rows`):** joins `FinancialObservation` against periodic `events::QmFiling` records (reusing `events::classify_form_type`, `FilingFormGroup::is_periodic_financial_report`, and `events::parse_filing_timefiled`) using an ordered `BTreeMap` (`UsTsx` vs `TsxvCse`). - `10-Q` / SEDAR `Interim financial statements` map to `FiscalPeriod::Quarterly`; `10-K` / `40-F` / SEDAR `Annual financial statements` map to `FiscalPeriod::Annual`; non-periodic forms (`8-K`, `News release`, `MD&A`, etc.) are never linked. - - **Dated observations (`report_date: Some(rd)`):** links to the earliest matching periodic filing (amended or unamended) on that Eastern calendar date (`et_date == rd`, strictly after `period_end`), allowing late restatements/amendments beyond the inference window. If unlinked and `rd > lag_date`, the observation is dropped (`observations_dropped_unanchored_vintage`) rather than backdated. + - **Dated observations (`report_date: Some(rd)`):** links to the earliest matching periodic filing (amended or unamended) on that Eastern calendar date (`et_date == rd`, strictly after `period_end`), allowing late restatements/amendments beyond the inference window. If unlinked and `rd > lag_date`, the observation is dropped (`observations_dropped_unanchored_vintage`) rather than backdated. If a dated statutory-lag estimate for `(key, period_end, fiscal_period)` would become visible at or after a newer dated version (`rd_b > rd_a`, `known_at_b <= lag_micros`) of the same statement, the stale estimate is dropped (`observations_dropped_stale_estimate`) so an older vintage never rolls a newer filing backward. - **Undated observations (`report_date: None`):** links to the earliest matching **non-amended** periodic filing strictly after `period_end` within inclusive heuristic windows of `QUARTERLY_FILING_LINK_WINDOW_DAYS = 75` or `ANNUAL_FILING_LINK_WINDOW_DAYS = 150` calendar days (sampled `qmFilings` carries no statement-period field). - **Statutory-lag fallback:** unlinked rows receive `period_end + lag_days` (`+45d` Q / `+90d` FY for `UsTsx`; `+60d` Q / `+120d` FY for `TsxvCse`) at `16:05:00 America/Toronto` via `shorts::et_to_utc_micros`, tagged `known_at_source = "statutory_lag_estimate"`. - **Validation, deduplication & determinism:** validates dates against `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE` (`2008-01-01..=2030-12-31`), drops bad rows into per-category `FundamentalsStats` counters without panicking, normalizes `-0.0` to `0.0`, collapses exact duplicates, discards conflicting `(key, period_end, known_at_utc_micros)` groups, preserves distinct `known_at_utc_micros` restatement versions, and emits rows strictly sorted by `(key, period_end, known_at_utc_micros)`. - **Stage 2 (`build_fundamentals_snapshots`, `fundamentals_as_of` / `fundamentals::as_of`):** - Sweeps rows in `(key, known_at_utc_micros, period_end)` order, applying all updates at a timestamp before emitting one `FundamentalsSnapshot` with the latest `k` (`k >= 1`) visible periods in descending `period_end` order. - Carries `None` fields forward only from the prior visible version of the same `(period_end, fiscal_period, currency)`, retaining per-field provenance so a snapshot is flagged `has_estimated_lag = true` (`known_at_source = "statutory_lag_estimate"`) whenever any visible slot or any quarter contributing to TTM used an estimate. - - Computes 4-quarter TTM flow sums independently of `k` from the 4 latest visible standalone quarters when adjacent `period_end` gaps are `77..=105` calendar days (`TTM_CONSECUTIVE_QUARTER_MIN_DAYS..=TTM_CONSECUTIVE_QUARTER_MAX_DAYS`) and all 4 share one currency. + - Resolves standalone quarterly versions separately from `FY` rows (so an annual report sharing December 31 with standalone `Q4` never erases `Q4` from TTM) and computes 4-quarter TTM flow sums independently of `k` from the 4 latest visible standalone quarters when adjacent `period_end` gaps are `77..=105` calendar days (`TTM_CONSECUTIVE_QUARTER_MIN_DAYS..=TTM_CONSECUTIVE_QUARTER_MAX_DAYS`) and all 4 share one currency. - `as_of(snapshots, key, as_of_micros)` performs an inclusive `O(log N)` binary search on `(key, effective_known_at_utc_micros)`. ### `bench-fundamentals` @@ -1582,11 +1582,10 @@ Fixed-seed (`SplitMix64`), offline benchmark exercising both venue classes, link cargo run -p curate-etl --release --offline -- bench-fundamentals [rows] ``` -Measured locally (`2026-12-01`, default `rows = 100000`, `filings = 79157`, `keys = 2500`, `rows_out = 97106`, `snapshots_out = 97105`, deterministic checksum `0x078d99c42d5f200b`): +Measured locally (`2026-12-01`, default `rows = 100000`, `filings = 79157`, `keys = 2500`, `rows_out = 97106`, `snapshots_out = 97105`, deterministic checksum `0xd5f693a28da4d1f0` hashing all row fields, ordered snapshot slots, TTM flows, and provenance): -- **Run 1:** Stage 1 `47.19 ms`, Stage 2 `35.75 ms`, total `82.94 ms` (`1,205,683 rows/s`, `829.41 ns/row`) -- **Run 2:** Stage 1 `43.89 ms`, Stage 2 `37.88 ms`, total `81.78 ms` (`1,222,862 rows/s`, `817.75 ns/row`) -- **500k scale check (`rows = 500000`, `filings = 395406`, `keys = 12500`, `rows_out = 485524`, `snapshots_out = 485518`, checksum `0x44fda3cd5f82ce5e`):** Stage 1 `277.89 ms`, Stage 2 `212.92 ms`, total `490.81 ms` (`1,018,714 rows/s`, `981.63 ns/row`) +- **Run 1:** Stage 1 `47.63 ms`, Stage 2 `41.81 ms`, total `89.44 ms` (`1,118,108 rows/s`, `894.37 ns/row`) +- **Run 2:** Stage 1 `44.34 ms`, Stage 2 `39.73 ms`, total `84.07 ms` (`1,189,459 rows/s`, `840.72 ns/row`) ## Exporting Input Files (`data-pipeline`) diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 89369cbb..aab8346a 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -11159,27 +11159,7 @@ pub fn run_fundamentals_benchmark( let total_elapsed_secs = rows_elapsed_secs + snaps_elapsed_secs; let (rows_per_sec, ns_per_row) = compute_rates(rows, total_elapsed_secs); - let mut hash = 0u64; - for row in &built.rows { - hash = mix_u64(hash, row.key as u64); - hash = mix_u64(hash, row.period_end as u64); - hash = mix_u64(hash, row.known_at_utc_micros as u64); - hash = mix_u64(hash, row.fiscal_period as u64); - hash = mix_u64(hash, row.fields.revenue.map_or(0, f64::to_bits)); - hash = mix_u64(hash, row.fields.total_assets.map_or(0, f64::to_bits)); - } - for snap in &snapshots { - hash = mix_u64(hash, snap.key as u64); - hash = mix_u64(hash, snap.effective_known_at_utc_micros as u64); - hash = mix_u64(hash, u64::from(snap.has_estimated_lag)); - hash = mix_u64(hash, snap.periods.len() as u64); - if let Some(ttm) = &snap.ttm { - hash = mix_u64(hash, ttm.ending_period_end as u64); - hash = mix_u64(hash, ttm.flows.revenue.map_or(0, f64::to_bits)); - hash = mix_u64(hash, u64::from(ttm.has_estimated_lag)); - } - } - let checksum = black_box(hash); + let checksum = black_box(hash_fundamentals_outputs(&built.rows, &snapshots)); Ok(FundamentalsBenchReport { rows, @@ -11198,6 +11178,81 @@ pub fn run_fundamentals_benchmark( }) } +#[inline] +fn mix_opt_f64(hash: u64, value: Option) -> u64 { + match value { + None => mix_u64(hash, 0), + Some(v) => mix_u64(mix_u64(hash, 1), v.to_bits()), + } +} + +#[inline] +fn mix_str(mut hash: u64, value: &str) -> u64 { + hash = mix_u64(hash, value.len() as u64); + for byte in value.bytes() { + hash = mix_u64(hash, u64::from(byte)); + } + hash +} + +#[inline] +fn mix_fundamentals_fields(mut hash: u64, fields: &FundamentalsFields) -> u64 { + hash = mix_opt_f64(hash, fields.revenue); + hash = mix_opt_f64(hash, fields.net_income); + hash = mix_opt_f64(hash, fields.operating_cash_flow); + hash = mix_opt_f64(hash, fields.total_assets); + hash = mix_opt_f64(hash, fields.total_equity); + hash = mix_opt_f64(hash, fields.shares_outstanding); + hash +} + +fn hash_fundamentals_outputs( + rows: &[crate::fundamentals::FundamentalsRow], + snapshots: &[crate::fundamentals::FundamentalsSnapshot], +) -> u64 { + let mut hash = 0u64; + for row in rows { + hash = mix_u64(hash, row.key as u64); + hash = mix_u64(hash, row.period_end as u64); + hash = mix_u64(hash, row.fiscal_period as u64); + hash = mix_str(hash, &row.currency); + hash = mix_u64(hash, row.known_at_utc_micros as u64); + hash = mix_str(hash, row.known_at_source); + hash = mix_fundamentals_fields(hash, &row.fields); + } + for snap in snapshots { + hash = mix_u64(hash, snap.key as u64); + hash = mix_u64(hash, snap.effective_known_at_utc_micros as u64); + hash = mix_str(hash, snap.known_at_source); + hash = mix_u64(hash, u64::from(snap.has_estimated_lag)); + hash = mix_u64(hash, snap.periods.len() as u64); + for slot in &snap.periods { + hash = mix_u64(hash, slot.period_end as u64); + hash = mix_u64(hash, slot.fiscal_period as u64); + hash = mix_str(hash, &slot.currency); + hash = mix_u64(hash, slot.known_at_utc_micros as u64); + hash = mix_str(hash, slot.known_at_source); + hash = mix_u64(hash, u64::from(slot.has_estimated_lag)); + hash = mix_fundamentals_fields(hash, &slot.fields); + } + match &snap.ttm { + None => { + hash = mix_u64(hash, 0); + } + Some(ttm) => { + hash = mix_u64(hash, 1); + hash = mix_u64(hash, ttm.ending_period_end as u64); + hash = mix_str(hash, &ttm.currency); + hash = mix_u64(hash, u64::from(ttm.has_estimated_lag)); + hash = mix_opt_f64(hash, ttm.flows.revenue); + hash = mix_opt_f64(hash, ttm.flows.net_income); + hash = mix_opt_f64(hash, ttm.flows.operating_cash_flow); + } + } + } + hash +} + #[cfg(test)] mod tests { use super::*; @@ -13366,11 +13421,70 @@ mod tests { + a.stats.observations_dropped_date_out_of_range + a.stats.observations_dropped_report_date_not_after_period_end + a.stats.observations_dropped_unanchored_vintage + + a.stats.observations_dropped_stale_estimate + a.stats.duplicate_collapsed + a.stats.duplicate_conflict_dropped ); } + #[test] + fn fundamentals_checksum_distinguishes_none_zero_slots_and_non_revenue_ttm() { + use crate::fundamentals::{ + FundamentalsPeriodSlot, FundamentalsSnapshot, FundamentalsTtm, TtmFlowFields, + }; + + let base_slot = FundamentalsPeriodSlot { + period_end: 19_000, + fiscal_period: FiscalPeriod::Quarterly, + currency: "USD".to_string(), + known_at_utc_micros: 1_000, + known_at_source: crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP, + has_estimated_lag: false, + fields: FundamentalsFields { + revenue: Some(10.0), + net_income: None, + operating_cash_flow: Some(5.0), + total_assets: Some(100.0), + total_equity: Some(50.0), + shares_outstanding: Some(1_000.0), + }, + }; + let base_snap = FundamentalsSnapshot { + key: 1, + effective_known_at_utc_micros: 1_000, + known_at_source: crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP, + has_estimated_lag: false, + periods: vec![base_slot], + ttm: Some(FundamentalsTtm { + ending_period_end: 19_000, + currency: "USD".to_string(), + flows: TtmFlowFields { + revenue: Some(40.0), + net_income: None, + operating_cash_flow: Some(20.0), + }, + has_estimated_lag: false, + }), + }; + + let h_base = hash_fundamentals_outputs(&[], &[base_snap.clone()]); + + // None vs Some(0.0) in slot net_income + let mut s_zero = base_snap.clone(); + s_zero.periods[0].fields.net_income = Some(0.0); + assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_zero])); + + // Non-revenue TTM flow change (operating_cash_flow) + let mut s_ttm = base_snap.clone(); + s_ttm.ttm.as_mut().unwrap().flows.operating_cash_flow = Some(21.0); + assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_ttm])); + + // Carried-forward slot provenance change + let mut s_prov = base_snap; + s_prov.periods[0].has_estimated_lag = true; + assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_prov])); + } + #[test] fn fundamentals_benchmark_zero_rows_handles_cleanly() { let report = run_fundamentals_benchmark(0).unwrap(); diff --git a/tools/curate-etl/src/fundamentals.rs b/tools/curate-etl/src/fundamentals.rs index 44c72169..3c4cf629 100644 --- a/tools/curate-etl/src/fundamentals.rs +++ b/tools/curate-etl/src/fundamentals.rs @@ -32,6 +32,11 @@ //! `rd > lag_date`, it is dropped and counted as an unanchored vintage //! (`observations_dropped_unanchored_vintage`) rather than backdating `known_at` before its //! observed `report_date`. +//! - If a dated statutory-lag estimate (`report_date: Some(rd_a)`) for `(key, period_end, +//! fiscal_period)` would become visible at or after a newer dated version (`rd_b > rd_a`, +//! `known_at_b <= lag_micros`) of the same statement, the stale estimate is dropped and counted +//! in `observations_dropped_stale_estimate` so an older vintage never rolls a newer filing +//! backward. //! - Otherwise `known_at_utc_micros` is `lag_date` at `16:05:00 America/Toronto` //! ([`FUNDAMENTALS_FALLBACK_HOUR_ET`]:[`FUNDAMENTALS_FALLBACK_MINUTE_ET`]) via //! [`crate::shorts::et_to_utc_micros`], tagged `known_at_source = "statutory_lag_estimate"`. @@ -56,7 +61,9 @@ //! with per-field provenance. //! - Emits the latest `k` visible periods in descending `period_end` order (annual rows may occupy //! slots; stock fields remain reported period values). -//! - Independently of `k`, computes 4-quarter TTM sums for flow fields (`revenue`, `net_income`, +//! - Independently of `k` and of annual (`FY`) rows sharing a `period_end` (such as a calendar +//! year-end `10-K` sharing December 31 with standalone `Q4`), resolves standalone quarterly +//! versions separately and computes 4-quarter TTM sums for flow fields (`revenue`, `net_income`, //! `operating_cash_flow`) from the 4 latest visible standalone quarterly periods when adjacent //! `period_end` spacing is within [`TTM_CONSECUTIVE_QUARTER_MIN_DAYS`]..=[`TTM_CONSECUTIVE_QUARTER_MAX_DAYS`] //! (`77..=105` calendar days, a heuristic given the input lacks a fiscal-quarter ordinal) and @@ -303,7 +310,7 @@ pub struct FundamentalsSnapshot { /// /// Conservation invariants: /// - Observations: -/// `observations_in == rows_out + observations_dropped_unknown_key + observations_dropped_non_finite + observations_dropped_date_out_of_range + observations_dropped_report_date_not_after_period_end + observations_dropped_unanchored_vintage + duplicate_collapsed + duplicate_conflict_dropped` +/// `observations_in == rows_out + observations_dropped_unknown_key + observations_dropped_non_finite + observations_dropped_date_out_of_range + observations_dropped_report_date_not_after_period_end + observations_dropped_unanchored_vintage + observations_dropped_stale_estimate + duplicate_collapsed + duplicate_conflict_dropped` /// - Output provenance: /// `rows_out == rows_linked_to_filing + rows_statutory_lag_estimate` /// - Filings: @@ -320,6 +327,7 @@ pub struct FundamentalsStats { pub observations_dropped_date_out_of_range: usize, pub observations_dropped_report_date_not_after_period_end: usize, pub observations_dropped_unanchored_vintage: usize, + pub observations_dropped_stale_estimate: usize, pub duplicate_collapsed: usize, pub duplicate_conflict_dropped: usize, pub filings_in: usize, @@ -417,6 +425,11 @@ struct ParsedPeriodicFiling { is_amendment: bool, } +struct CandidateRow { + row: FundamentalsRow, + report_date: Option, +} + /// Builds sorted, unique bitemporal fundamentals rows from financial observations, periodic /// filings, and per-listing statutory-lag venue classes. /// @@ -543,7 +556,7 @@ where }); } - let mut candidates: Vec> = Vec::with_capacity(eligible_obs.len()); + let mut candidates: Vec> = Vec::with_capacity(eligible_obs.len()); for obs in eligible_obs { let linked_micros = filing_index @@ -601,63 +614,111 @@ where (micros, KNOWN_AT_SOURCE_STATUTORY_LAG) }; - candidates.push(FundamentalsRow { - key: obs.key, - period_end: obs.period_end, - fiscal_period: obs.fiscal_period, - currency: obs.currency, - known_at_utc_micros, - known_at_source, - fields: obs.fields, + candidates.push(CandidateRow { + row: FundamentalsRow { + key: obs.key, + period_end: obs.period_end, + fiscal_period: obs.fiscal_period, + currency: obs.currency, + known_at_utc_micros, + known_at_source, + fields: obs.fields, + }, + report_date: obs.report_date, }); } candidates.sort_unstable_by(|a, b| { - a.key - .cmp(&b.key) - .then_with(|| a.period_end.cmp(&b.period_end)) - .then_with(|| a.known_at_utc_micros.cmp(&b.known_at_utc_micros)) + a.row + .key + .cmp(&b.row.key) + .then_with(|| a.row.period_end.cmp(&b.row.period_end)) + .then_with(|| a.row.known_at_utc_micros.cmp(&b.row.known_at_utc_micros)) }); let mut rows: Vec> = Vec::with_capacity(candidates.len()); + let mut surviving_indices: Vec = Vec::new(); let total = candidates.len(); - let mut idx = 0usize; + let mut pe_start = 0usize; - while idx < total { - let mut group_end = idx + 1; - while group_end < total - && candidates[group_end].key == candidates[idx].key - && candidates[group_end].period_end == candidates[idx].period_end - && candidates[group_end].known_at_utc_micros == candidates[idx].known_at_utc_micros + while pe_start < total { + let mut pe_end = pe_start + 1; + while pe_end < total + && candidates[pe_end].row.key == candidates[pe_start].row.key + && candidates[pe_end].row.period_end == candidates[pe_start].row.period_end { - group_end += 1; + pe_end += 1; } - let group_len = group_end - idx; - let first = &candidates[idx]; - let all_identical = candidates[idx + 1..group_end].iter().all(|other| { - first.fiscal_period == other.fiscal_period - && first.currency == other.currency - && first.known_at_source == other.known_at_source - && first.fields.bit_eq(&other.fields) - }); + // Drop dated statutory-lag estimates superseded by a newer dated version of the same + // `(key, period_end, fiscal_period)` that becomes visible at or before the fallback time. + let slice = &candidates[pe_start..pe_end]; + let has_dated_estimate = slice.len() > 1 + && slice.iter().any(|c| { + c.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG && c.report_date.is_some() + }); - if all_identical { - stats.duplicate_collapsed += group_len - 1; - if first.known_at_source == KNOWN_AT_SOURCE_FILING_TIMESTAMP { - stats.rows_linked_to_filing += 1; - } else { - stats.rows_statutory_lag_estimate += 1; + surviving_indices.clear(); + if has_dated_estimate { + for (rel_idx, cand) in slice.iter().enumerate() { + let is_stale_estimate = cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG + && cand.report_date.is_some_and(|rd_a| { + slice.iter().any(|other| { + other.row.fiscal_period == cand.row.fiscal_period + && other.report_date.is_some_and(|rd_b| rd_b > rd_a) + && other.row.known_at_utc_micros <= cand.row.known_at_utc_micros + }) + }); + if is_stale_estimate { + stats.observations_dropped_stale_estimate += 1; + } else { + surviving_indices.push(pe_start + rel_idx); + } } - if rows.last().is_none_or(|prev| prev.key != first.key) { - stats.keys_out += 1; - } - rows.push(first.clone()); } else { - stats.duplicate_conflict_dropped += group_len; + surviving_indices.extend(pe_start..pe_end); } - idx = group_end; + let mut g_start = 0usize; + while g_start < surviving_indices.len() { + let first_idx = surviving_indices[g_start]; + let first = &candidates[first_idx].row; + let mut g_end = g_start + 1; + while g_end < surviving_indices.len() + && candidates[surviving_indices[g_end]].row.known_at_utc_micros + == first.known_at_utc_micros + { + g_end += 1; + } + + let group_len = g_end - g_start; + let all_identical = surviving_indices[g_start + 1..g_end].iter().all(|&other_idx| { + let other = &candidates[other_idx].row; + first.fiscal_period == other.fiscal_period + && first.currency == other.currency + && first.known_at_source == other.known_at_source + && first.fields.bit_eq(&other.fields) + }); + + if all_identical { + stats.duplicate_collapsed += group_len - 1; + if first.known_at_source == KNOWN_AT_SOURCE_FILING_TIMESTAMP { + stats.rows_linked_to_filing += 1; + } else { + stats.rows_statutory_lag_estimate += 1; + } + if rows.last().is_none_or(|prev| prev.key != first.key) { + stats.keys_out += 1; + } + rows.push(first.clone()); + } else { + stats.duplicate_conflict_dropped += group_len; + } + + g_start = g_end; + } + + pe_start = pe_end; } stats.rows_out = rows.len(); @@ -770,12 +831,9 @@ fn sum_4_flows(values: [Option; 4]) -> Option { } } -fn compute_ttm(visible_periods: &BTreeMap) -> Option { +fn compute_ttm(visible_quarters: &BTreeMap) -> Option { let quarters: [&ResolvedPeriod; TTM_QUARTER_COUNT] = { - let mut iter = visible_periods - .values() - .rev() - .filter(|p| p.fiscal_period == FiscalPeriod::Quarterly); + let mut iter = visible_quarters.values().rev(); let q0 = iter.next()?; let q1 = iter.next()?; let q2 = iter.next()?; @@ -853,6 +911,7 @@ where .cmp(&rows[b].key) .then_with(|| rows[a].known_at_utc_micros.cmp(&rows[b].known_at_utc_micros)) .then_with(|| rows[a].period_end.cmp(&rows[b].period_end)) + .then_with(|| rows[a].fiscal_period.cmp(&rows[b].fiscal_period)) }); let mut snapshots: Vec> = Vec::new(); @@ -862,6 +921,7 @@ where while idx < total { let key = &rows[order[idx]].key; let mut visible_periods: BTreeMap = BTreeMap::new(); + let mut visible_quarters: BTreeMap = BTreeMap::new(); while idx < total && &rows[order[idx]].key == key { let effective_ts = rows[order[idx]].known_at_utc_micros; @@ -871,10 +931,25 @@ where && rows[order[idx]].known_at_utc_micros == effective_ts { let row = &rows[order[idx]]; - match visible_periods.get_mut(&row.period_end) { - Some(existing) => existing.apply_update(row), - None => { - visible_periods.insert(row.period_end, ResolvedPeriod::from_row(row)); + if row.fiscal_period == FiscalPeriod::Quarterly { + let resolved = match visible_quarters.get_mut(&row.period_end) { + Some(existing) => { + existing.apply_update(row); + existing.clone() + } + None => { + let created = ResolvedPeriod::from_row(row); + visible_quarters.insert(row.period_end, created.clone()); + created + } + }; + visible_periods.insert(row.period_end, resolved); + } else { + match visible_periods.get_mut(&row.period_end) { + Some(existing) => existing.apply_update(row), + None => { + visible_periods.insert(row.period_end, ResolvedPeriod::from_row(row)); + } } } idx += 1; @@ -886,7 +961,7 @@ where .take(k) .map(ResolvedPeriod::to_slot) .collect(); - let ttm = compute_ttm(&visible_periods); + let ttm = compute_ttm(&visible_quarters); let has_estimated_lag = periods.iter().any(|p| p.has_estimated_lag) || ttm.as_ref().is_some_and(|t| t.has_estimated_lag); let known_at_source = if has_estimated_lag { diff --git a/tools/curate-etl/src/fundamentals_tests.rs b/tools/curate-etl/src/fundamentals_tests.rs index 1d9e0b9d..4afa3272 100644 --- a/tools/curate-etl/src/fundamentals_tests.rs +++ b/tools/curate-etl/src/fundamentals_tests.rs @@ -76,6 +76,7 @@ fn assert_reconciliation(build: &FundamentalsBuild) { + s.observations_dropped_date_out_of_range + s.observations_dropped_report_date_not_after_period_end + s.observations_dropped_unanchored_vintage + + s.observations_dropped_stale_estimate + s.duplicate_collapsed + s.duplicate_conflict_dropped, "observation reconciliation failed: {s:?}" @@ -737,3 +738,171 @@ fn robustness_bad_rows_dedup_conflicts_and_input_order_determinism() { let snaps_b = build_fundamentals_snapshots(&built_rev.rows, 4).unwrap(); assert_eq!(snaps_a, snaps_b); } + +#[test] +fn stale_statutory_lag_estimate_does_not_overwrite_newer_filed_version() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q1_end = day(2024, 3, 31); + + // Apr 30 observation has no same-day periodic filing -> would fall back to May 15 16:05 ET. + // May 10 observation links to a 10-Q -> visible May 10 16:15 ET. + // Because Apr 30 is an older report vintage than May 10, the stale estimate must be dropped + // so revenue stays 110 at and after May 15 instead of reverting to 100. + let filings = vec![filing("ACME", "2024-05-10T16:15:00 EDT", "10-Q")]; + let observations = vec![ + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 4, 30)), + fields_rev(100.0), + ), + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 10)), + fields_rev(110.0), + ), + ]; + + let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.rows_out, 1); + assert_eq!(built.stats.rows_linked_to_filing, 1); + assert_eq!(built.stats.rows_statutory_lag_estimate, 0); + assert_eq!(built.stats.observations_dropped_stale_estimate, 1); + + // Input-order determinism with stale estimate present + let mut obs_rev = observations; + obs_rev.reverse(); + assert_eq!(built, build_fundamentals_rows(obs_rev, filings, &venues)); + + let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); + assert_eq!(snaps.len(), 1); + + let ts_may_10 = utc_micros(2024, 5, 10, 20, 15, 0); + let ts_may_15_fallback = et_to_utc_micros(day(2024, 5, 15), 16, 5, 0).unwrap(); + + for probe in [ts_may_10, ts_may_15_fallback, ts_may_15_fallback + 1_000_000] { + let snap = as_of(&snaps, "ACME", probe).expect("snapshot visible"); + assert_eq!(snap.effective_known_at_utc_micros, ts_may_10); + assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!snap.has_estimated_lag); + assert_eq!(snap.periods[0].period_end, q1_end); + assert_eq!(snap.periods[0].fields.revenue, Some(110.0)); + } + + // Edge cases: + // (a) An earlier estimate (Apr 30 -> May 15) followed by a LATER filing (Jun 1) is NOT stale. + // (b) A linked FY filing sharing Dec 31 does NOT suppress a standalone Q4 estimate. + let edge_filings = vec![ + filing("ACME", "2024-06-01T17:00:00 EDT", "10-Q/A"), + filing("ACME", "2024-02-12T16:15:00 EST", "10-K"), + ]; + let dec_31 = day(2023, 12, 31); + let edge_obs = vec![ + obs("ACME", q1_end, FiscalPeriod::Quarterly, "USD", Some(day(2024, 4, 30)), fields_rev(100.0)), + obs("ACME", q1_end, FiscalPeriod::Quarterly, "USD", Some(day(2024, 6, 1)), fields_rev(115.0)), + obs("ACME", dec_31, FiscalPeriod::Quarterly, "USD", Some(day(2024, 2, 10)), fields_rev(40.0)), + obs("ACME", dec_31, FiscalPeriod::Annual, "USD", Some(day(2024, 2, 12)), fields_rev(160.0)), + ]; + let edge_built = build_fundamentals_rows(edge_obs, edge_filings, &venues); + assert_reconciliation(&edge_built); + assert_eq!(edge_built.stats.observations_dropped_stale_estimate, 0); + assert_eq!(edge_built.stats.rows_out, 4); +} + +#[test] +fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() { + let make_row = |pe: i32, kind: FiscalPeriod, ts: i64, src: &'static str, fields: FundamentalsFields| { + FundamentalsRow { + key: "CAL".to_string(), + period_end: pe, + fiscal_period: kind, + currency: "USD".to_string(), + known_at_utc_micros: ts, + known_at_source: src, + fields, + } + }; + + let q1 = day(2023, 3, 31); + let q2 = day(2023, 6, 30); + let q3 = day(2023, 9, 30); + let q4_fy = day(2023, 12, 31); + + let rows = vec![ + make_row(q1, FiscalPeriod::Quarterly, 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), + make_row(q2, FiscalPeriod::Quarterly, 200, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), + make_row(q3, FiscalPeriod::Quarterly, 300, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), + make_row(q4_fy, FiscalPeriod::Quarterly, 400, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), + // Later FY report sharing December 31 period_end + make_row(q4_fy, FiscalPeriod::Annual, 500, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)), + // Even later Q4 restatement omitting operating_cash_flow -> should inherit original Q4's OCF + make_row( + q4_fy, + FiscalPeriod::Quarterly, + 600, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + FundamentalsFields { + revenue: Some(45.0), + net_income: Some(4.5), + operating_cash_flow: None, + total_assets: Some(210.0), + total_equity: Some(85.0), + shares_outstanding: Some(1_000.0), + }, + ), + ]; + + let snaps = build_fundamentals_snapshots(&rows, 4).unwrap(); + assert_eq!(snaps.len(), 6); + + // At t=400 (Q4 visible): TTM ends 2023-12-31 with revenue 100 + let s4 = as_of(&snaps, "CAL", 400).unwrap(); + assert_eq!(s4.periods[0].period_end, q4_fy); + assert_eq!(s4.periods[0].fiscal_period, FiscalPeriod::Quarterly); + assert_eq!(s4.ttm.as_ref().unwrap().ending_period_end, q4_fy); + assert_eq!(s4.ttm.as_ref().unwrap().flows.revenue, Some(100.0)); + + // At t=500 (FY shares 2023-12-31): latest slot is FY, while TTM still uses all 4 standalone quarters + let s5 = as_of(&snaps, "CAL", 500).unwrap(); + assert_eq!(s5.periods[0].period_end, q4_fy); + assert_eq!(s5.periods[0].fiscal_period, FiscalPeriod::Annual); + assert_eq!(s5.periods[0].fields.revenue, Some(100.0)); + let ttm5 = s5.ttm.as_ref().expect("TTM must survive FY sharing Dec 31"); + assert_eq!(ttm5.ending_period_end, q4_fy); + assert_eq!(ttm5.flows.revenue, Some(100.0)); + assert_eq!(ttm5.flows.net_income, Some(10.0)); + assert_eq!(ttm5.flows.operating_cash_flow, Some(15.0)); + + // At t=600 (Q4 restatement after FY): inherits original Q4's operating_cash_flow (6.0), TTM updates to 105 + let s6 = as_of(&snaps, "CAL", 600).unwrap(); + assert_eq!(s6.periods[0].period_end, q4_fy); + assert_eq!(s6.periods[0].fiscal_period, FiscalPeriod::Quarterly); + assert_eq!(s6.periods[0].fields.revenue, Some(45.0)); + assert_eq!(s6.periods[0].fields.operating_cash_flow, Some(6.0)); + let ttm6 = s6.ttm.as_ref().expect("TTM after Q4 restatement"); + assert_eq!(ttm6.ending_period_end, q4_fy); + assert_eq!(ttm6.flows.revenue, Some(105.0)); + assert_eq!(ttm6.flows.operating_cash_flow, Some(15.0)); + + // Provenance check: if Q4 was statutory_lag_estimate and later FY (filing_timestamp) occupies + // periods[0] on Dec 31, TTM still uses estimated Q4 so snapshot stays flagged estimated. + let rows_est_q4 = vec![ + make_row(q1, FiscalPeriod::Quarterly, 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), + make_row(q2, FiscalPeriod::Quarterly, 200, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), + make_row(q3, FiscalPeriod::Quarterly, 300, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), + make_row(q4_fy, FiscalPeriod::Quarterly, 400, KNOWN_AT_SOURCE_STATUTORY_LAG, fields_rev(40.0)), + make_row(q4_fy, FiscalPeriod::Annual, 500, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)), + ]; + let snaps_est = build_fundamentals_snapshots(&rows_est_q4, 4).unwrap(); + let fy_snap = as_of(&snaps_est, "CAL", 500).unwrap(); + assert!(!fy_snap.periods[0].has_estimated_lag); + assert!(fy_snap.ttm.as_ref().unwrap().has_estimated_lag); + assert!(fy_snap.has_estimated_lag); + assert_eq!(fy_snap.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); +} diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 04d3c213..b211d86c 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -508,7 +508,7 @@ fn main() -> ExitCode { report.checksum ); println!( - " stats: linked={} statutory_lag={} dup_collapsed={} dup_conflict={} obs_unknown_key={} obs_non_finite={} obs_oor={} obs_rd_le_pe={} obs_unanchored={} filings_eligible={} filings_non_periodic={} filings_bad_ts={} filings_oor={} filings_before_pe={}", + " stats: linked={} statutory_lag={} dup_collapsed={} dup_conflict={} obs_unknown_key={} obs_non_finite={} obs_oor={} obs_rd_le_pe={} obs_unanchored={} obs_stale_est={} filings_eligible={} filings_non_periodic={} filings_bad_ts={} filings_oor={} filings_before_pe={}", report.stats.rows_linked_to_filing, report.stats.rows_statutory_lag_estimate, report.stats.duplicate_collapsed, @@ -518,6 +518,7 @@ fn main() -> ExitCode { report.stats.observations_dropped_date_out_of_range, report.stats.observations_dropped_report_date_not_after_period_end, report.stats.observations_dropped_unanchored_vintage, + report.stats.observations_dropped_stale_estimate, report.stats.filings_eligible, report.stats.filings_ignored_non_periodic, report.stats.filings_dropped_invalid_timestamp, From be5bd1c38ab0d03f1ef4f56d1e44ad1f7d8923f5 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 00:43:53 -0500 Subject: [PATCH 20/21] =?UTF-8?q?T-132:=20M2.2a=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20point-in-time=20fundamentals=20builder=20(`qmF?= =?UTF-8?q?inancials`=20=C3=97=20`qmFilings`=20`known=5Fat`=20link=20+=20s?= =?UTF-8?q?tatutory-lag=20fallback=20=E2=86=92=20bitemporal=20rows=20?= =?UTF-8?q?=E2=86=92=202D=20PIT=20snapshots=20+=20TTM)=20with=20restatemen?= =?UTF-8?q?t=20fixture=20test=20and=20local=20benchmark=20(no=20new=20crat?= =?UTF-8?q?es)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/fundamentals.rs | 154 +++++++++++---------- tools/curate-etl/src/fundamentals_tests.rs | 94 ++++++++++++- 2 files changed, 173 insertions(+), 75 deletions(-) diff --git a/tools/curate-etl/src/fundamentals.rs b/tools/curate-etl/src/fundamentals.rs index 3c4cf629..98b12b1c 100644 --- a/tools/curate-etl/src/fundamentals.rs +++ b/tools/curate-etl/src/fundamentals.rs @@ -33,10 +33,10 @@ //! (`observations_dropped_unanchored_vintage`) rather than backdating `known_at` before its //! observed `report_date`. //! - If a dated statutory-lag estimate (`report_date: Some(rd_a)`) for `(key, period_end, -//! fiscal_period)` would become visible at or after a newer dated version (`rd_b > rd_a`, -//! `known_at_b <= lag_micros`) of the same statement, the stale estimate is dropped and counted -//! in `observations_dropped_stale_estimate` so an older vintage never rolls a newer filing -//! backward. +//! fiscal_period)` would become visible at or after an accepted newer dated version +//! (`rd_b > rd_a`, `known_at_b <= lag_micros`) of the same statement, the stale estimate is +//! dropped and counted in `observations_dropped_stale_estimate` so an older vintage never rolls +//! a newer filing backward. //! - Otherwise `known_at_utc_micros` is `lag_date` at `16:05:00 America/Toronto` //! ([`FUNDAMENTALS_FALLBACK_HOUR_ET`]:[`FUNDAMENTALS_FALLBACK_MINUTE_ET`]) via //! [`crate::shorts::et_to_utc_micros`], tagged `known_at_source = "statutory_lag_estimate"`. @@ -637,7 +637,6 @@ where }); let mut rows: Vec> = Vec::with_capacity(candidates.len()); - let mut surviving_indices: Vec = Vec::new(); let total = candidates.len(); let mut pe_start = 0usize; @@ -650,71 +649,82 @@ where pe_end += 1; } - // Drop dated statutory-lag estimates superseded by a newer dated version of the same - // `(key, period_end, fiscal_period)` that becomes visible at or before the fallback time. - let slice = &candidates[pe_start..pe_end]; - let has_dated_estimate = slice.len() > 1 - && slice.iter().any(|c| { - c.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG && c.report_date.is_some() - }); + // Track the newest accepted `report_date` seen at an earlier `known_at_utc_micros` for + // each `FiscalPeriod` so only accepted newer versions can suppress a stale statutory-lag + // estimate. + let mut max_accepted_rd_q: Option = None; + let mut max_accepted_rd_fy: Option = None; - surviving_indices.clear(); - if has_dated_estimate { - for (rel_idx, cand) in slice.iter().enumerate() { - let is_stale_estimate = cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG - && cand.report_date.is_some_and(|rd_a| { - slice.iter().any(|other| { - other.row.fiscal_period == cand.row.fiscal_period - && other.report_date.is_some_and(|rd_b| rd_b > rd_a) - && other.row.known_at_utc_micros <= cand.row.known_at_utc_micros - }) - }); - if is_stale_estimate { - stats.observations_dropped_stale_estimate += 1; - } else { - surviving_indices.push(pe_start + rel_idx); - } - } - } else { - surviving_indices.extend(pe_start..pe_end); - } - - let mut g_start = 0usize; - while g_start < surviving_indices.len() { - let first_idx = surviving_indices[g_start]; - let first = &candidates[first_idx].row; + let mut g_start = pe_start; + while g_start < pe_end { + let first = &candidates[g_start].row; let mut g_end = g_start + 1; - while g_end < surviving_indices.len() - && candidates[surviving_indices[g_end]].row.known_at_utc_micros - == first.known_at_utc_micros + while g_end < pe_end + && candidates[g_end].row.known_at_utc_micros == first.known_at_utc_micros { g_end += 1; } let group_len = g_end - g_start; - let all_identical = surviving_indices[g_start + 1..g_end].iter().all(|&other_idx| { - let other = &candidates[other_idx].row; + let all_identical = candidates[g_start + 1..g_end].iter().all(|other_cand| { + let other = &other_cand.row; first.fiscal_period == other.fiscal_period && first.currency == other.currency && first.known_at_source == other.known_at_source && first.fields.bit_eq(&other.fields) }); - if all_identical { - stats.duplicate_collapsed += group_len - 1; - if first.known_at_source == KNOWN_AT_SOURCE_FILING_TIMESTAMP { - stats.rows_linked_to_filing += 1; - } else { - stats.rows_statutory_lag_estimate += 1; - } - if rows.last().is_none_or(|prev| prev.key != first.key) { - stats.keys_out += 1; - } - rows.push(first.clone()); - } else { + if !all_identical { stats.duplicate_conflict_dropped += group_len; + g_start = g_end; + continue; } + let mut group_max_rd: Option = None; + let mut all_dated = true; + for cand in &candidates[g_start..g_end] { + match cand.report_date { + Some(rd) => { + group_max_rd = Some(group_max_rd.map_or(rd, |m| m.max(rd))); + } + None => all_dated = false, + } + } + + let prior_max_rd = match first.fiscal_period { + FiscalPeriod::Quarterly => max_accepted_rd_q, + FiscalPeriod::Annual => max_accepted_rd_fy, + }; + let is_stale_estimate = first.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG + && all_dated + && group_max_rd + .is_some_and(|rd_a| prior_max_rd.is_some_and(|rd_b| rd_b > rd_a)); + + if is_stale_estimate { + stats.observations_dropped_stale_estimate += group_len; + g_start = g_end; + continue; + } + + if let Some(rd) = group_max_rd { + let slot = match first.fiscal_period { + FiscalPeriod::Quarterly => &mut max_accepted_rd_q, + FiscalPeriod::Annual => &mut max_accepted_rd_fy, + }; + *slot = Some(slot.map_or(rd, |m| m.max(rd))); + } + + stats.duplicate_collapsed += group_len - 1; + if first.known_at_source == KNOWN_AT_SOURCE_FILING_TIMESTAMP { + stats.rows_linked_to_filing += 1; + } else { + stats.rows_statutory_lag_estimate += 1; + } + if rows.last().is_none_or(|prev| prev.key != first.key) { + stats.keys_out += 1; + } + rows.push(first.clone()); + g_start = g_end; } @@ -922,6 +932,7 @@ where let key = &rows[order[idx]].key; let mut visible_periods: BTreeMap = BTreeMap::new(); let mut visible_quarters: BTreeMap = BTreeMap::new(); + let mut visible_annuals: BTreeMap = BTreeMap::new(); while idx < total && &rows[order[idx]].key == key { let effective_ts = rows[order[idx]].known_at_utc_micros; @@ -931,27 +942,22 @@ where && rows[order[idx]].known_at_utc_micros == effective_ts { let row = &rows[order[idx]]; - if row.fiscal_period == FiscalPeriod::Quarterly { - let resolved = match visible_quarters.get_mut(&row.period_end) { - Some(existing) => { - existing.apply_update(row); - existing.clone() - } - None => { - let created = ResolvedPeriod::from_row(row); - visible_quarters.insert(row.period_end, created.clone()); - created - } - }; - visible_periods.insert(row.period_end, resolved); - } else { - match visible_periods.get_mut(&row.period_end) { - Some(existing) => existing.apply_update(row), - None => { - visible_periods.insert(row.period_end, ResolvedPeriod::from_row(row)); - } + let by_kind = match row.fiscal_period { + FiscalPeriod::Quarterly => &mut visible_quarters, + FiscalPeriod::Annual => &mut visible_annuals, + }; + let resolved = match by_kind.get_mut(&row.period_end) { + Some(existing) => { + existing.apply_update(row); + existing.clone() } - } + None => { + let created = ResolvedPeriod::from_row(row); + by_kind.insert(row.period_end, created.clone()); + created + } + }; + visible_periods.insert(row.period_end, resolved); idx += 1; } diff --git a/tools/curate-etl/src/fundamentals_tests.rs b/tools/curate-etl/src/fundamentals_tests.rs index 4afa3272..9f9dd370 100644 --- a/tools/curate-etl/src/fundamentals_tests.rs +++ b/tools/curate-etl/src/fundamentals_tests.rs @@ -815,6 +815,71 @@ fn stale_statutory_lag_estimate_does_not_overwrite_newer_filed_version() { assert_eq!(edge_built.stats.rows_out, 4); } +#[test] +fn conflicting_newer_filing_does_not_suppress_eligible_statutory_lag_estimate() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q1_end = day(2024, 3, 31); + + // Apr 30 observation (rev 100) has no same-day filing -> May 15 16:05 ET fallback. + // Two May 10 observations link to the same 10-Q with conflicting revenues (110 vs 112). + // Because the May 10 group is rejected as a duplicate conflict, it must NOT suppress the + // eligible Apr 30 statutory-lag estimate. + let filings = vec![filing("ACME", "2024-05-10T16:15:00 EDT", "10-Q")]; + let observations = vec![ + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 4, 30)), + fields_rev(100.0), + ), + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 10)), + fields_rev(110.0), + ), + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 10)), + fields_rev(112.0), + ), + ]; + + let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.duplicate_conflict_dropped, 2); + assert_eq!(built.stats.observations_dropped_stale_estimate, 0); + assert_eq!(built.stats.rows_out, 1); + assert_eq!(built.stats.rows_linked_to_filing, 0); + assert_eq!(built.stats.rows_statutory_lag_estimate, 1); + + // Input-order determinism + let mut obs_rev = observations; + obs_rev.reverse(); + assert_eq!(built, build_fundamentals_rows(obs_rev, filings, &venues)); + + let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); + let ts_may_10 = utc_micros(2024, 5, 10, 20, 15, 0); + let ts_may_15_fallback = et_to_utc_micros(day(2024, 5, 15), 16, 5, 0).unwrap(); + + assert!(as_of(&snaps, "ACME", ts_may_10).is_none()); + assert!(as_of(&snaps, "ACME", ts_may_15_fallback - 1).is_none()); + + let snap = as_of(&snaps, "ACME", ts_may_15_fallback).expect("fallback estimate must be visible"); + assert_eq!(snap.effective_known_at_utc_micros, ts_may_15_fallback); + assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(snap.has_estimated_lag); + assert_eq!(snap.periods[0].period_end, q1_end); + assert_eq!(snap.periods[0].fields.revenue, Some(100.0)); +} + #[test] fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() { let make_row = |pe: i32, kind: FiscalPeriod, ts: i64, src: &'static str, fields: FundamentalsFields| { @@ -856,10 +921,25 @@ fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() { shares_outstanding: Some(1_000.0), }, ), + // Partial FY amendment after the Q4 amendment -> should inherit original FY's OCF (15.0) + make_row( + q4_fy, + FiscalPeriod::Annual, + 700, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + FundamentalsFields { + revenue: Some(102.0), + net_income: Some(10.2), + operating_cash_flow: None, + total_assets: Some(220.0), + total_equity: Some(90.0), + shares_outstanding: Some(1_000.0), + }, + ), ]; let snaps = build_fundamentals_snapshots(&rows, 4).unwrap(); - assert_eq!(snaps.len(), 6); + assert_eq!(snaps.len(), 7); // At t=400 (Q4 visible): TTM ends 2023-12-31 with revenue 100 let s4 = as_of(&snaps, "CAL", 400).unwrap(); @@ -890,6 +970,18 @@ fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() { assert_eq!(ttm6.flows.revenue, Some(105.0)); assert_eq!(ttm6.flows.operating_cash_flow, Some(15.0)); + // At t=700 (partial FY amendment after Q4 amendment): inherits original FY's OCF (15.0) while + // TTM remains backed by the 4 standalone quarters (rev 105, OCF 15). + let s7 = as_of(&snaps, "CAL", 700).unwrap(); + assert_eq!(s7.periods[0].period_end, q4_fy); + assert_eq!(s7.periods[0].fiscal_period, FiscalPeriod::Annual); + assert_eq!(s7.periods[0].fields.revenue, Some(102.0)); + assert_eq!(s7.periods[0].fields.operating_cash_flow, Some(15.0)); + let ttm7 = s7.ttm.as_ref().expect("TTM after partial FY amendment"); + assert_eq!(ttm7.ending_period_end, q4_fy); + assert_eq!(ttm7.flows.revenue, Some(105.0)); + assert_eq!(ttm7.flows.operating_cash_flow, Some(15.0)); + // Provenance check: if Q4 was statutory_lag_estimate and later FY (filing_timestamp) occupies // periods[0] on Dec 31, TTM still uses estimated Q4 so snapshot stays flagged estimated. let rows_est_q4 = vec![ From 948dbf560c8398f08dfad58ed6b7f40c6ba9f940 Mon Sep 17 00:00:00 2001 From: Studio Date: Tue, 1 Dec 2026 00:52:59 -0500 Subject: [PATCH 21/21] =?UTF-8?q?T-132:=20M2.2a=20=E2=80=94=20`tools/curat?= =?UTF-8?q?e-etl`:=20pure=20point-in-time=20fundamentals=20builder=20(`qmF?= =?UTF-8?q?inancials`=20=C3=97=20`qmFilings`=20`known=5Fat`=20link=20+=20s?= =?UTF-8?q?tatutory-lag=20fallback=20=E2=86=92=20bitemporal=20rows=20?= =?UTF-8?q?=E2=86=92=202D=20PIT=20snapshots=20+=20TTM)=20with=20restatemen?= =?UTF-8?q?t=20fixture=20test=20and=20local=20benchmark=20(no=20new=20crat?= =?UTF-8?q?es)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tools/curate-etl/src/fundamentals.rs | 69 ++++++++++++---------- tools/curate-etl/src/fundamentals_tests.rs | 69 ++++++++++++++++++++++ 2 files changed, 106 insertions(+), 32 deletions(-) diff --git a/tools/curate-etl/src/fundamentals.rs b/tools/curate-etl/src/fundamentals.rs index 98b12b1c..7ac7cae6 100644 --- a/tools/curate-etl/src/fundamentals.rs +++ b/tools/curate-etl/src/fundamentals.rs @@ -637,6 +637,7 @@ where }); let mut rows: Vec> = Vec::with_capacity(candidates.len()); + let mut survivors: Vec = Vec::new(); let total = candidates.len(); let mut pe_start = 0usize; @@ -657,17 +658,41 @@ where let mut g_start = pe_start; while g_start < pe_end { - let first = &candidates[g_start].row; + let group_ts = candidates[g_start].row.known_at_utc_micros; let mut g_end = g_start + 1; - while g_end < pe_end - && candidates[g_end].row.known_at_utc_micros == first.known_at_utc_micros - { + while g_end < pe_end && candidates[g_end].row.known_at_utc_micros == group_ts { g_end += 1; } - let group_len = g_end - g_start; - let all_identical = candidates[g_start + 1..g_end].iter().all(|other_cand| { - let other = &other_cand.row; + // Filter out stale dated statutory-lag candidates before duplicate/conflict checks + // so a superseded estimate cannot cause an eligible estimate at the same fallback + // timestamp to be rejected as conflicting. + survivors.clear(); + for idx in g_start..g_end { + let cand = &candidates[idx]; + let prior_max_rd = match cand.row.fiscal_period { + FiscalPeriod::Quarterly => max_accepted_rd_q, + FiscalPeriod::Annual => max_accepted_rd_fy, + }; + let is_stale_estimate = cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG + && cand + .report_date + .is_some_and(|rd_a| prior_max_rd.is_some_and(|rd_b| rd_b > rd_a)); + if is_stale_estimate { + stats.observations_dropped_stale_estimate += 1; + } else { + survivors.push(idx); + } + } + + if survivors.is_empty() { + g_start = g_end; + continue; + } + + let first = &candidates[survivors[0]].row; + let all_identical = survivors[1..].iter().all(|&idx| { + let other = &candidates[idx].row; first.fiscal_period == other.fiscal_period && first.currency == other.currency && first.known_at_source == other.known_at_source @@ -675,37 +700,17 @@ where }); if !all_identical { - stats.duplicate_conflict_dropped += group_len; + stats.duplicate_conflict_dropped += survivors.len(); g_start = g_end; continue; } let mut group_max_rd: Option = None; - let mut all_dated = true; - for cand in &candidates[g_start..g_end] { - match cand.report_date { - Some(rd) => { - group_max_rd = Some(group_max_rd.map_or(rd, |m| m.max(rd))); - } - None => all_dated = false, + for &idx in &survivors { + if let Some(rd) = candidates[idx].report_date { + group_max_rd = Some(group_max_rd.map_or(rd, |m| m.max(rd))); } } - - let prior_max_rd = match first.fiscal_period { - FiscalPeriod::Quarterly => max_accepted_rd_q, - FiscalPeriod::Annual => max_accepted_rd_fy, - }; - let is_stale_estimate = first.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG - && all_dated - && group_max_rd - .is_some_and(|rd_a| prior_max_rd.is_some_and(|rd_b| rd_b > rd_a)); - - if is_stale_estimate { - stats.observations_dropped_stale_estimate += group_len; - g_start = g_end; - continue; - } - if let Some(rd) = group_max_rd { let slot = match first.fiscal_period { FiscalPeriod::Quarterly => &mut max_accepted_rd_q, @@ -714,7 +719,7 @@ where *slot = Some(slot.map_or(rd, |m| m.max(rd))); } - stats.duplicate_collapsed += group_len - 1; + stats.duplicate_collapsed += survivors.len() - 1; if first.known_at_source == KNOWN_AT_SOURCE_FILING_TIMESTAMP { stats.rows_linked_to_filing += 1; } else { diff --git a/tools/curate-etl/src/fundamentals_tests.rs b/tools/curate-etl/src/fundamentals_tests.rs index 9f9dd370..a3919caf 100644 --- a/tools/curate-etl/src/fundamentals_tests.rs +++ b/tools/curate-etl/src/fundamentals_tests.rs @@ -880,6 +880,75 @@ fn conflicting_newer_filing_does_not_suppress_eligible_statutory_lag_estimate() assert_eq!(snap.periods[0].fields.revenue, Some(100.0)); } +#[test] +fn stale_estimate_at_same_fallback_timestamp_does_not_conflict_with_eligible_estimate() { + let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); + let q1_end = day(2024, 3, 31); + + // Apr 30 (rev 100) and May 12 (rev 115) have no same-day periodic filing -> both get the + // May 15 16:05 ET fallback timestamp. The accepted May 10 10-Q (rev 110) supersedes Apr 30, + // so Apr 30 must be dropped as a stale estimate before duplicate/conflict checks and must + // not cause the eligible May 12 estimate to be discarded as a conflict. + let filings = vec![filing("ACME", "2024-05-10T16:15:00 EDT", "10-Q")]; + let observations = vec![ + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 4, 30)), + fields_rev(100.0), + ), + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 10)), + fields_rev(110.0), + ), + obs( + "ACME", + q1_end, + FiscalPeriod::Quarterly, + "USD", + Some(day(2024, 5, 12)), + fields_rev(115.0), + ), + ]; + + let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); + assert_reconciliation(&built); + assert_eq!(built.stats.observations_dropped_stale_estimate, 1); + assert_eq!(built.stats.duplicate_conflict_dropped, 0); + assert_eq!(built.stats.rows_out, 2); + assert_eq!(built.stats.rows_linked_to_filing, 1); + assert_eq!(built.stats.rows_statutory_lag_estimate, 1); + + // Input-order determinism + let mut obs_rev = observations; + obs_rev.reverse(); + assert_eq!(built, build_fundamentals_rows(obs_rev, filings, &venues)); + + let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); + let ts_may_15_fallback = et_to_utc_micros(day(2024, 5, 15), 16, 5, 0).unwrap(); + + let before_fallback = as_of(&snaps, "ACME", ts_may_15_fallback - 1) + .expect("May 10 10-Q must be visible before fallback"); + assert_eq!(before_fallback.periods[0].period_end, q1_end); + assert_eq!(before_fallback.periods[0].fields.revenue, Some(110.0)); + assert_eq!(before_fallback.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(!before_fallback.has_estimated_lag); + + let at_fallback = as_of(&snaps, "ACME", ts_may_15_fallback) + .expect("May 12 estimate must be visible at fallback cutoff"); + assert_eq!(at_fallback.effective_known_at_utc_micros, ts_may_15_fallback); + assert_eq!(at_fallback.periods[0].period_end, q1_end); + assert_eq!(at_fallback.periods[0].fields.revenue, Some(115.0)); + assert_eq!(at_fallback.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(at_fallback.has_estimated_lag); +} + #[test] fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() { let make_row = |pe: i32, kind: FiscalPeriod, ts: i64, src: &'static str, fields: FundamentalsFields| {