T-132: M2.2a — tools/curate-etl: pure point-in-time fundamentals builder (qmFinancials × qmFilings known_at link + statutory-lag fallback → bitemporal rows → 2D PIT snapshots + TTM) with restatement fixture test and local benchmark (no new crates)
This commit is contained in:
commit
b0e08171bd
32 changed files with 16714 additions and 78 deletions
|
|
@ -1,95 +1,175 @@
|
|||
# Milestone M2 Baseline Verification Report (T-128 / M2.0)
|
||||
|
||||
- **Date:** `2026-11-30`
|
||||
- **Target Baseline:** `master` / `dev` at `56b73b7e663d293079ab7bac264950dfa7a68b00` (contains accepted M1 closure commit `d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1`)
|
||||
- **Verdict:** **GREEN — Ready to start Milestone M2 implementation** (`0` real failures across all sandbox gates, full unfiltered `bun test`, and Studio's authoritative unsandboxed verification; previous Auto Mode baseline blocker on `d52aa20b` is confirmed resolved in `56b73b7e`).
|
||||
- **Scope Compliance:** Zero M2 feature code, zero CI workflow changes, zero T-127 edits, and zero `studio.config.json` modifications.
|
||||
**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
|
||||
|
||||
Executed from workspace root (`/home/boki/repos/stock-bot`):
|
||||
### Revisions Checked
|
||||
|
||||
| Check | Command | Exit Code | Output (Verbatim) |
|
||||
| --- | --- | ---: | --- |
|
||||
| `HEAD` SHA | `git rev-parse HEAD` | `0` | `56b73b7e663d293079ab7bac264950dfa7a68b00` |
|
||||
| `master` SHA | `git rev-parse master` | `0` | `56b73b7e663d293079ab7bac264950dfa7a68b00` |
|
||||
| Current branch | `git branch --show-current` | `0` | `dev` (`HEAD == master == dev`) |
|
||||
| M1 ancestry check | `git merge-base --is-ancestor d52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1 HEAD` | `0` | *(empty stdout/stderr — confirms `d52aa20b` is an ancestor of `56b73b7e`)* |
|
||||
| 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` |
|
||||
|
||||
**Note on `.git` sandbox access:** Because this workspace (`/home/boki/repos/stock-bot`) is the main repository checkout rather than a linked `.git/worktrees/...` worktree, read-only git commands and the 5 git-dependent tests in `scripts/test/` succeeded inside the sandbox without indirection errors.
|
||||
### 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 (no exit `0` was fabricated inside the sandbox):
|
||||
|
||||
| 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` |
|
||||
|
||||
### 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. Gate-by-Gate Verification Table
|
||||
## 2. Sandbox-Runnable Gates (Sequential — Revision `56b73b7e663d293079ab7bac264950dfa7a68b00`)
|
||||
|
||||
### 2.1 Sandbox-Runnable Gates (Sequential)
|
||||
All seven sandbox-runnable gates exited `0` with zero failures and zero warnings:
|
||||
|
||||
| Gate | Command | Exit Code | Result / Exact Counts |
|
||||
| --- | --- | ---: | --- |
|
||||
| Typecheck | `bun run typecheck` | `0` | **PASS** (`tsc --project tsconfig.check.json --noEmit`, 0 errors) |
|
||||
| Contracts | `bun run test:contracts` | `0` | **PASS** (`tsc --project tsconfig.contracts.json --noEmit`, 0 errors) |
|
||||
| Lint | `bun run lint:check` | `0` | **PASS** (`eslint apps/stock libs tools test --ext .ts,.tsx --max-warnings 0`, 0 errors, 0 warnings) |
|
||||
| Utils tests | `bun run test:utils` | `0` | **PASS** (`32 pass`, `0 fail`, `59 expect()` calls across `3` files, `201ms`) |
|
||||
| Calculations tests | `bun run test:calculations` | `0` | **PASS** (`144 pass`, `0 fail`, `76,602 expect()` calls across `12` files, `814ms`) |
|
||||
| Native Rust tests | `CARGO_BUILD_JOBS=2 bun run test:native` | `0` | **PASS** (`1,078 passed`, `0 failed`, `4 ignored` across `49` test suites: `engine` lib `150 passed / 4 ignored`, `curate-etl` unit + integration/contract + doc-tests `928 passed / 0 failed`) |
|
||||
| Workspace Rust lib tests | `CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | `0` | **PASS** (`732 passed`, `0 failed`, `4 ignored` across `2` crates: `curate-etl` `582 passed`, `engine` `150 passed / 4 ignored`) |
|
||||
| Workspace build | `bun run build` | `0` | **PASS** (`29/29` packages succeeded via Turbo) |
|
||||
|
||||
### 2.2 Authoritative Unsandboxed Verification (`studio.config.json`)
|
||||
|
||||
| Gate | Command | Exit Code | Result / Exact Counts |
|
||||
| --- | --- | ---: | --- |
|
||||
| Studio build | `bun run build` | `0` | **PASS** (`29/29` packages) |
|
||||
| Studio full test suite | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test` | `0` | **PASS** (`3,648 pass`, `15 skip`, `0 fail`, `889,698 expect()` calls across `282` files, `193.45s`; isolated on `stock_bot_safety*` and Redis DB15) |
|
||||
| Sandbox-blocked Postgres pair rerun | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-run.test.ts test/postgres/security-master-export-curate-inputs.test.ts` | `0` | **PASS** (`2 pass`, `0 fail`, `116 expect()` calls across `2` files, `880ms`) |
|
||||
| Studio Rust half | `CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline` | `0` | **PASS** (`732 passed`, `0 failed`, `4 ignored`) |
|
||||
|
||||
### 2.3 Supplemental Python / Marimo Verification (Not Wired Into Automated Gates)
|
||||
|
||||
| Check | Command | Exit Code | Result |
|
||||
| --- | --- | ---: | --- |
|
||||
| Python SDK tests | `python/.venv/bin/pytest python/tests/ -v` | `0` | **PASS** (`5 passed` in `0.62s`) |
|
||||
| Marimo notebook check | `python/.venv/bin/marimo check --format=json research/notebooks/ca_shorts_filings_study.py` | `0` | **PASS** (`0 issues`, `errored: false`) |
|
||||
| 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 Sandbox `bun test` Failure Classification
|
||||
## 3. Full Unfiltered Sandbox `bun test` Triage (Revision `56b73b7e663d293079ab7bac264950dfa7a68b00`)
|
||||
|
||||
Unfiltered `bun test` was executed inside the sandbox (`5,838` lines captured to `/tmp/m2-baseline-bun-test.log`, subsequently deleted after analysis):
|
||||
- **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`)
|
||||
- **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).
|
||||
|
||||
- **Exit code:** `1`
|
||||
- **Totals:** `3,536 pass`, `125 skip`, `2 fail`, `888,395 expect()` calls across `282` files (`111.79s`).
|
||||
- **Git-dependent tooling suites in `scripts/test/`:** All 5 passed inside the sandbox (`43/43` tests: `audit-secrets-repo.test.ts` `11/11`, `benchmark-replay.test.ts` `12/12`, `benchmark-research.test.ts` `8/8`, `benchmark-sma.test.ts` `2/2`, `strategy-packaging.test.ts` `10/10`).
|
||||
- **Previous Auto Mode baseline failure attribution:** On `d52aa20b`, `test/unit/data-pipeline-rust-evaluation-doc.test.ts > contains all seven required sections in order` failed because `design/data-pipeline/rust-migration-evaluation.md` appended a numbered `## 8.` heading. Commit `56b73b7e` renamed that section to `## Addendum: ...`, and all `13/13` tests in `test/unit/data-pipeline-rust-evaluation-doc.test.ts` now pass.
|
||||
### Failure Classification Summary (10 files, 40 failures, 3 unhandled `beforeAll` errors)
|
||||
|
||||
### Complete Failure Classification Table (Every `(fail)` Entry in Full Log)
|
||||
| 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 |
|
||||
|
||||
| # | Test File | Test Name | Exact Error (Verbatim) | Classification | Authoritative Unsandboxed Status |
|
||||
| ---: | --- | --- | --- | --- | --- |
|
||||
| 1 | `test/postgres/security-master-run.test.ts` (line 37) | `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` | `error: Dedicated stock_bot_safety database required` (`createIsolatedFixture`, missing `PIPELINE_TEST_DATABASE_URL` pointing to `/stock_bot_safety*` because `/home/boki/.studio/test-env/stock-bot.env` and `127.0.0.1:5432` are outside the sandbox) | **(a) Expected sandbox-only** (PostgreSQL safety-URL guard; unlike `describe.skipIf(!url)` suites, fails closed inside `createIsolatedFixture()`) | **PASS** (`302ms`) |
|
||||
| 2 | `test/postgres/security-master-export-curate-inputs.test.ts` (line 35) | `exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*) > exports exact TSV bytes read-only and matches across chunkSize=1 and chunkSize=5000` | `error: Dedicated stock_bot_safety database required` (`createIsolatedFixture`, same missing `PIPELINE_TEST_DATABASE_URL` guard outside Studio's env) | **(a) Expected sandbox-only** (PostgreSQL safety-URL guard) | **PASS** (`318ms`) |
|
||||
### Individual Failing Test Names (All 40 Accounted For)
|
||||
|
||||
- **Real failures found (`(b)`):** **0**
|
||||
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 (Zero Code/Config Edits)
|
||||
## 4. Authoritative Unsandboxed Gate (Studio Runner — Revision `904def37e2e9cff5dce538c3d1f61ffca3594e9d`)
|
||||
|
||||
1. **`@modelcontextprotocol/sdk` absence & sandbox network allowlist:**
|
||||
- `@modelcontextprotocol/sdk` is **not present** in `bun.lock` or any `package.json` across the repository (`0` matches in `bun.lock`, root `package.json`, `apps/`, `libs/`, `tools/`).
|
||||
- `studio.config.json` (`agentExecution.programmer.networkDomains` lines 6–10 and `agentExecution.qa.networkDomains` lines 14–18) allows **only** `["crates.io", "index.crates.io", "static.crates.io"]` (no `registry.npmjs.org`).
|
||||
- **M2 implication:** Before implementing the MCP copilot server in `web-api` / standalone stdio+SSE wrapper, either pre-install/lock `@modelcontextprotocol/sdk` on the host outside the sandbox, extend the network allowlist, or implement the MCP JSON-RPC 2.0 stdio/SSE protocol directly with zero new npm dependencies.
|
||||
2. **Python SDK test suite is outside automated gates:**
|
||||
- Neither `python/tests/test_stockbot_sdk.py` nor `pytest` under `python/` is referenced or invoked by root `package.json`, `scripts/check.ts`, or `studio.config.json` `test.command` (`bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline`).
|
||||
- **M2 implication:** `python/tests/test_stockbot_sdk.py` (`5/5` currently passing locally) and `marimo check` will not run automatically during Studio gates unless explicitly wired in a future task; M2 PIT fundamentals / Feature Library Python work should account for this.
|
||||
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/`).
|
||||
- `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):**
|
||||
- `studio.config.json` sets `"designDir": "design"` (line 42), `"docs.pitch": "design/pitch.md"` (line 44), and `"docs.pillars": "design/pillars.md"` (line 45), while `docs.brand`, `docs.index`, `docs.plan`, `docs.milestones`, `docs.dataContracts`, `docs.validation`, `docs.dataPipeline`, and `docs.servers` (lines 46, 48–54) point to `docs/...`.
|
||||
- No `docs/` directory exists at the repository root (`ls: cannot access 'docs': No such file or directory`). All milestone and platform documents live under `design/` (specifically `design/MILESTONES.md` lines 83–103 for M2). `studio.config.json` was intentionally left untouched in this baseline verification task.
|
||||
|
||||
---
|
||||
|
||||
## 5. Verdict
|
||||
|
||||
**GREEN.** Baseline commit `56b73b7e663d293079ab7bac264950dfa7a68b00` (`master` / `dev`, descending from accepted M1 commit `d52aa20b`) passes all sandbox-runnable gates, has `0` real failures in full unfiltered `bun test` (`2` sandbox-only `PIPELINE_TEST_DATABASE_URL` guard errors that pass in Studio's unsandboxed run), and passes Studio's authoritative unsandboxed verification (`29/29` packages built, `3,648 pass / 15 skip / 0 fail` across `282` test files, `732` Rust workspace lib tests passing). Milestone M2 implementation is unblocked to proceed (starting with the MCP copilot server, then PIT fundamentals, QuestDB `10.2.0` intraday, and the Feature Library; T-127 remains deferred).
|
||||
- `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.
|
||||
|
|
|
|||
|
|
@ -196,3 +196,30 @@ 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<string | null>`. 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.
|
||||
|
||||
### `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 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`.
|
||||
|
||||
### Remaining M2 MCP Items (Later Tasks)
|
||||
|
||||
- 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.
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
6
libs/research/src/mcp/index.ts
Normal file
6
libs/research/src/mcp/index.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export * from './protocol';
|
||||
export * from './server';
|
||||
export * from './stdio';
|
||||
export * from './tools/analyze-signal';
|
||||
export * from './tools/event-study';
|
||||
export * from './tools/query-data';
|
||||
274
libs/research/src/mcp/protocol.ts
Normal file
274
libs/research/src/mcp/protocol.ts
Normal file
|
|
@ -0,0 +1,274 @@
|
|||
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<typeof jsonRpcIdSchema>;
|
||||
|
||||
/** 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<typeof jsonRpcRequestSchema>;
|
||||
|
||||
/** 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<typeof jsonRpcNotificationSchema>;
|
||||
|
||||
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<Record<string, JsonSchemaProperty>>;
|
||||
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<Record<string, JsonSchemaProperty>>;
|
||||
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;
|
||||
}
|
||||
|
||||
/** Valid MCP progress token (`string | finite number`). */
|
||||
export const mcpProgressTokenSchema = z.union([z.string(), z.number().finite()]);
|
||||
export type McpProgressToken = z.infer<typeof mcpProgressTokenSchema>;
|
||||
|
||||
/** Standard optional MCP `_meta` request/notification metadata bag. */
|
||||
export const mcpRequestMetaSchema = z
|
||||
.object({
|
||||
progressToken: mcpProgressTokenSchema.optional(),
|
||||
})
|
||||
.passthrough();
|
||||
export type McpRequestMeta = z.infer<typeof mcpRequestMetaSchema>;
|
||||
|
||||
const jsonObjectSchema = z.custom<Record<string, unknown>>(
|
||||
(value): value is Record<string, unknown> =>
|
||||
typeof value === 'object' && value !== null && !Array.isArray(value),
|
||||
{ message: 'Expected a JSON object.' }
|
||||
);
|
||||
|
||||
/** 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(),
|
||||
_meta: mcpRequestMetaSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Strict MCP `notifications/initialized` params schema. */
|
||||
export const mcpInitializedNotificationParamsSchema = z
|
||||
.object({
|
||||
_meta: mcpRequestMetaSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Strict MCP `ping` params schema. */
|
||||
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 (preserves own keys on `arguments`). */
|
||||
export const mcpToolsCallParamsSchema = z
|
||||
.object({
|
||||
name: z.string().min(1),
|
||||
arguments: jsonObjectSchema.optional(),
|
||||
_meta: mcpRequestMetaSchema.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,
|
||||
};
|
||||
}
|
||||
536
libs/research/src/mcp/server.ts
Normal file
536
libs/research/src/mcp/server.ts
Normal file
|
|
@ -0,0 +1,536 @@
|
|||
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<TInput> {
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
readonly inputSchema: z.ZodType<TInput, z.ZodTypeDef, unknown>;
|
||||
readonly jsonSchema?: JsonSchemaObject;
|
||||
readonly handler: (input: TInput) => Promise<McpToolCallResult> | 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<string, unknown>) => Promise<McpToolCallResult>;
|
||||
}
|
||||
|
||||
/** 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<string | null>;
|
||||
}
|
||||
|
||||
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<z.ZodRawShape>,
|
||||
outerDescription: string | undefined
|
||||
): JsonSchemaObject {
|
||||
const shape = schema.shape;
|
||||
const properties: Record<string, JsonSchemaProperty> = {};
|
||||
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<string, JsonSchemaProperty>;
|
||||
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('; ');
|
||||
}
|
||||
|
||||
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() : '';
|
||||
const safeName = SAFE_ERROR_NAME_RE.test(rawName) ? rawName : 'Error';
|
||||
return `${safeName}: 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<TInput>(definition: McpToolDefinition<TInput>): 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<string, unknown>): Promise<McpToolCallResult> {
|
||||
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<string, McpToolEntry>();
|
||||
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<string | null> {
|
||||
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}".`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
147
libs/research/src/mcp/stdio.ts
Normal file
147
libs/research/src/mcp/stdio.ts
Normal file
|
|
@ -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<Uint8Array | string>;
|
||||
|
||||
/** 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<void> {
|
||||
const ok = output.write(`${line}\n`);
|
||||
if (!ok && typeof output.once === 'function') {
|
||||
await new Promise<void>(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<void> {
|
||||
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<void> => {
|
||||
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<void> => {
|
||||
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<void> => {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
791
libs/research/src/mcp/tools/analyze-signal.ts
Normal file
791
libs/research/src/mcp/tools/analyze-signal.ts
Normal file
|
|
@ -0,0 +1,791 @@
|
|||
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 { UNIVERSE_REFS } from '../../market-data-store-duckdb';
|
||||
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 SUPPORTED_UNIVERSE_REF_SET: ReadonlySet<string> = 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);
|
||||
|
||||
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()
|
||||
.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<typeof analyzeSignalInputSchema>;
|
||||
|
||||
/** Server-side injected configuration for {@link createAnalyzeSignalTool}. */
|
||||
export interface AnalyzeSignalToolOptions {
|
||||
readonly store: MarketDataStore;
|
||||
readonly ledger: TrialLedgerExecutor;
|
||||
readonly vaultContext: Pick<VaultFenceContext, 'vaultCutoffTs'>;
|
||||
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 effectiveFrom: string;
|
||||
readonly effectiveTo: string;
|
||||
readonly effectiveAsOf: string;
|
||||
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<Record<SignalPanelErrorCode, string>> = {
|
||||
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<Record<SignalStudyErrorCode, string>> = {
|
||||
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<Partial<Record<TrialLedgerErrorCode, string>>> = {
|
||||
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<number>,
|
||||
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 > asOfMs ||
|
||||
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<number>,
|
||||
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 effectiveFrom: string;
|
||||
readonly effectiveTo: string;
|
||||
readonly effectiveAsOf: string;
|
||||
}): SignalStudyExpression {
|
||||
const { input, listingIds, universeSnapshotDate, effectiveFrom, effectiveTo, effectiveAsOf } =
|
||||
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,
|
||||
effectiveFrom,
|
||||
effectiveTo,
|
||||
effectiveAsOf,
|
||||
},
|
||||
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<McpToolCallResult> {
|
||||
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,
|
||||
effectiveFrom: fenced.canonicalFrom,
|
||||
effectiveTo: fenced.canonicalTo,
|
||||
effectiveAsOf: fenced.canonicalAsOf,
|
||||
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: fenced.canonicalFrom,
|
||||
to: fenced.canonicalTo,
|
||||
adjustment: input.adjustment,
|
||||
asOf: fenced.canonicalAsOf,
|
||||
scope: 'vault_fenced',
|
||||
})
|
||||
);
|
||||
|
||||
const rawShortsTable = await store.shortsAsOf({
|
||||
listingIds,
|
||||
from: fenced.canonicalFrom,
|
||||
to: fenced.canonicalTo,
|
||||
asOf: fenced.canonicalAsOf,
|
||||
});
|
||||
|
||||
const listingIdSet = new Set<number>(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,
|
||||
effectiveFrom: fenced.canonicalFrom,
|
||||
effectiveTo: fenced.canonicalTo,
|
||||
effectiveAsOf: fenced.canonicalAsOf,
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
1032
libs/research/src/mcp/tools/event-study.ts
Normal file
1032
libs/research/src/mcp/tools/event-study.ts
Normal file
File diff suppressed because it is too large
Load diff
249
libs/research/src/mcp/tools/query-data.ts
Normal file
249
libs/research/src/mcp/tools/query-data.ts
Normal file
|
|
@ -0,0 +1,249 @@
|
|||
import { z } from 'zod';
|
||||
import {
|
||||
type BarRecord,
|
||||
type MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
type VaultFenceContext,
|
||||
} from '../../market-data-store';
|
||||
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,
|
||||
resolveUniverseDate,
|
||||
validateVaultCutoffTs,
|
||||
} from './vault-fenced-input';
|
||||
|
||||
/** 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 = MCP_MAX_LISTING_IDS;
|
||||
|
||||
/**
|
||||
* 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: 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)
|
||||
.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(hasExclusiveListingSelector, EXCLUSIVE_LISTING_SELECTOR_MESSAGE);
|
||||
|
||||
export type QueryDataInput = z.infer<typeof queryDataInputSchema>;
|
||||
|
||||
/** Configuration for {@link createQueryDataTool}. */
|
||||
export interface QueryDataToolOptions {
|
||||
readonly store: MarketDataStore;
|
||||
readonly vaultContext: Pick<VaultFenceContext, 'vaultCutoffTs'>;
|
||||
}
|
||||
|
||||
/** 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 validateFactoryOptions(options: QueryDataToolOptions): number {
|
||||
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'
|
||||
);
|
||||
}
|
||||
|
||||
return validateVaultCutoffTs(options.vaultContext?.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 {
|
||||
const vaultCutoffTs = validateFactoryOptions(options);
|
||||
const { store } = options;
|
||||
|
||||
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<McpToolCallResult> {
|
||||
try {
|
||||
const fenced = fenceVaultQueryBounds(
|
||||
{
|
||||
from: input.from,
|
||||
to: input.to,
|
||||
asOf: input.asOf,
|
||||
},
|
||||
vaultCutoffTs
|
||||
);
|
||||
|
||||
const effectiveLimit = input.limit;
|
||||
let listingIds: number[];
|
||||
|
||||
if (input.universe !== undefined) {
|
||||
const universeDate = resolveUniverseDate(
|
||||
fenced.toMs,
|
||||
fenced.toSubMs,
|
||||
fenced.asOfMs,
|
||||
fenced.asOfSubMs
|
||||
);
|
||||
const resolved = await store.universe({
|
||||
ref: input.universe,
|
||||
date: universeDate,
|
||||
});
|
||||
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 stream = store.bars({
|
||||
listingIds,
|
||||
timeframe: input.timeframe,
|
||||
from: input.from,
|
||||
to: fenced.effectiveFencedTo,
|
||||
adjustment: input.adjustment,
|
||||
asOf: fenced.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) {
|
||||
const mapped = formatMappedStoreError(err);
|
||||
if (mapped !== null) {
|
||||
return mapped;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
341
libs/research/src/mcp/tools/vault-fenced-input.ts
Normal file
341
libs/research/src/mcp/tools/vault-fenced-input.ts
Normal file
|
|
@ -0,0 +1,341 @@
|
|||
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 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;
|
||||
}
|
||||
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 fromSubMs: number;
|
||||
readonly toSubMs: number;
|
||||
readonly asOfSubMs: number;
|
||||
readonly canonicalFrom: string;
|
||||
readonly canonicalTo: string;
|
||||
readonly canonicalAsOf: string;
|
||||
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 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;
|
||||
const effectiveFencedAsOf =
|
||||
fenced.clampedAsOf || input.asOf === undefined
|
||||
? formatUtcIsoWithMicros(fenced.asOfMs, 999)
|
||||
: input.asOf;
|
||||
|
||||
return {
|
||||
...fenced,
|
||||
vaultCutoffDate: utcDateOf(vaultCutoffTs),
|
||||
fromSubMs,
|
||||
toSubMs,
|
||||
asOfSubMs,
|
||||
canonicalFrom,
|
||||
canonicalTo,
|
||||
canonicalAsOf,
|
||||
effectiveFencedTo,
|
||||
effectiveFencedAsOf,
|
||||
};
|
||||
}
|
||||
|
||||
const SAFE_VALIDATION_FIELDS: ReadonlySet<string> = new Set([
|
||||
'from',
|
||||
'to',
|
||||
'asOf',
|
||||
'date',
|
||||
'ref',
|
||||
'listingIds',
|
||||
'timeframe',
|
||||
'adjustment',
|
||||
'scope',
|
||||
'limit',
|
||||
]);
|
||||
|
||||
const SAFE_STORE_METHODS: ReadonlySet<string> = new Set([
|
||||
'bars',
|
||||
'crossSection',
|
||||
'fundamentalsAsOf',
|
||||
'events',
|
||||
'shortsAsOf',
|
||||
'macroAsOf',
|
||||
'fx',
|
||||
'universe',
|
||||
]);
|
||||
|
||||
const ADJ_SNAPSHOT_ERROR_MESSAGES: Readonly<Record<AdjFactorsSnapshotErrorCode, string>> = {
|
||||
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;
|
||||
}
|
||||
820
libs/research/test/mcp-analyze-signal-qa.test.ts
Normal file
820
libs/research/test/mcp-analyze-signal-qa.test.ts
Normal file
|
|
@ -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<number, number[]>();
|
||||
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<BarBatch> {
|
||||
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<Table> {
|
||||
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<number[]> {
|
||||
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<Row = Record<string, unknown>>(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<string, unknown>;
|
||||
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<string, unknown> {
|
||||
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<string, unknown>;
|
||||
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<string, unknown>;
|
||||
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<string, unknown>) => {
|
||||
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<string, unknown>;
|
||||
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<typeof createStore>[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);
|
||||
});
|
||||
});
|
||||
1595
libs/research/test/mcp-analyze-signal.test.ts
Normal file
1595
libs/research/test/mcp-analyze-signal.test.ts
Normal file
File diff suppressed because it is too large
Load diff
595
libs/research/test/mcp-edge-cases.test.ts
Normal file
595
libs/research/test/mcp-edge-cases.test.ts
Normal file
|
|
@ -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<BarBatch> {
|
||||
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<number[]> {
|
||||
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<string, unknown>,
|
||||
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<string | Uint8Array> {
|
||||
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<string, unknown>[] = [
|
||||
{ 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/);
|
||||
});
|
||||
});
|
||||
1116
libs/research/test/mcp-event-study-qa.test.ts
Normal file
1116
libs/research/test/mcp-event-study-qa.test.ts
Normal file
File diff suppressed because it is too large
Load diff
1451
libs/research/test/mcp-event-study.test.ts
Normal file
1451
libs/research/test/mcp-event-study.test.ts
Normal file
File diff suppressed because it is too large
Load diff
454
libs/research/test/mcp-protocol.test.ts
Normal file
454
libs/research/test/mcp-protocol.test.ts
Normal file
|
|
@ -0,0 +1,454 @@
|
|||
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<string, unknown>;
|
||||
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 or paths', async () => {
|
||||
const boomTool = defineMcpTool({
|
||||
name: 'explode',
|
||||
description: 'Always throws an error.',
|
||||
inputSchema: z.object({}).strict(),
|
||||
handler() {
|
||||
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;
|
||||
},
|
||||
});
|
||||
|
||||
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: 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({
|
||||
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');
|
||||
});
|
||||
});
|
||||
783
libs/research/test/mcp-query-data.test.ts
Normal file
783
libs/research/test/mcp-query-data.test.ts
Normal file
|
|
@ -0,0 +1,783 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
type BarBatch,
|
||||
type BarRecord,
|
||||
type MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
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,
|
||||
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<BarBatch> {
|
||||
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<number[]> {
|
||||
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<string, unknown>
|
||||
): 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<string, unknown>;
|
||||
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<string, unknown>[] = [
|
||||
{
|
||||
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 and unexpected errors without leaking paths or stack traces', async () => {
|
||||
const domainErrors: readonly [Error, string][] = [
|
||||
[new VaultScopeNotAuthorizedError(), 'VaultScopeNotAuthorizedError'],
|
||||
[
|
||||
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) {
|
||||
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('/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<number, readonly BarRecord[]>([
|
||||
[101, [janBar101]],
|
||||
[202, [janBar202]],
|
||||
]);
|
||||
|
||||
const universeDates: string[] = [];
|
||||
const store: MarketDataStore = {
|
||||
async universe(q: UniverseQuery): Promise<number[]> {
|
||||
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<BarBatch> {
|
||||
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 () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
195
libs/research/test/mcp-stdio.test.ts
Normal file
195
libs/research/test/mcp-stdio.test.ts
Normal file
|
|
@ -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<Uint8Array | string> {
|
||||
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<string, unknown> };
|
||||
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<void>(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<string, unknown> };
|
||||
expect(errResp.id).toBeNull();
|
||||
expect(errResp.error.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR);
|
||||
expect(okResp.id).toBe(2);
|
||||
expect(okResp.result).toEqual({});
|
||||
});
|
||||
});
|
||||
178
test/unit/m2-baseline-report-doc.test.ts
Normal file
178
test/unit/m2-baseline-report-doc.test.ts
Normal file
|
|
@ -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<string, string[]>();
|
||||
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');
|
||||
});
|
||||
});
|
||||
|
|
@ -1553,6 +1553,40 @@ 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<K>` against periodic `events::QmFiling<K>` records (reusing `events::classify_form_type`, `FilingFormGroup::is_periodic_financial_report`, and `events::parse_filing_timefiled`) using an ordered `BTreeMap<K, StatutoryLagVenue>` (`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. 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<K>` 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.
|
||||
- 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`
|
||||
|
||||
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 `0xd5f693a28da4d1f0` hashing all row fields, ordered snapshot slots, TTM flows, and provenance):
|
||||
|
||||
- **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`)
|
||||
|
||||
All `curate-*` commands read local TSV and concatenated raw-BSON files produced by the read-only exporters in `@stock-bot/data-pipeline`:
|
||||
|
|
|
|||
951
tools/curate-etl/src/bars_1m.rs
Normal file
951
tools/curate-etl/src/bars_1m.rs
Normal file
|
|
@ -0,0 +1,951 @@
|
|||
//! 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::borrow::Borrow;
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::{BinaryHeap, HashMap};
|
||||
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<K = String> {
|
||||
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<K = String> {
|
||||
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<K = String> {
|
||||
pub rows: Vec<Bar1mRow<K>>,
|
||||
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<K = String> {
|
||||
pub key: K,
|
||||
/// 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<i64>,
|
||||
}
|
||||
|
||||
impl<K> DailySessionClose<K> {
|
||||
/// 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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<K = String>
|
||||
where
|
||||
K: Eq + Hash,
|
||||
{
|
||||
per_date: HashMap<i32, i64>,
|
||||
per_listing_date: HashMap<K, HashMap<i32, Option<i64>>>,
|
||||
}
|
||||
|
||||
impl<K: Eq + Hash> SessionCloseCutoffPolicy<K> {
|
||||
/// 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<I>(mut self, cutoffs: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = (i32, i64)>,
|
||||
{
|
||||
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<i64>) {
|
||||
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<i64>,
|
||||
) -> 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<I>(mut self, cutoffs: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = (K, i32, Option<i64>)>,
|
||||
{
|
||||
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]
|
||||
pub fn cutoff_for(&self, key: &K, session_date: i32) -> Option<i64> {
|
||||
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<K: Eq + Hash> DailySessionClose<K> {
|
||||
/// Converts a raw [`Bar1dRow`] into a [`DailySessionClose`] using an explicit
|
||||
/// [`SessionCloseCutoffPolicy`].
|
||||
#[inline]
|
||||
pub fn from_bar_1d(row: Bar1dRow<K>, cutoff_policy: &SessionCloseCutoffPolicy<K>) -> 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,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a borrowed [`Bar1dRow`] into a [`DailySessionClose`] using an explicit
|
||||
/// [`SessionCloseCutoffPolicy`].
|
||||
#[inline]
|
||||
pub fn from_bar_1d_ref(row: &Bar1dRow<K>, cutoff_policy: &SessionCloseCutoffPolicy<K>) -> 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A single session-close cross-check mismatch sample retained for downstream reporting.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct SessionCloseMismatchSample<K = String> {
|
||||
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<K = String> {
|
||||
pub stats: SessionCloseStats,
|
||||
pub mismatch_samples: Vec<SessionCloseMismatchSample<K>>,
|
||||
}
|
||||
|
||||
#[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<K> {
|
||||
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<K>(
|
||||
a: &ValidatedIntradayBar<K>,
|
||||
b: &ValidatedIntradayBar<K>,
|
||||
) -> 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<K, B>(bars: B, splits: &SplitTable<K>) -> Bars1mBuild<K>
|
||||
where
|
||||
K: Ord + Eq + Hash + Clone,
|
||||
B: IntoIterator<Item = EodIntradayBar<K>>,
|
||||
{
|
||||
let bars_iter = bars.into_iter();
|
||||
let mut valid_bars: Vec<ValidatedIntradayBar<K>> = 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<Bar1mRow<K>> = 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
|
||||
|| (first.volume > 0.0 && 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<K>(SessionCloseMismatchSample<K>);
|
||||
|
||||
impl<K: Ord> Ord for HeapSessionCloseMismatch<K> {
|
||||
#[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<K: Ord> PartialOrd for HeapSessionCloseMismatch<K> {
|
||||
#[inline]
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: Ord> PartialEq for HeapSessionCloseMismatch<K> {
|
||||
#[inline]
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.cmp(other) == Ordering::Equal
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: Ord> Eq for HeapSessionCloseMismatch<K> {}
|
||||
|
||||
struct LastRthBar<'a, K> {
|
||||
key: &'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 select_last_rth_bars<'a, K, I>(
|
||||
rth_sorted: I,
|
||||
valid_daily: &[DailySessionClose<K>],
|
||||
) -> Vec<LastRthBar<'a, K>>
|
||||
where
|
||||
K: Ord + 'a,
|
||||
I: IntoIterator<Item = (&'a K, i32, i64, f64)>,
|
||||
{
|
||||
let mut result: Vec<LastRthBar<'a, K>> = Vec::new();
|
||||
let mut daily_idx = 0usize;
|
||||
|
||||
let mut cur_group: Option<(&'a K, i32, Option<i64>)> = None;
|
||||
let mut cur_best: Option<LastRthBar<'a, K>> = 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<K>],
|
||||
valid_daily: &[DailySessionClose<K>],
|
||||
) -> Vec<LastRthBar<'a, K>> {
|
||||
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 {
|
||||
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<(&'a K, i32, i64, f64)> = rows_1m
|
||||
.iter()
|
||||
.filter(|row| row.session == IntradaySession::Rth)
|
||||
.map(|row| (&row.key, row.session_date, row.ts, row.close))
|
||||
.collect();
|
||||
|
||||
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))
|
||||
});
|
||||
|
||||
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)` 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 (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<K, D, I>(
|
||||
rows_1m: &[Bar1mRow<K>],
|
||||
bars_1d_closes: I,
|
||||
rel_tolerance: f64,
|
||||
) -> Result<SessionCloseCheck<K>, Bars1mError>
|
||||
where
|
||||
K: Ord + Clone,
|
||||
D: Into<DailySessionClose<K>>,
|
||||
I: IntoIterator<Item = D>,
|
||||
{
|
||||
if !rel_tolerance.is_finite() || rel_tolerance < 0.0 {
|
||||
return Err(Bars1mError::InvalidTolerance { rel_tolerance });
|
||||
}
|
||||
|
||||
let mut stats = SessionCloseStats::default();
|
||||
|
||||
let daily_iter = bars_1d_closes.into_iter();
|
||||
let mut valid_daily: Vec<DailySessionClose<K>> = Vec::with_capacity(daily_iter.size_hint().0);
|
||||
for item in daily_iter {
|
||||
let daily: DailySessionClose<K> = 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 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;
|
||||
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 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<HeapSessionCloseMismatch<K>> =
|
||||
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
|
||||
.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<SessionCloseMismatchSample<K>> =
|
||||
heap.into_sorted_vec().into_iter().map(|w| w.0).collect();
|
||||
|
||||
Ok(SessionCloseCheck {
|
||||
stats,
|
||||
mismatch_samples,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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<K, R, I>(
|
||||
rows_1m: &[Bar1mRow<K>],
|
||||
bars_1d: I,
|
||||
cutoff_policy: &SessionCloseCutoffPolicy<K>,
|
||||
rel_tolerance: f64,
|
||||
) -> Result<SessionCloseCheck<K>, Bars1mError>
|
||||
where
|
||||
K: Ord + Eq + Hash + Clone,
|
||||
R: Borrow<Bar1dRow<K>>,
|
||||
I: IntoIterator<Item = R>,
|
||||
{
|
||||
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;
|
||||
878
tools/curate-etl/src/bars_1m_tests.rs
Normal file
878
tools/curate-etl/src/bars_1m_tests.rs
Normal file
|
|
@ -0,0 +1,878 @@
|
|||
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<K>(
|
||||
key: K,
|
||||
ts: i64,
|
||||
open: f64,
|
||||
high: f64,
|
||||
low: f64,
|
||||
close: f64,
|
||||
volume: f64,
|
||||
) -> EodIntradayBar<K> {
|
||||
EodIntradayBar {
|
||||
key,
|
||||
ts,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
}
|
||||
}
|
||||
|
||||
fn daily_row<K>(key: K, session_date: i32, close: f64) -> Bar1dRow<K> {
|
||||
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 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);
|
||||
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 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);
|
||||
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<String> = 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 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);
|
||||
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 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
|
||||
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, 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, 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);
|
||||
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::<i32, DailySessionClose<i32>, _>(
|
||||
&[],
|
||||
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 (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_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<i32> = 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, 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),
|
||||
// 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,
|
||||
);
|
||||
// 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 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_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, 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);
|
||||
|
||||
// Verify DailySessionClose::from_bar_1d / from_bar_1d_ref parity with the cutoff policy.
|
||||
let converted_owned: Vec<DailySessionClose<i32>> = 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,
|
||||
[daily_row(1, half_day, 105.5)],
|
||||
&cutoff_policy,
|
||||
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);
|
||||
|
||||
// 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,
|
||||
[daily_row(1, half_day, 101.25)],
|
||||
&SessionCloseCutoffPolicy::standard_rth(),
|
||||
0.005,
|
||||
)
|
||||
.unwrap();
|
||||
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_against_bars_1d(
|
||||
&post_cutoff_only.rows,
|
||||
[daily_row(9, half_day, 101.25)],
|
||||
&cutoff_policy,
|
||||
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);
|
||||
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::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::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::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);
|
||||
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::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::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, 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);
|
||||
|
||||
// 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");
|
||||
}
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -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,
|
||||
|
|
@ -17,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,
|
||||
|
|
@ -70,9 +72,11 @@ pub enum CliAction {
|
|||
BenchAdj(usize),
|
||||
BenchCorporateActions(usize),
|
||||
BenchBars(usize),
|
||||
BenchBars1m(usize),
|
||||
BenchFx(usize),
|
||||
BenchShorts(usize),
|
||||
BenchEvents(usize),
|
||||
BenchFundamentals(usize),
|
||||
BenchProviderMapping(usize),
|
||||
BenchParquetBars(usize),
|
||||
BenchParquetShorts(usize),
|
||||
|
|
@ -128,9 +132,11 @@ 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\
|
||||
{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\
|
||||
|
|
@ -173,9 +179,11 @@ 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\
|
||||
{name} bench-fundamentals [rows]\n\
|
||||
{name} bench-provider-mapping [lookups]\n\
|
||||
{name} bench-parquet-bars [rows]\n\
|
||||
{name} bench-parquet-shorts [rows]\n\
|
||||
|
|
@ -1462,6 +1470,14 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
)),
|
||||
},
|
||||
["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::<usize>() {
|
||||
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::<usize>() {
|
||||
Ok(n) if n > 0 => Ok(CliAction::BenchFx(n)),
|
||||
|
|
@ -1486,6 +1502,18 @@ pub fn parse_args(args: &[String]) -> Result<CliAction, String> {
|
|||
)),
|
||||
},
|
||||
["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::<usize>() {
|
||||
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,
|
||||
)),
|
||||
|
|
@ -2088,6 +2116,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 +2148,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 +2176,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!(
|
||||
|
|
@ -3374,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());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
1030
tools/curate-etl/src/fundamentals.rs
Normal file
1030
tools/curate-etl/src/fundamentals.rs
Normal file
File diff suppressed because it is too large
Load diff
1069
tools/curate-etl/src/fundamentals_tests.rs
Normal file
1069
tools/curate-etl/src/fundamentals_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -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;
|
||||
|
|
@ -13,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;
|
||||
|
|
@ -36,6 +38,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, 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,
|
||||
BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD,
|
||||
|
|
@ -93,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,
|
||||
|
|
@ -141,9 +160,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,
|
||||
|
|
|
|||
|
|
@ -4,14 +4,14 @@ 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,
|
||||
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,
|
||||
|
|
@ -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");
|
||||
|
|
@ -437,6 +482,51 @@ 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={} 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,
|
||||
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.observations_dropped_stale_estimate,
|
||||
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,
|
||||
|
|
|
|||
|
|
@ -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<i64, SessionCloseEr
|
|||
Ok((i64::from(epoch_day) * 86_400 + utc_hour_secs) * 1_000_000)
|
||||
}
|
||||
|
||||
/// Converts a UTC timestamp (microseconds since the Unix epoch) into North American Eastern Time
|
||||
/// (`America/New_York` / `America/Toronto`) calendar date, minute-of-day (`0..=1439`), and DST
|
||||
/// state.
|
||||
///
|
||||
/// Reuses the crate's `1976..=2030` DST table across all three historical eras (`1976–1986`,
|
||||
/// `1987–2006`, `2007–2030`) with exact `02:00 EST` (`07:00 UTC`) spring-forward and `02:00 EDT`
|
||||
/// (`06:00 UTC`) fall-back transitions. Returns [`SessionCloseError::TimestampOutOfRange`] for any
|
||||
/// timestamp outside `[SESSION_MIN_SUPPORTED_UTC_MICROS, SESSION_MAX_SUPPORTED_UTC_MICROS]`.
|
||||
#[inline]
|
||||
pub fn utc_micros_to_et_local(utc_micros: i64) -> Result<EtLocalDateTime, SessionCloseError> {
|
||||
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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
584
tools/curate-etl/tests/bars_1m_qa_contract.rs
Normal file
584
tools/curate-etl/tests/bars_1m_qa_contract.rs
Normal file
|
|
@ -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<K: Ord + std::fmt::Debug>(rows: &[Bar1mRow<K>]) {
|
||||
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<f64> = built.rows.iter().map(|r| r.close).collect();
|
||||
let volumes: Vec<f64> = 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<String> = 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<String> = 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<String> = 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<String> = 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<String> = 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<String> = 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));
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue