diff --git a/database/postgres/init/37-research-findings.sql b/database/postgres/init/37-research-findings.sql deleted file mode 100644 index b4c800ac..00000000 --- a/database/postgres/init/37-research-findings.sql +++ /dev/null @@ -1,99 +0,0 @@ --- Research findings & provider caveats schema (M2.1i) --- Research track migration: creates append-only findings and provider_caveats tables, --- lookup/idempotency indexes, and immutability triggers reusing --- reject_research_evidence_mutation() from 17-research-retention.sql. - -CREATE OR REPLACE FUNCTION research_trim_ecmascript(value TEXT) -RETURNS TEXT -LANGUAGE SQL -IMMUTABLE -STRICT -AS $$ - -- Explicit ECMAScript WhiteSpace + LineTerminator set so nonblank checks and - -- trimmed length caps match String.prototype.trim() regardless of DB collation. - SELECT btrim( - value, - U&'\0009\000A\000B\000C\000D\0020\00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\2028\2029\202F\205F\3000\FEFF' - ); -$$; - -CREATE OR REPLACE FUNCTION research_finding_refs_valid(refs TEXT[], max_len INTEGER) -RETURNS BOOLEAN -LANGUAGE SQL -IMMUTABLE -STRICT -AS $$ - SELECT COALESCE(array_ndims(refs), 1) = 1 - AND NOT EXISTS ( - SELECT 1 - FROM unnest(refs) AS r - WHERE r IS NULL - OR char_length(r) > max_len - ); -$$; - -CREATE TABLE IF NOT EXISTS findings ( - id TEXT PRIMARY KEY - CHECK (research_trim_ecmascript(id) <> ''), - kind TEXT NOT NULL - CHECK (kind IN ('finding', 'dead_end')), - title TEXT NOT NULL - CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256), - summary TEXT NOT NULL - CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096), - status TEXT NOT NULL DEFAULT 'pending_review' - CHECK (research_trim_ecmascript(status) <> ''), - created_at TIMESTAMPTZ NOT NULL, - trial_refs TEXT[] NOT NULL - CHECK (cardinality(trial_refs) <= 32) - CHECK (COALESCE(array_ndims(trial_refs), 1) = 1) - CHECK (research_finding_refs_valid(trial_refs, 256)), - evidence_refs TEXT[] NOT NULL - CHECK (cardinality(evidence_refs) <= 32) - CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) - CHECK (research_finding_refs_valid(evidence_refs, 256)), - idempotency_key TEXT - CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128)) -); - -CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key - ON findings (idempotency_key) - WHERE idempotency_key IS NOT NULL; - -CREATE INDEX IF NOT EXISTS idx_findings_created_at - ON findings (created_at); - -CREATE TABLE IF NOT EXISTS provider_caveats ( - id TEXT PRIMARY KEY - CHECK (research_trim_ecmascript(id) <> ''), - provider TEXT NOT NULL - CHECK (research_trim_ecmascript(provider) <> ''), - dataset TEXT NOT NULL - CHECK (research_trim_ecmascript(dataset) <> ''), - caveat TEXT NOT NULL - CHECK (research_trim_ecmascript(caveat) <> ''), - created_at TIMESTAMPTZ NOT NULL DEFAULT now() -); - -CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider - ON provider_caveats (lower(provider)); - -DROP TRIGGER IF EXISTS findings_retained ON findings; -CREATE TRIGGER findings_retained - BEFORE UPDATE OR DELETE ON findings - FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation(); - -DROP TRIGGER IF EXISTS findings_no_truncate ON findings; -CREATE TRIGGER findings_no_truncate - BEFORE TRUNCATE ON findings - FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation(); - -DROP TRIGGER IF EXISTS provider_caveats_retained ON provider_caveats; -CREATE TRIGGER provider_caveats_retained - BEFORE UPDATE OR DELETE ON provider_caveats - FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation(); - -DROP TRIGGER IF EXISTS provider_caveats_no_truncate ON provider_caveats; -CREATE TRIGGER provider_caveats_no_truncate - BEFORE TRUNCATE ON provider_caveats - FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation(); diff --git a/design/DATA-CONTRACTS.md b/design/DATA-CONTRACTS.md index 837da47a..9f973afe 100644 --- a/design/DATA-CONTRACTS.md +++ b/design/DATA-CONTRACTS.md @@ -194,65 +194,6 @@ The M1 exit gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD 2. `uncovered_venue` — listings on exchanges absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`, `ceo`, and `ib:AEQLIT`, plus `ceo:NEOE` where EODHD carries only 19 of 587 listings). 3. `non_equity_instrument` — non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX inactive shells `.H`, TSXV CPCs `.P`, and exchange test symbols). -### Research Knowledge & Findings Schema (PostgreSQL, Append-Only) - -Applied via `@stock-bot/postgres` (`research` migration track, `database/postgres/init/37-research-findings.sql`, immediately after `36-trial-ledger.sql`). Owned by Stock Bot research alongside `trial_ledger` and `vault_evaluations` (see [`design/VALIDATION-AND-RIGOR.md`](VALIDATION-AND-RIGOR.md) §2A and §3 for those tables). - -- **Research-visible boundary:** `findings` and `provider_caveats` store research-visible empirical evidence only. Callers and MCP adapters (`file_finding`, `read_knowledge`) are responsible for verifying that every `trial_ref` belongs to the research-visible `trial_ledger` and for excluding Vault holdout observations or Vault-only evidence from stored text and opaque `evidence_refs`. -- **Append-only enforcement:** Both tables reuse `reject_research_evidence_mutation()` from `17-research-retention.sql` via row-level `BEFORE UPDATE OR DELETE` (`findings_retained`, `provider_caveats_retained`) and statement-level `BEFORE TRUNCATE` (`findings_no_truncate`, `provider_caveats_no_truncate`) triggers, raising SQLSTATE `23514` on any mutation attempt. -- **Character-length & whitespace convention:** SQL `CHECK` constraints enforce PostgreSQL `char_length(...)` (Unicode code points) matching the MCP tool caps (`title` trimmed `1..256`, `summary` trimmed `1..4096`, each ref `<= 256`, `idempotency_key` `1..128`). Nonblank and trimmed-length checks use `research_trim_ecmascript(...)`, which strips the explicit 25-character ECMAScript `WhiteSpace` + `LineTerminator` set (`U+0009`..`U+000D`, `U+0020`, `U+00A0`, `U+1680`, `U+2000`..`U+200A`, `U+2028`, `U+2029`, `U+202F`, `U+205F`, `U+3000`, `U+FEFF`) regardless of database collation. JavaScript/Zod validation counts UTF-16 code units, which can reach the same numeric limit sooner for supplementary Unicode characters. - -```sql -CREATE TABLE IF NOT EXISTS findings ( - id TEXT PRIMARY KEY - CHECK (research_trim_ecmascript(id) <> ''), - kind TEXT NOT NULL - CHECK (kind IN ('finding', 'dead_end')), - title TEXT NOT NULL - CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256), - summary TEXT NOT NULL - CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096), - status TEXT NOT NULL DEFAULT 'pending_review' - CHECK (research_trim_ecmascript(status) <> ''), - created_at TIMESTAMPTZ NOT NULL, - trial_refs TEXT[] NOT NULL - CHECK (cardinality(trial_refs) <= 32) - CHECK (COALESCE(array_ndims(trial_refs), 1) = 1) - CHECK (research_finding_refs_valid(trial_refs, 256)), - evidence_refs TEXT[] NOT NULL - CHECK (cardinality(evidence_refs) <= 32) - CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1) - CHECK (research_finding_refs_valid(evidence_refs, 256)), - idempotency_key TEXT - CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128)) -); - -CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key - ON findings (idempotency_key) - WHERE idempotency_key IS NOT NULL; - -CREATE INDEX IF NOT EXISTS idx_findings_created_at - ON findings (created_at); - -CREATE TABLE IF NOT EXISTS provider_caveats ( - id TEXT PRIMARY KEY - CHECK (research_trim_ecmascript(id) <> ''), - provider TEXT NOT NULL - CHECK (research_trim_ecmascript(provider) <> ''), - dataset TEXT NOT NULL - CHECK (research_trim_ecmascript(dataset) <> ''), - caveat TEXT NOT NULL - CHECK (research_trim_ecmascript(caveat) <> ''), - created_at TIMESTAMPTZ NOT NULL DEFAULT now() -); - -CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider - ON provider_caveats (lower(provider)); -``` - -- **Reference arrays (`trial_refs`, `evidence_refs`):** Stored as opaque 1-dimensional `TEXT[]` arrays (empty arrays permitted via `COALESCE(array_ndims(...), 1) = 1`, max 32 entries each, no `NULL` elements, max 256 chars per entry enforced via `research_finding_refs_valid`). Reference normalization, deduplication, minimum `trial_refs` count, and research-visibility checks remain in the MCP tool/adapter layer. -- **Indexes:** `idx_findings_idempotency_key` (partial unique `WHERE idempotency_key IS NOT NULL`) supports atomic compare-and-append idempotency while allowing multiple `NULL` keys; `idx_findings_created_at` supports chronological listing; `idx_provider_caveats_lower_provider` supports case-insensitive provider filtering in `read_knowledge`. - --- ## 3. Curated Storage Schemas @@ -276,9 +217,9 @@ Schemas: - **`adj_factors/part.parquet`**: `(listing_id INT32, ex_date DATE, split_factor DOUBLE, div_cash DOUBLE, div_currency VARCHAR, cum_split_factor DOUBLE, cum_total_factor DOUBLE, known_at TIMESTAMPTZ)`. - **`corporate_actions/part.parquet`**: `(listing_id INT32, ex_date DATE, declared_date DATE, kind VARCHAR, ratio DOUBLE, cash_amount DOUBLE, currency VARCHAR, successor_listing_id INT32, terminal_return DOUBLE, known_at TIMESTAMPTZ, known_at_source VARCHAR)`. - **`fundamentals_bitemporal/part.parquet`**: `(listing_id INT32, period_end DATE, fiscal_period VARCHAR, currency VARCHAR, known_at TIMESTAMPTZ, known_at_source VARCHAR, )`. -- **`fundamentals_pit/year=YYYY/part.parquet`**: Pre-resolved point-in-time snapshots partitioned by the UTC year of `effective_known_at`, sorted and unique by `(listing_id, effective_known_at)`: `(listing_id INT32 NOT NULL, effective_known_at TIMESTAMPTZ NOT NULL, known_at_source VARCHAR NOT NULL, has_estimated_lag BOOLEAN NOT NULL, period_end DATE NOT NULL, fiscal_period VARCHAR NOT NULL, currency VARCHAR NOT NULL, period_known_at TIMESTAMPTZ NOT NULL, revenue DOUBLE, net_income DOUBLE, operating_cash_flow DOUBLE, total_assets DOUBLE, total_equity DOUBLE, shares_outstanding DOUBLE, ttm_period_end DATE, ttm_currency VARCHAR, ttm_revenue DOUBLE, ttm_net_income DOUBLE, ttm_operating_cash_flow DOUBLE, ttm_has_estimated_lag BOOLEAN)` (all `ttm_*` columns are `NULL` when 4 consecutive standalone quarters in one currency are unavailable). Each snapshot computes: +- **`fundamentals_pit/year=YYYY/part.parquet`**: Wide pre-resolved point-in-time snapshots keyed by `(listing_id INT32, effective_known_at TIMESTAMPTZ)` where each row computes: $$\text{latest } k \text{ periods by } \texttt{period\_end} \text{ of } \left(\arg\max_{\texttt{known\_at} \le \texttt{effective\_known\_at}} \text{ per } (\texttt{listing\_id}, \texttt{period\_end})\right)$$ - forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2; the physical Parquet row flattens the latest visible resolved period (`periods[0]`) alongside the precomputed `ttm_*` columns (lagged slots `periods[1..]` are omitted). + forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2. - **`events/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, known_at_source VARCHAR, kind VARCHAR, subtype VARCHAR, payload_json VARCHAR)`. - **`shorts/part.parquet`**: `(listing_id INT32, report_date DATE, known_at TIMESTAMPTZ, shares_short DOUBLE, net_change DOUBLE, pct_float DOUBLE, source VARCHAR)`. - **`macro/part.parquet`**: `(country_iso VARCHAR, indicator VARCHAR, period_date DATE, known_at TIMESTAMPTZ, known_at_source VARCHAR, value DOUBLE)`. diff --git a/design/m2-baseline-report.md b/design/m2-baseline-report.md index 4bbefde1..c79daa1e 100644 --- a/design/m2-baseline-report.md +++ b/design/m2-baseline-report.md @@ -1,175 +1,95 @@ # Milestone M2 Baseline Verification Report (T-128 / M2.0) -**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`. +- **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. --- -## 1. Repository Provenance & Revision Mapping +## 1. Repository Provenance -### Revisions Checked +Executed from workspace root (`/home/boki/repos/stock-bot`): -| 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` | +| 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`)* | -### 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 | +**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. --- -## 2. Sandbox-Runnable Gates (Sequential — Revision `56b73b7e663d293079ab7bac264950dfa7a68b00`) +## 2. Gate-by-Gate Verification Table -All seven sandbox-runnable gates exited `0` with zero failures and zero warnings: +### 2.1 Sandbox-Runnable Gates (Sequential) -| 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 | +| 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`) | --- -## 3. Full Unfiltered Sandbox `bun test` Triage (Revision `56b73b7e663d293079ab7bac264950dfa7a68b00`) +## 3. Full Sandbox `bun test` Failure Classification -- **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). +Unfiltered `bun test` was executed inside the sandbox (`5,838` lines captured to `/tmp/m2-baseline-bun-test.log`, subsequently deleted after analysis): -### Failure Classification Summary (10 files, 40 failures, 3 unhandled `beforeAll` errors) +- **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. -| 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 | +### Complete Failure Classification Table (Every `(fail)` Entry in Full Log) -### Individual Failing Test Names (All 40 Accounted For) +| # | 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`) | -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` +- **Real failures found (`(b)`):** **0** --- -## 4. Authoritative Unsandboxed Gate (Studio Runner — Revision `904def37e2e9cff5dce538c3d1f61ffca3594e9d`) +## 4. Read-Only M2 Planning Facts (Zero Code/Config Edits) -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`). +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. 3. **`studio.config.json` `docs.*` path mismatch (left untouched):** - - `docs/` does not exist at the repository root. - - `studio.config.json` lines 43–55 still point `docs.index`, `docs.plan`, `docs.milestones`, `docs.dataContracts`, `docs.validation`, `docs.dataPipeline`, and `docs.servers` at `docs/...` paths, whereas the actual milestone and architecture documents live under `design/` (e.g., `design/MILESTONES.md` lines 83–103 contain the M2 checklist and exit criteria). `studio.config.json` was intentionally left untouched in this task. + - `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). diff --git a/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts b/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts deleted file mode 100644 index 9cff62f1..00000000 --- a/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts +++ /dev/null @@ -1,522 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdir, mkdtemp, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import type { MarketDataStore } from '@stock-bot/research/market-data-store'; -import type { FundamentalsAsOfQuery } from '@stock-bot/research/market-data-store-duckdb'; -import { createAnalyzeSignalTool, createMcpServer } from '@stock-bot/research/mcp'; -import { type SignalObservation, buildForwardReturnPanel, collectBars } from '@stock-bot/research/signal-panel'; -import { analyzeSignal } from '@stock-bot/research/signal-study'; -import type { TrialLedgerExecutor } from '@stock-bot/research/trial-ledger'; -import { createNodeDuckDbExecutor, openDuckDbMarketDataStore } from '../src/index'; - -// QA end-to-end evidence for T-149: MCP `analyze_signal` (source = fundamentals) -// driven against the REAL DuckDB `fundamentalsAsOf` over Hive Parquet files. -// - Dataset ID: `synthetic:qa-analyze-signal-fundamentals-real-duckdb:seed-20261206:v1` -// - Tool version: `mcp:analyze_signal:v1`; adjustment `raw`; horizon 3 sessions; modeled costs 0 -// - Pre-Vault window 2023-03-01..2023-05-12; Vault cutoff 2023-05-15T00:00:00.000Z -// - Bars: 6 listings (101..106), 20:00 UTC closes; 5 post-cutoff bars must be fenced out. -// - Fundamentals (ttm_revenue), all 13:00 UTC: -// 2023-03-10 verified (101..105), 2023-04-05 verified Q2 (all), -// 2023-04-18 same-month restatement (101..103, verified), -// 2023-04-18 estimated-lag update (104) -> omitted by DuckDB under default lag, -// 2023-04-20 verified row with NULL ttm_revenue (105) -> must not displace 2023-04-05. -// - Baseline: direct `buildForwardReturnPanel` + `analyzeSignal` over independently listed -// expected observations. - -const VAULT_CUTOFF_TS = Date.UTC(2023, 4, 15); -const VAULT_CUTOFF_DATE = '2023-05-15'; -const PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const LISTING_IDS = [101, 102, 103, 104, 105, 106] as const; -const HORIZON = 3; -// Listing with bars but no fundamentals rows at all (sparse coverage probe). -const UNCOVERED_LISTING_ID = 107; -const BAR_LISTING_IDS = [...LISTING_IDS, UNCOVERED_LISTING_ID] as const; - -const tempDirs: string[] = []; - -afterEach(async () => { - while (tempDirs.length > 0) { - const dir = tempDirs.pop(); - if (dir !== undefined) { - await rm(dir, { recursive: true, force: true }); - } - } -}); - -function createSeededRng(seed: number): () => number { - let s = seed >>> 0; - return () => { - s = (s + 0x6d2b79f5) >>> 0; - let t = s; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} - -function businessDates(start: string, count: number): string[] { - const out: string[] = []; - const d = new Date(`${start}T00:00:00Z`); - while (out.length < count) { - const dow = d.getUTCDay(); - if (dow !== 0 && dow !== 6) { - out.push(d.toISOString().slice(0, 10)); - } - d.setUTCDate(d.getUTCDate() + 1); - } - return out; -} - -function ms(date: string, hour: number): number { - return Date.parse(`${date}T${String(hour).padStart(2, '0')}:00:00.000Z`); -} - -interface PitRow { - readonly listingId: number; - readonly knownAt: string; // YYYY-MM-DD - readonly hour?: number; // UTC hour, default 13 - readonly ttm: number | null; - readonly estimated?: boolean; -} - -const BASE_PIT_ROWS: readonly PitRow[] = [ - ...[101, 102, 103, 104, 105].map((lid, l) => ({ - listingId: lid, - knownAt: '2023-03-10', - ttm: 200 + ((l * 3) % 5) * 25, - })), - ...LISTING_IDS.map((lid, l) => ({ listingId: lid, knownAt: '2023-04-05', ttm: 100 + l * 40 })), - ...[101, 102, 103].map((lid, l) => ({ listingId: lid, knownAt: '2023-04-18', ttm: 400 - l * 90 })), - { listingId: 104, knownAt: '2023-04-18', ttm: 999, estimated: true }, - { listingId: 105, knownAt: '2023-04-20', ttm: null }, -]; - -function pitRowSql(r: PitRow): string { - const est = r.estimated === true ? 'TRUE' : 'FALSE'; - const ttm = r.ttm === null ? 'NULL::DOUBLE' : `${r.ttm}::DOUBLE`; - const ttmMeta = - r.ttm === null ? 'NULL::DATE, NULL::VARCHAR' : `DATE '2023-03-31', 'USD'::VARCHAR`; - const ts = `${r.knownAt} ${String(r.hour ?? 13).padStart(2, '0')}:00:00+00`; - return `(${r.listingId}::INTEGER, TIMESTAMPTZ '${ts}', 'filing_date'::VARCHAR, ${est}::BOOLEAN, - DATE '2023-03-31', 'Q1'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${ts}', - 1.0::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, - ${ttmMeta}, ${ttm}, NULL::DOUBLE, NULL::DOUBLE, ${est}::BOOLEAN)`; -} - -async function writeCurated( - curatedRoot: string, - pitPartitions: Readonly> -): Promise { - const rand = createSeededRng(20261206); - const dates = businessDates('2023-03-01', 58); // 53 pre-cutoff + 5 Vault sessions - const prices = BAR_LISTING_IDS.map(() => 40); - const barValues: string[] = []; - for (const date of dates) { - for (let l = 0; l < BAR_LISTING_IDS.length; l += 1) { - const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; - prices[l] = Math.max(1, prices[l]! * (1 + ret)); - const close = Number(prices[l]!.toFixed(6)); - const ts = `TIMESTAMPTZ '${date} 20:00:00+00'`; - barValues.push( - `(${BAR_LISTING_IDS[l]}::INTEGER, DATE '${date}', ${ts}, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, 50000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, ${ts})` - ); - } - } - - await mkdir(join(curatedRoot, 'bars_1d', 'year=2023'), { recursive: true }); - const writer = await createNodeDuckDbExecutor(); - try { - await writer.run(` - COPY ( - SELECT * FROM (VALUES ${barValues.join(', ')}) - AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) - ) TO '${join(curatedRoot, 'bars_1d', 'year=2023', 'part.parquet')}' (FORMAT PARQUET) - `); - for (const [year, rows] of Object.entries(pitPartitions)) { - const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`); - await mkdir(dir, { recursive: true }); - await writer.run(` - COPY ( - SELECT * FROM (VALUES ${rows.map(pitRowSql).join(', ')}) AS t( - listing_id, effective_known_at, known_at_source, has_estimated_lag, - period_end, fiscal_period, currency, period_known_at, - revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, - ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag - ) - ) TO '${join(dir, 'part.parquet')}' (FORMAT PARQUET) - `); - } - } finally { - await writer.close(); - } -} - -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: number[]; -} - -// Deterministic in-memory trial_ledger port (fixed created_at, sequential ids). -function createLedger(): { executor: TrialLedgerExecutor; rows: LedgerRow[] } { - const rows: LedgerRow[] = []; - let nextId = 1; - const executor: TrialLedgerExecutor = { - async query>(text: string, params?: readonly unknown[]) { - const p = params ?? []; - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - const id = nextId++; - 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 (trimmed.startsWith('SELECT')) { - if (text.includes('WHERE trial_id = $1::bigint')) { - const matched = rows.filter(r => r.trial_id === String(p[0])); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const matched = rows.filter( - r => r.universe_market === p[0] && r.horizon_bucket === p[1] - ); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - } - return { rows: [], rowCount: 0 }; - }, - }; - return { executor, rows }; -} - -async function openStore( - pitPartitions: Readonly> -): Promise<{ - store: MarketDataStore; - calls: FundamentalsAsOfQuery[]; - close: () => Promise; -}> { - const root = await mkdtemp(join(tmpdir(), 'stockbot-qa-as-fnd-')); - tempDirs.push(root); - const curatedRoot = join(root, 'curated'); - const duckTempDir = join(root, 'duckdb-tmp'); - await mkdir(duckTempDir, { recursive: true }); - await writeCurated(curatedRoot, pitPartitions); - const opened = await openDuckDbMarketDataStore({ - curatedRoot, - vaultCutoffTs: VAULT_CUTOFF_TS, - env: { - STOCK_BOT_DUCKDB_MEMORY_LIMIT: '1GB', - STOCK_BOT_DUCKDB_THREADS: '2', - STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, - }, - }); - const calls: FundamentalsAsOfQuery[] = []; - const inner = opened.store; - const store: MarketDataStore = { - ...inner, - bars: q => inner.bars(q), - shortsAsOf: q => inner.shortsAsOf(q), - universe: q => inner.universe(q), - fundamentalsAsOf: q => { - calls.push(q); - return inner.fundamentalsAsOf(q); - }, - }; - return { store, calls, close: () => opened.close() }; -} - -async function runTool( - store: MarketDataStore, - ledger: TrialLedgerExecutor, - allowEstimatedLag?: boolean, - listingIds: readonly number[] = LISTING_IDS -): Promise<{ isError: boolean; text: string }> { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createAnalyzeSignalTool({ - store, - ledger, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - principalId: PRINCIPAL, - }), - ], - }); - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'qa-1', - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: { - listingIds: [...listingIds], - from: '2023-03-01', - to: '2023-05-19', // straddles the Vault cutoff; must be clamped - signal: { - source: 'fundamentals', - field: 'ttm_revenue', - ...(allowEstimatedLag === undefined ? {} : { allowEstimatedLag }), - }, - horizonSessions: HORIZON, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }, - }) - ); - const parsed = JSON.parse(raw as string) as { - result: { isError?: boolean; content: { text: string }[] }; - }; - return { isError: parsed.result.isError === true, text: parsed.result.content[0]?.text ?? '' }; -} - -function expectedObservations( - includeEstimated: boolean, - rows: readonly PitRow[] = BASE_PIT_ROWS -): SignalObservation[] { - const out: SignalObservation[] = []; - for (const r of rows) { - if (r.ttm === null || (r.estimated === true && !includeEstimated)) { - continue; - } - out.push({ listingId: r.listingId, knownAt: ms(r.knownAt, r.hour ?? 13), value: r.ttm }); - } - return out; -} - -async function directBaseline( - store: MarketDataStore, - signals: SignalObservation[], - listingIds: readonly number[] = LISTING_IDS -): Promise<{ rankIc: unknown; series: number[]; sampleStart: string; sampleEnd: string }> { - const bars = await collectBars(store.bars({ - listingIds: [...listingIds], - from: '2023-03-01', - to: '2023-05-12', - timeframe: '1d', - adjustment: 'raw', - })); - const built = buildForwardReturnPanel({ - bars, - signals, - horizonSessions: HORIZON, - vaultCutoffDate: VAULT_CUTOFF_DATE, - }); - const ledger = createLedger(); - const study = await analyzeSignal(ledger.executor, { - principalId: PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'qa_direct_baseline', - params: { field: 'ttm_revenue' }, - universe: [...listingIds], - horizon: `${HORIZON}d`, - }, - panel: built.panel, - vaultCutoffDate: VAULT_CUTOFF_DATE, - }); - if (study.status !== 'ok') { - throw new Error(`baseline study not ok: ${study.status}`); - } - return { - rankIc: study.analysis.rankIc, - series: ledger.rows[0]!.daily_series, - sampleStart: study.trial.sampleStart, - sampleEnd: study.trial.sampleEnd, - }; -} - -interface OkPayload { - status: 'ok'; - signal: unknown; - analysis: { rankIc: unknown }; - trial: { sampleStart: string; sampleEnd: string; expressionHash: string }; -} - -describe('analyze_signal fundamentals over real DuckDB fundamentalsAsOf (QA)', () => { - test('default lag: same-month restatement, estimated-lag omission and null-field rows replay exactly like the verified-only baseline', async () => { - const s = await openStore({ '2023': BASE_PIT_ROWS }); - try { - const ledger = createLedger(); - const res = await runTool(s.store, ledger.executor); - expect(res.isError).toBe(false); - const payload = JSON.parse(res.text) as OkPayload; - expect(payload.status).toBe('ok'); - expect(payload.signal).toEqual({ - source: 'fundamentals', - field: 'ttm_revenue', - allowEstimatedLag: false, - }); - - const baseline = await directBaseline(s.store, expectedObservations(false)); - expect(payload.analysis.rankIc).toEqual(baseline.rankIc); - expect(ledger.rows).toHaveLength(1); - expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); - expect(payload.trial.sampleStart).toBe(baseline.sampleStart); - expect(payload.trial.sampleEnd).toBe(baseline.sampleEnd); - expect(payload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true); - - // Every real-store read is strictly pre-Vault and forwards the lag flag verbatim. - expect(s.calls.length).toBeGreaterThan(0); - for (const call of s.calls) { - expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS); - expect(call.allowEstimatedLag).toBe(false); - expect(call.fields).toEqual(['ttm_revenue']); - } - // Fan-out bound: month-end snapshots (3) + at most one probe per eligible session (53). - expect(s.calls.length).toBeLessThanOrEqual(3 + 53); - } finally { - await s.close(); - } - }); - - test('allowEstimatedLag true includes the estimated update and matches its own baseline', async () => { - const s = await openStore({ '2023': BASE_PIT_ROWS }); - try { - const ledger = createLedger(); - const res = await runTool(s.store, ledger.executor, true); - const payload = JSON.parse(res.text) as OkPayload; - expect(payload.status).toBe('ok'); - const baseline = await directBaseline(s.store, expectedObservations(true)); - expect(payload.analysis.rankIc).toEqual(baseline.rankIc); - expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); - expect(s.calls.every(c => c.allowEstimatedLag === true)).toBe(true); - - const defaultLedger = createLedger(); - const defaultRes = await runTool(s.store, defaultLedger.executor); - const defaultPayload = JSON.parse(defaultRes.text) as OkPayload; - expect(defaultPayload.trial.expressionHash).not.toBe(payload.trial.expressionHash); - expect(defaultLedger.rows[0]!.daily_series).not.toEqual(ledger.rows[0]!.daily_series); - } finally { - await s.close(); - } - }); - - test('appending Vault-window and post-cutoff revisions in another Parquet partition leaves payload and ledger rows byte-identical', async () => { - const clean = await openStore({ '2023': BASE_PIT_ROWS }); - const poisoned = await openStore({ - '2023': BASE_PIT_ROWS, - '2099': [ - // Exactly at the Vault cutoff, inside the Vault, and long after. - ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-15', ttm: 5_000 + lid })), - ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-17', ttm: 7_000 - lid })), - ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2024-01-02', ttm: 9_000 + lid })), - ], - }); - try { - const cleanLedger = createLedger(); - const poisonedLedger = createLedger(); - const cleanRes = await runTool(clean.store, cleanLedger.executor); - const poisonedRes = await runTool(poisoned.store, poisonedLedger.executor); - expect(cleanRes.isError).toBe(false); - expect(poisonedRes.text).toBe(cleanRes.text); - expect(poisonedLedger.rows).toEqual(cleanLedger.rows); - expect(poisoned.calls.map(c => c.asOf)).toEqual(clean.calls.map(c => c.asOf)); - } finally { - await clean.close(); - await poisoned.close(); - } - }); - - test('a release stamped exactly at a bar close and superseded next morning is replayed at that close', async () => { - // 106 files at 2023-04-12 20:00:00Z (== bar close ts) and restates at 2023-04-13 13:00Z. - // A month-end-only read would only see the 04-13 vintage; the 04-12 close must use 50. - const rows: readonly PitRow[] = [ - ...BASE_PIT_ROWS, - { listingId: 106, knownAt: '2023-04-12', hour: 20, ttm: 50 }, - { listingId: 106, knownAt: '2023-04-13', ttm: 900 }, - ]; - const s = await openStore({ '2023': rows }); - try { - const ledger = createLedger(); - const res = await runTool(s.store, ledger.executor); - const payload = JSON.parse(res.text) as OkPayload; - expect(payload.status).toBe('ok'); - const baseline = await directBaseline(s.store, expectedObservations(false, rows)); - expect(payload.analysis.rankIc).toEqual(baseline.rankIc); - expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); - // Probe at the exact close timestamp is issued (store compares effective_known_at <= asOf). - expect(s.calls.some(c => Date.parse(c.asOf) === ms('2023-04-12', 20))).toBe(true); - } finally { - await s.close(); - } - }); - - test('sparse coverage: a listing with bars but no fundamentals stays bounded and does not change the study', async () => { - // Measurement for the reviewer's non-blocking fan-out note. The uncovered listing is - // probed at each eligible session, so calls grow with sessions, not with listings. - const covered = await openStore({ '2023': BASE_PIT_ROWS }); - const sparse = await openStore({ '2023': BASE_PIT_ROWS }); - try { - const coveredLedger = createLedger(); - const sparseLedger = createLedger(); - const coveredRes = await runTool(covered.store, coveredLedger.executor); - const sparseRes = await runTool(sparse.store, sparseLedger.executor, undefined, [ - ...LISTING_IDS, - UNCOVERED_LISTING_ID, - ]); - const coveredPayload = JSON.parse(coveredRes.text) as OkPayload; - const sparsePayload = JSON.parse(sparseRes.text) as OkPayload; - expect(coveredPayload.status).toBe('ok'); - expect(sparsePayload.status).toBe('ok'); - - // No signal for 107 -> same cross-sectional series as the covered-only study. - const baseline = await directBaseline(sparse.store, expectedObservations(false), [ - ...LISTING_IDS, - UNCOVERED_LISTING_ID, - ]); - expect(sparseLedger.rows[0]!.daily_series).toEqual(baseline.series); - - // 53 eligible sessions over 3 UTC months: <= 3 month-end snapshots + 53 probes. - expect(sparse.calls.length).toBeLessThanOrEqual(3 + 53); - expect(sparse.calls.length).toBeGreaterThan(covered.calls.length); - // Each session timestamp is probed at most once. - const asOfs = sparse.calls.map(c => c.asOf); - expect(new Set(asOfs).size).toBe(asOfs.length); - for (const call of sparse.calls) { - expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS); - } - } finally { - await covered.close(); - await sparse.close(); - } - }); -}); diff --git a/libs/data/duckdb/test/duckdb-market-data-store.test.ts b/libs/data/duckdb/test/duckdb-market-data-store.test.ts index dfe3259c..d43bd44c 100644 --- a/libs/data/duckdb/test/duckdb-market-data-store.test.ts +++ b/libs/data/duckdb/test/duckdb-market-data-store.test.ts @@ -247,685 +247,4 @@ describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => { await opened.close(); } }); - - test('fundamentalsAsOf enforces restatement non-overwrite, multi-year Hive glob, Vault microsecond fence, and allowEstimatedLag semantics', async () => { - const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-')); - tempDirs.push(root); - const curatedRoot = join(root, 'curated'); - const duckTempDir = join(root, 'duckdb-tmp'); - - await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2023'), { recursive: true }); - await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2024'), { recursive: true }); - await mkdir(join(curatedRoot, 'fundamentals_pit', 'year=2025'), { recursive: true }); - await mkdir(duckTempDir, { recursive: true }); - - // Vault cutoff = 2025-02-13T00:00:00.000Z - const vaultCutoffTs = computeVaultCutoffTs('2025-08-13'); - const s1KnownMs = Date.UTC(2024, 4, 1, 20, 0, 0, 0); // 2024-05-01T20:00:00Z - const s2KnownMs = Date.UTC(2024, 7, 1, 20, 0, 0, 0); // 2024-08-01T20:00:00Z - const s3KnownMs = Date.UTC(2024, 8, 15, 20, 0, 0, 0); // 2024-09-15T20:00:00Z - - const writer = await createNodeDuckDbExecutor(); - try { - // year=2023 partition: listing 50 (only exists in 2023 partition) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - ( - 50::INTEGER, - TIMESTAMPTZ '2023-11-05 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2023-09-30', - 'Q3'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2023-11-05 20:00:00+00', - 80.0::DOUBLE, - 8.0::DOUBLE, - 12.0::DOUBLE, - 500.0::DOUBLE, - 250.0::DOUBLE, - 10.0::DOUBLE, - DATE '2023-09-30', - 'USD'::VARCHAR, - 310.0::DOUBLE, - 31.0::DOUBLE, - 46.0::DOUBLE, - FALSE::BOOLEAN - ) - ) AS t( - listing_id, effective_known_at, known_at_source, has_estimated_lag, - period_end, fiscal_period, currency, period_known_at, - revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, - ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag - ) - ) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2023', 'part.parquet')}' (FORMAT PARQUET) - `); - - // year=2024 partition: - // - listing 101: S1 (Q1), S2 (Q2), S3 (Q1 restatement known after Q2 -> latest period stays Q2, TTM changes) - // - listing 201: older verified snapshot + newer estimated-lag snapshot (strict mode must omit without fallback) - // - listing 202: verified snapshot with estimated-lag TTM only (strict mode keeps row, nulls ttm_* + ttm_period_end + ttm_currency, preserves ttm_has_estimated_lag) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - ( - 101::INTEGER, - TIMESTAMPTZ '2024-05-01 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-03-31', - 'Q1'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2024-05-01 20:00:00+00', - 100.0::DOUBLE, - 10.0::DOUBLE, - 15.0::DOUBLE, - 1000.0::DOUBLE, - 500.0::DOUBLE, - 50.0::DOUBLE, - DATE '2024-03-31', - 'USD'::VARCHAR, - 380.0::DOUBLE, - 38.0::DOUBLE, - 55.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 101::INTEGER, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-06-30', - 'Q2'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 120.0::DOUBLE, - 14.0::DOUBLE, - 20.0::DOUBLE, - 1050.0::DOUBLE, - 520.0::DOUBLE, - 50.0::DOUBLE, - DATE '2024-06-30', - 'USD'::VARCHAR, - 420.0::DOUBLE, - 44.0::DOUBLE, - 65.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 101::INTEGER, - TIMESTAMPTZ '2024-09-15 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-06-30', - 'Q2'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 120.0::DOUBLE, - 14.0::DOUBLE, - 20.0::DOUBLE, - 1050.0::DOUBLE, - 520.0::DOUBLE, - 50.0::DOUBLE, - DATE '2024-06-30', - 'USD'::VARCHAR, - 415.0::DOUBLE, - 42.0::DOUBLE, - 63.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 201::INTEGER, - TIMESTAMPTZ '2024-05-01 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-03-31', - 'Q1'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2024-05-01 20:00:00+00', - 50.0::DOUBLE, - 5.0::DOUBLE, - 7.0::DOUBLE, - 400.0::DOUBLE, - 200.0::DOUBLE, - 20.0::DOUBLE, - DATE '2024-03-31', - 'USD'::VARCHAR, - 190.0::DOUBLE, - 19.0::DOUBLE, - 27.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 201::INTEGER, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 'estimated_lag'::VARCHAR, - TRUE::BOOLEAN, - DATE '2024-06-30', - 'Q2'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 60.0::DOUBLE, - 6.0::DOUBLE, - 8.0::DOUBLE, - 420.0::DOUBLE, - 210.0::DOUBLE, - 20.0::DOUBLE, - DATE '2024-06-30', - 'USD'::VARCHAR, - 210.0::DOUBLE, - 21.0::DOUBLE, - 30.0::DOUBLE, - TRUE::BOOLEAN - ), - ( - 202::INTEGER, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-06-30', - 'Q2'::VARCHAR, - 'CAD'::VARCHAR, - TIMESTAMPTZ '2024-08-01 20:00:00+00', - 75.0::DOUBLE, - 9.0::DOUBLE, - 11.0::DOUBLE, - 600.0::DOUBLE, - 300.0::DOUBLE, - 30.0::DOUBLE, - DATE '2024-06-30', - 'CAD'::VARCHAR, - 300.0::DOUBLE, - 30.0::DOUBLE, - 45.0::DOUBLE, - TRUE::BOOLEAN - ) - ) AS t( - listing_id, effective_known_at, known_at_source, has_estimated_lag, - period_end, fiscal_period, currency, period_known_at, - revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, - ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag - ) - ) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2024', 'part.parquet')}' (FORMAT PARQUET) - `); - - // year=2025 partition: Vault microsecond boundary rows - // - listing 102: 1 microsecond before cutoff (eligible), exact cutoff (excluded), post-cutoff (excluded) - // - listing 103: exact cutoff only (must return 0 rows) - await writer.run(` - COPY ( - SELECT * FROM (VALUES - ( - 102::INTEGER, - TIMESTAMPTZ '2025-02-12 23:59:59.999999+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-12-31', - 'Q4'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2025-02-12 23:59:59.999999+00', - 210.0::DOUBLE, - 21.0::DOUBLE, - 31.0::DOUBLE, - 1500.0::DOUBLE, - 750.0::DOUBLE, - 60.0::DOUBLE, - DATE '2024-12-31', - 'USD'::VARCHAR, - 800.0::DOUBLE, - 80.0::DOUBLE, - 120.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 102::INTEGER, - TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-12-31', - 'Q4'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', - 999.0::DOUBLE, - 99.0::DOUBLE, - 99.0::DOUBLE, - 9999.0::DOUBLE, - 4999.0::DOUBLE, - 60.0::DOUBLE, - DATE '2024-12-31', - 'USD'::VARCHAR, - 9999.0::DOUBLE, - 999.0::DOUBLE, - 999.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 102::INTEGER, - TIMESTAMPTZ '2025-02-14 12:00:00.000000+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2025-03-31', - 'Q1'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2025-02-14 12:00:00.000000+00', - 1111.0::DOUBLE, - 111.0::DOUBLE, - 111.0::DOUBLE, - 11111.0::DOUBLE, - 5555.0::DOUBLE, - 60.0::DOUBLE, - DATE '2025-03-31', - 'USD'::VARCHAR, - 11111.0::DOUBLE, - 1111.0::DOUBLE, - 1111.0::DOUBLE, - FALSE::BOOLEAN - ), - ( - 103::INTEGER, - TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', - 'filing_date'::VARCHAR, - FALSE::BOOLEAN, - DATE '2024-12-31', - 'Q4'::VARCHAR, - 'USD'::VARCHAR, - TIMESTAMPTZ '2025-02-13 00:00:00.000000+00', - 777.0::DOUBLE, - 77.0::DOUBLE, - 77.0::DOUBLE, - 7777.0::DOUBLE, - 3333.0::DOUBLE, - 40.0::DOUBLE, - DATE '2024-12-31', - 'USD'::VARCHAR, - 7777.0::DOUBLE, - 777.0::DOUBLE, - 777.0::DOUBLE, - FALSE::BOOLEAN - ) - ) AS t( - listing_id, effective_known_at, known_at_source, has_estimated_lag, - period_end, fiscal_period, currency, period_known_at, - revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, - ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag - ) - ) TO '${join(curatedRoot, 'fundamentals_pit', 'year=2025', 'part.parquet')}' (FORMAT PARQUET) - `); - } finally { - await writer.close(); - } - - const opened = await openDuckDbMarketDataStore({ - curatedRoot, - vaultCutoffTs, - env: { - STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', - STOCK_BOT_DUCKDB_THREADS: '2', - STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, - }, - }); - - try { - // 1. Before S1: no row for listing 101 - const beforeS1 = await opened.store.fundamentalsAsOf({ - listingIds: [101], - fields: ['revenue', 'ttm_revenue'], - asOf: '2024-04-30T23:59:59Z', - }); - expect(beforeS1.rows).toEqual([]); - - // 2. Between S1 and S2: Q1 row (revenue 100, ttm_revenue 380) - const betweenS1S2 = await opened.store.fundamentalsAsOf({ - listingIds: [101], - fields: ['revenue', 'ttm_revenue'], - asOf: '2024-06-15', - }); - expect(betweenS1S2.rows).toHaveLength(1); - expect(betweenS1S2.rows[0]).toEqual({ - listing_id: 101, - effective_known_at: s1KnownMs, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-03-31', - fiscal_period: 'Q1', - currency: 'USD', - period_known_at: s1KnownMs, - revenue: 100, - ttm_revenue: 380, - ttm_period_end: '2024-03-31', - ttm_currency: 'USD', - ttm_has_estimated_lag: false, - }); - - // 3. Between S2 and S3: Q2 baseline (revenue 120, period_known_at = S2, pre-restatement TTM 420) - const betweenS2S3 = await opened.store.fundamentalsAsOf({ - listingIds: [101], - fields: ['revenue', 'ttm_revenue'], - asOf: '2024-08-15', - }); - expect(betweenS2S3.rows).toHaveLength(1); - expect(betweenS2S3.rows[0]).toEqual({ - listing_id: 101, - effective_known_at: s2KnownMs, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: s2KnownMs, - revenue: 120, - ttm_revenue: 420, - ttm_period_end: '2024-06-30', - ttm_currency: 'USD', - ttm_has_estimated_lag: false, - }); - - // 4. At and after S3 (Q1 restatement with known_at > Q2): Q2 period_end, revenue, and period_known_at stay fixed while ttm_revenue updates to 415 - for (const asOf of ['2024-09-15T20:00:00Z', '2024-10-01']) { - const afterS3 = await opened.store.fundamentalsAsOf({ - listingIds: [101], - fields: ['revenue', 'ttm_revenue'], - asOf, - }); - expect(afterS3.rows).toHaveLength(1); - expect(afterS3.rows[0]).toEqual({ - listing_id: 101, - effective_known_at: s3KnownMs, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: s2KnownMs, - revenue: 120, - ttm_revenue: 415, - ttm_period_end: '2024-06-30', - ttm_currency: 'USD', - ttm_has_estimated_lag: false, - }); - } - - // 5. Multi-partition glob (year=2023 + year=2024) sorted by listing_id ASC, with non-TTM projection omitting TTM metadata columns - const multiYear = await opened.store.fundamentalsAsOf({ - listingIds: [101, 50], - fields: ['revenue'], - asOf: '2024-10-01', - }); - expect(multiYear.columns).toEqual([ - 'listing_id', - 'effective_known_at', - 'known_at_source', - 'has_estimated_lag', - 'period_end', - 'fiscal_period', - 'currency', - 'period_known_at', - 'revenue', - ]); - expect(multiYear.rows.map(r => r.listing_id)).toEqual([50, 101]); - expect(multiYear.rows[0]!.period_end).toBe('2023-09-30'); - expect(multiYear.rows[0]!.revenue).toBe(80); - expect(multiYear.rows[1]!.revenue).toBe(120); - - // 6. Vault microsecond fence: last pre-cutoff microsecond is eligible; exact cutoff and post-cutoff are excluded - for (const asOf of ['2025-02-13T00:00:00.000Z', '2025-06-01']) { - const fenced = await opened.store.fundamentalsAsOf({ - listingIds: [103, 102], - fields: ['revenue'], - asOf, - }); - expect(fenced.rows).toHaveLength(1); - expect(fenced.rows[0]!.listing_id).toBe(102); - expect(fenced.rows[0]!.revenue).toBe(210); - expect(fenced.rows[0]!.period_end).toBe('2024-12-31'); - } - - // 7. allowEstimatedLag default (true) vs strict (false): - // - listing 201 (has_estimated_lag = true on latest snapshot) returned by default, omitted in strict mode without falling back to older verified Q1 row - // - listing 202 (has_estimated_lag = false, ttm_has_estimated_lag = true) kept in strict mode with all ttm_* values + ttm_period_end + ttm_currency nulled and ttm_has_estimated_lag preserved - const lagAllowed = await opened.store.fundamentalsAsOf({ - listingIds: [202, 201], - fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'], - asOf: '2024-09-01', - }); - expect(lagAllowed.rows.map(r => r.listing_id)).toEqual([201, 202]); - expect(lagAllowed.rows[0]!.revenue).toBe(60); - expect(lagAllowed.rows[0]!.has_estimated_lag).toBe(true); - expect(lagAllowed.rows[1]!.revenue).toBe(75); - expect(lagAllowed.rows[1]!.ttm_revenue).toBe(300); - expect(lagAllowed.rows[1]!.ttm_net_income).toBe(30); - expect(lagAllowed.rows[1]!.ttm_operating_cash_flow).toBe(45); - expect(lagAllowed.rows[1]!.ttm_period_end).toBe('2024-06-30'); - expect(lagAllowed.rows[1]!.ttm_currency).toBe('CAD'); - expect(lagAllowed.rows[1]!.ttm_has_estimated_lag).toBe(true); - - const lagStrict = await opened.store.fundamentalsAsOf({ - listingIds: [202, 201], - fields: ['revenue', 'ttm_revenue', 'ttm_net_income', 'ttm_operating_cash_flow'], - asOf: '2024-09-01', - allowEstimatedLag: false, - }); - expect(lagStrict.rows).toHaveLength(1); - expect(lagStrict.rows[0]).toEqual({ - listing_id: 202, - effective_known_at: s2KnownMs, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'CAD', - period_known_at: s2KnownMs, - revenue: 75, - ttm_revenue: null, - ttm_net_income: null, - ttm_operating_cash_flow: null, - ttm_period_end: null, - ttm_currency: null, - ttm_has_estimated_lag: true, - }); - } finally { - await opened.close(); - } - }); -}); - -interface FundamentalsFixtureRow { - readonly listingId: number; - readonly effectiveKnownAt: string; - readonly hasEstimatedLag?: boolean; - readonly periodEnd: string; - readonly fiscalPeriod: string; - readonly periodKnownAt?: string; - readonly revenue: number | null; - readonly ttmRevenue: number | null; - readonly ttmHasEstimatedLag: boolean | null; -} - -function fundamentalsRowSql(r: FundamentalsFixtureRow): string { - const num = (v: number | null): string => (v === null ? 'NULL::DOUBLE' : `${v}::DOUBLE`); - const bool = (v: boolean | null): string => (v === null ? 'NULL::BOOLEAN' : `${v ? 'TRUE' : 'FALSE'}::BOOLEAN`); - const ttmMissing = r.ttmRevenue === null; - return `( - ${r.listingId}::INTEGER, TIMESTAMPTZ '${r.effectiveKnownAt}', 'filing_date'::VARCHAR, ${bool(r.hasEstimatedLag ?? false)}, - DATE '${r.periodEnd}', '${r.fiscalPeriod}'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${r.periodKnownAt ?? r.effectiveKnownAt}', - ${num(r.revenue)}, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, - ${ttmMissing ? 'NULL::DATE' : `DATE '${r.periodEnd}'`}, ${ttmMissing ? 'NULL::VARCHAR' : `'USD'::VARCHAR`}, - ${num(r.ttmRevenue)}, NULL::DOUBLE, NULL::DOUBLE, ${bool(r.ttmHasEstimatedLag)} - )`; -} - -async function writeFundamentalsPartition( - curatedRoot: string, - year: number, - rows: readonly FundamentalsFixtureRow[] -): Promise { - const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`); - await mkdir(dir, { recursive: true }); - const writer = await createNodeDuckDbExecutor(); - try { - await writer.run(` - COPY ( - SELECT * FROM (VALUES ${rows.map(fundamentalsRowSql).join(', ')}) AS t( - listing_id, effective_known_at, known_at_source, has_estimated_lag, - period_end, fiscal_period, currency, period_known_at, - revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, - ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag - ) - ) TO '${join(dir, 'part.parquet')}' (FORMAT PARQUET) - `); - } finally { - await writer.close(); - } -} - -describe('openDuckDbMarketDataStore fundamentalsAsOf edge cases (@duckdb/node-api)', () => { - async function openFundamentalsStore(): Promise>> { - const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-fnd-edge-')); - tempDirs.push(root); - const curatedRoot = join(root, 'curated'); - const duckTempDir = join(root, 'duckdb-tmp'); - await mkdir(duckTempDir, { recursive: true }); - - // Partition directory does not drive ranking: listing 7's newest snapshot sits in - // year=2023 while its older one sits in year=2024; listing 8 is the reverse. - await writeFundamentalsPartition(curatedRoot, 2023, [ - { listingId: 7, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 70, ttmRevenue: 270, ttmHasEstimatedLag: false }, - { listingId: 8, effectiveKnownAt: '2023-11-01 12:00:00+00', periodEnd: '2023-09-30', fiscalPeriod: 'Q3', revenue: 80, ttmRevenue: 300, ttmHasEstimatedLag: false }, - ]); - await writeFundamentalsPartition(curatedRoot, 2024, [ - { listingId: 7, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 65, ttmRevenue: 260, ttmHasEstimatedLag: false }, - { listingId: 8, effectiveKnownAt: '2024-02-15 12:00:00+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 85, ttmRevenue: 310, ttmHasEstimatedLag: false }, - // Sub-millisecond neighbours: only the microsecond distinguishes them. - { listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000500+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 90, ttmRevenue: 360, ttmHasEstimatedLag: false }, - { listingId: 9, effectiveKnownAt: '2024-03-01 12:00:00.000501+00', periodEnd: '2023-12-31', fiscalPeriod: 'Q4', revenue: 91, ttmRevenue: 361, ttmHasEstimatedLag: false }, - // Verified Q1, then estimated Q2. - { listingId: 10, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 100, ttmRevenue: 400, ttmHasEstimatedLag: false }, - { listingId: 10, effectiveKnownAt: '2024-08-01 12:00:00+00', hasEstimatedLag: true, periodEnd: '2024-06-30', fiscalPeriod: 'Q2', revenue: 110, ttmRevenue: 410, ttmHasEstimatedLag: true }, - // TTM-only estimated lag. - { listingId: 11, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 111, ttmRevenue: 444, ttmHasEstimatedLag: true }, - // No TTM yet (fewer than four quarters): TTM values and flag are NULL. - { listingId: 12, effectiveKnownAt: '2024-05-01 12:00:00+00', periodEnd: '2024-03-31', fiscalPeriod: 'Q1', revenue: 12, ttmRevenue: null, ttmHasEstimatedLag: null }, - ]); - - return openDuckDbMarketDataStore({ - curatedRoot, - vaultCutoffTs: computeVaultCutoffTs('2025-08-13'), - env: { - STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB', - STOCK_BOT_DUCKDB_THREADS: '2', - STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, - }, - }); - } - - test('selects the latest effective_known_at across Hive partitions regardless of partition directory', async () => { - const opened = await openFundamentalsStore(); - try { - const result = await opened.store.fundamentalsAsOf({ - listingIds: [8, 7], - fields: ['revenue'], - asOf: '2024-06-01', - }); - expect(result.rows.map(r => [r.listing_id, r.fiscal_period, r.revenue])).toEqual([ - [7, 'Q1', 70], - [8, 'Q4', 85], - ]); - - const earlier = await opened.store.fundamentalsAsOf({ - listingIds: [7, 8], - fields: ['revenue'], - asOf: '2024-01-01', - }); - expect(earlier.rows.map(r => [r.listing_id, r.fiscal_period])).toEqual([[8, 'Q3']]); - } finally { - await opened.close(); - } - }); - - test('binds explicit sub-millisecond asOf so microsecond-adjacent snapshots are separated', async () => { - const opened = await openFundamentalsStore(); - try { - const at = async (asOf: string): Promise => - (await opened.store.fundamentalsAsOf({ listingIds: [9], fields: ['revenue'], asOf })).rows.map( - r => r.revenue - ); - expect(await at('2024-03-01T12:00:00.000499Z')).toEqual([]); - expect(await at('2024-03-01T12:00:00.000500Z')).toEqual([90]); - expect(await at('2024-03-01T14:00:00.000500+02:00')).toEqual([90]); - expect(await at('2024-03-01T12:00:00.000501Z')).toEqual([91]); - } finally { - await opened.close(); - } - }); - - test('strict allowEstimatedLag returns the verified snapshot that was latest at an earlier asOf, and omits the listing once an estimated snapshot is latest', async () => { - const opened = await openFundamentalsStore(); - try { - const beforeEstimate = await opened.store.fundamentalsAsOf({ - listingIds: [10], - fields: ['revenue'], - asOf: '2024-07-31', - allowEstimatedLag: false, - }); - expect(beforeEstimate.rows.map(r => [r.fiscal_period, r.revenue])).toEqual([['Q1', 100]]); - - const afterEstimate = await opened.store.fundamentalsAsOf({ - listingIds: [10], - fields: ['revenue'], - asOf: '2024-08-02', - allowEstimatedLag: false, - }); - expect(afterEstimate.rows).toEqual([]); - } finally { - await opened.close(); - } - }); - - test('strict mode keeps TTM-estimated rows without TTM columns when no ttm_* field is requested, and passes through NULL TTM flags', async () => { - const opened = await openFundamentalsStore(); - try { - const noTtm = await opened.store.fundamentalsAsOf({ - listingIds: [11], - fields: ['revenue'], - asOf: '2024-06-01', - allowEstimatedLag: false, - }); - expect(noTtm.columns).not.toContain('ttm_has_estimated_lag'); - expect(noTtm.rows).toEqual([ - expect.objectContaining({ listing_id: 11, revenue: 111, has_estimated_lag: false }), - ]); - expect(Object.keys(noTtm.rows[0]!)).toEqual(noTtm.columns as string[]); - - const nullTtm = await opened.store.fundamentalsAsOf({ - listingIds: [12, 11], - fields: ['ttm_revenue'], - asOf: '2024-06-01', - allowEstimatedLag: false, - }); - expect(nullTtm.rows.map(r => [r.listing_id, r.ttm_revenue, r.ttm_period_end, r.ttm_currency, r.ttm_has_estimated_lag])).toEqual([ - [11, null, null, null, true], - [12, null, null, null, null], - ]); - } finally { - await opened.close(); - } - }); - - test('returns only requested listings and is reproducible across repeated identical queries', async () => { - const opened = await openFundamentalsStore(); - try { - const q = { - listingIds: [12, 999, 7], - fields: ['ttm_revenue', 'revenue'], - asOf: '2024-09-01T00:00:00.000001Z', - }; - const first = await opened.store.fundamentalsAsOf(q); - const second = await opened.store.fundamentalsAsOf(q); - expect(first.rows.map(r => r.listing_id)).toEqual([7, 12]); - expect(second).toEqual(first); - } finally { - await opened.close(); - } - }); }); diff --git a/libs/data/postgres/src/migrations.ts b/libs/data/postgres/src/migrations.ts index 1fa68e3c..1f05331a 100644 --- a/libs/data/postgres/src/migrations.ts +++ b/libs/data/postgres/src/migrations.ts @@ -45,7 +45,6 @@ const RESEARCH_FILES = new Set([ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', - '37-research-findings.sql', ]); function locateMigrationsDir(): string { diff --git a/libs/data/questdb/README.md b/libs/data/questdb/README.md index 55476969..469ab8be 100644 --- a/libs/data/questdb/README.md +++ b/libs/data/questdb/README.md @@ -1,115 +1,102 @@ -# QuestDB Client Library - -A QuestDB 10.2.0 client library for the Stock Bot trading platform, optimized for time-series data, parameterized PGWire queries, and intraday bar storage. - -## Features - -- **Time-Series Optimized**: Built for QuestDB 10.2.0 (`LATEST ON`, `SAMPLE BY`, `ASOF JOIN`) -- **Parameterized PGWire Queries**: All value filters bind `$1..$n` placeholders; structured identifiers and intervals are strictly validated -- **Contract DDL**: Offline DDL generator for M2 intraday tables (`bars_1m`, `fx_1m`, `bar_revisions`) with `SYMBOL CAPACITY ... [NO]CACHE`, `PARTITION BY MONTH WAL`, and `DEDUP UPSERT KEYS` -- **Typed `bars_1m` Range Reader**: `readBars1m()` binds `listing_id` as canonical decimal string, returns `INT32` `listing_id` values, and projects `ts` and `known_at` as lossless UTC epoch microseconds (`bigint`) -- **InfluxDB Line Protocol**: Batch ingestion writer -- **Health Monitoring**: Connection health monitoring and metrics - -## Usage - -### Parameterized Queries & `LATEST ON` - -```typescript -import { QuestDBClient, QuestDBQueryBuilder } from '@stock-bot/questdb'; - -const questClient = new QuestDBClient({ - host: 'localhost', - httpPort: 9000, - pgPort: 8812, - influxPort: 9009, - database: 'qdb', -}); -await questClient.connect(); - -// Parameterized PGWire query via query builder -const { sql, params } = QuestDBQueryBuilder.create(questClient) - .select('listing_id', 'ts', 'close', 'volume') - .from('bars_1m') - .where('listing_id = $1', ['1042']) - .latestOn('ts', 'listing_id') - .buildParameterized(); -// sql: -// SELECT listing_id, ts, close, volume FROM bars_1m WHERE listing_id = $1 LATEST ON ts PARTITION BY listing_id -// params: ['1042'] - -// Execute directly (forwards both SQL and bound params) -const latestBars = await questClient.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', { - where: 'session = $1', - params: ['RTH'], -}); - -// Override the designated timestamp column explicitly -const latestRevisions = await questClient.latestBy( - 'bar_revisions', - ['listing_id', 'revised_at', 'new_close'], - 'listing_id', - { timestampColumn: 'revised_at' } -); - -// Time-series aggregations with bound filters -const hourlyStats = await questClient - .aggregate('ohlcv_data') - .selectAgg({ avg_close: 'avg(close)' }) - .whereSymbol('AAPL') - .whereLastHours(24) - .groupBy('symbol') - .sampleBy('1h') - .execute(); -``` - -### Reading `bars_1m` Ranges - -```typescript -import { readBars1m } from '@stock-bot/questdb'; - -// Queries `[from, to)` ordered by `ts ASC`, binding listingId as decimal string SYMBOL -// and converting returned `listing_id` back to signed INT32. -const bars = await readBars1m( - questClient, - 1042, - new Date('2024-01-02T14:30:00.000Z'), - new Date('2024-01-02T21:00:00.000Z') -); -``` - -> **Storage-layer read semantics**: `readBars1m` returns all stored bars in `[from, to)` with `ts` and `known_at` projected via `CAST(... AS LONG)` as UTC epoch microseconds (`bigint`, preserving all 6 fractional digits independent of host timezone) without applying replay cutoffs. Research callers (`MarketDataStore`) remain responsible for as-of availability filtering and Vault fencing. - -### M2 Intraday Contract DDL (Offline) - -```typescript -import { getM2IntradayDDL } from '@stock-bot/questdb'; - -const ddl = getM2IntradayDDL(); -// ddl.bars_1m -> CREATE TABLE IF NOT EXISTS bars_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, listing_id) -// ddl.fx_1m -> CREATE TABLE IF NOT EXISTS fx_1m (...) TIMESTAMP(ts) PARTITION BY MONTH WAL DEDUP UPSERT KEYS(ts, pair) -// ddl.bar_revisions -> CREATE TABLE IF NOT EXISTS bar_revisions (...) TIMESTAMP(revised_at) PARTITION BY MONTH WAL -``` - -M2 intraday tables are opt-in and are not auto-created during `QuestDBClient.connect()`. - -## Configuration - -Configure using environment variables: - -```env -QUESTDB_HOST=localhost -QUESTDB_HTTP_PORT=9000 -QUESTDB_PG_PORT=8812 -QUESTDB_INFLUX_PORT=9009 -``` - -## Time-Series Features - -QuestDB 10.2.0 supports: - -- **High-frequency data**: Millions of data points per second -- **Time-based partitioning**: Monthly WAL partitions for intraday tables -- **ASOF JOINs**: Time-series specific joins -- **SAMPLE BY**: Time-based aggregations -- **LATEST ON**: Get latest values per partition key (`LATEST ON PARTITION BY `) +# QuestDB Client Library + +A comprehensive QuestDB client library for the Stock Bot trading platform, optimized for time-series data, market analytics, and high-performance queries. + +## Features + +- **Time-Series Optimized**: Built specifically for time-series data patterns +- **Dual Protocol Support**: HTTP REST API and PostgreSQL wire protocol +- **InfluxDB Line Protocol**: High-performance data ingestion +- **SQL Analytics**: Full SQL support for complex analytics +- **Schema Management**: Automatic table creation and partitioning +- **Performance Monitoring**: Query performance tracking and optimization +- **Health Monitoring**: Connection health monitoring and metrics + +## Usage + +```typescript +import { QuestDBClient } from '@stock-bot/questdb'; + +// Initialize client +const questClient = new QuestDBClient(); +await questClient.connect(); + +// Insert market data using InfluxDB Line Protocol +await questClient.insert('ohlcv', { + symbol: 'AAPL', + open: 150.00, + high: 152.00, + low: 149.50, + close: 151.50, + volume: 1000000, + timestamp: new Date() +}); + +// Query with SQL +const prices = await questClient.query(` + SELECT symbol, close, timestamp + FROM ohlcv + WHERE symbol = 'AAPL' + AND timestamp > dateadd('d', -1, now()) + ORDER BY timestamp DESC +`); + +// Time-series aggregations +const dailyStats = await questClient.aggregate('ohlcv') + .select(['symbol', 'avg(close) as avg_price']) + .where('symbol = ?', ['AAPL']) + .groupBy('symbol') + .sampleBy('1d', 'timestamp') + .execute(); +``` + +## Data Types + +The client provides typed access to the following time-series data: + +- **ohlcv**: OHLCV candlestick data +- **trades**: Individual trade executions +- **quotes**: Bid/ask quote data +- **indicators**: Technical indicator values +- **performance**: Portfolio performance metrics +- **risk_metrics**: Risk calculation results + +## Configuration + +Configure using environment variables: + +```env +QUESTDB_HOST=localhost +QUESTDB_HTTP_PORT=9000 +QUESTDB_PG_PORT=8812 +QUESTDB_INFLUX_PORT=9009 +``` + +## Time-Series Features + +QuestDB excels at: + +- **High-frequency data**: Millions of data points per second +- **Time-based partitioning**: Automatic partitioning by time +- **ASOF JOINs**: Time-series specific joins +- **SAMPLE BY**: Time-based aggregations +- **LATEST BY**: Get latest values by key + +## Performance + +The client includes performance optimizations: + +- Connection pooling for HTTP and PostgreSQL protocols +- Batch insertions for high throughput +- Compressed data transfer +- Query result caching +- Automatic schema optimization + +## Health Monitoring + +Built-in health monitoring: + +```typescript +const health = await questClient.getHealth(); +console.log(health.status); // 'healthy' | 'degraded' | 'unhealthy' +``` diff --git a/libs/data/questdb/src/client.ts b/libs/data/questdb/src/client.ts index 84e63f43..d4cba976 100644 --- a/libs/data/questdb/src/client.ts +++ b/libs/data/questdb/src/client.ts @@ -3,193 +3,15 @@ import { Pool } from 'pg'; import type { LoggerLike } from '@stock-bot/logger'; import { QuestDBHealthMonitor } from './health'; import { QuestDBInfluxWriter } from './influx-writer'; -import { - assertIdentifier, - assertSampleInterval, - assertSelectColumn, - QuestDBQueryBuilder, - rebaseWhereCondition, -} from './query-builder'; +import { QuestDBQueryBuilder } from './query-builder'; import { QuestDBSchemaManager } from './schema'; import type { - Bar1mRow, - LatestByOptions, QueryResult, QuestDBClientConfig, QuestDBConnectionOptions, - QuestDBQueryable, TableNames, } from './types'; -const INT32_MIN = -2147483648; -const INT32_MAX = 2147483647; -const CANONICAL_INT_RE = /^-?(?:0|[1-9]\d*)$/; -const ISO_UTC_OR_OFFSET_RE = - /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|([+-])(\d{2}):(\d{2}))$/; -const ALLOWED_PARTITIONS = new Set(['NONE', 'HOUR', 'DAY', 'MONTH', 'YEAR']); - -function formatInt32ListingId(listingId: number): string { - if (!Number.isInteger(listingId) || listingId < INT32_MIN || listingId > INT32_MAX) { - throw new RangeError( - `Invalid listingId: expected signed INT32 integer, received ${String(listingId)}` - ); - } - return String(listingId === 0 ? 0 : listingId); -} - -function parseInt32ListingSymbol(raw: unknown): number { - if (typeof raw !== 'string' || !CANONICAL_INT_RE.test(raw)) { - throw new Error(`Malformed bars_1m listing_id SYMBOL value: "${String(raw)}"`); - } - const parsed = Number(raw); - if (!Number.isInteger(parsed) || parsed < INT32_MIN || parsed > INT32_MAX) { - throw new RangeError(`Out-of-range bars_1m listing_id SYMBOL value: "${raw}"`); - } - return parsed; -} - -function toUtcIsoString(value: Date | string, label: string): string { - if (value instanceof Date) { - if (Number.isNaN(value.getTime())) { - throw new Error(`Invalid ${label} timestamp: Date is NaN`); - } - return value.toISOString(); - } - if (typeof value === 'string') { - const trimmed = value.trim(); - const match = ISO_UTC_OR_OFFSET_RE.exec(trimmed); - if (!match) { - throw new Error( - `Invalid ${label} timestamp: expected ISO-8601 string with explicit UTC or offset timezone, received "${value}"` - ); - } - - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - const hour = Number(match[4]); - const minute = Number(match[5]); - const second = Number(match[6]); - const frac = match[7]; - const tz = match[8]; - - const baseUtcMs = Date.UTC(year, month - 1, day, hour, minute, second); - const check = new Date(baseUtcMs); - if ( - check.getUTCFullYear() !== year || - check.getUTCMonth() !== month - 1 || - check.getUTCDate() !== day || - check.getUTCHours() !== hour || - check.getUTCMinutes() !== minute || - check.getUTCSeconds() !== second - ) { - throw new Error(`Invalid ${label} timestamp calendar date/time: "${value}"`); - } - - if (tz === 'Z') { - return trimmed; - } - - const sign = match[9] === '+' ? 1 : -1; - const offsetHours = Number(match[10]); - const offsetMinutes = Number(match[11]); - if (offsetHours > 23 || offsetMinutes > 59) { - throw new Error(`Invalid ${label} timestamp timezone offset: "${value}"`); - } - - const adjustedUtcMs = baseUtcMs - sign * (offsetHours * 60 + offsetMinutes) * 60_000; - const utcDate = new Date(adjustedUtcMs); - const isoSeconds = utcDate.toISOString().slice(0, 19); - return frac ? `${isoSeconds}.${frac}Z` : `${isoSeconds}Z`; - } - throw new Error(`Invalid ${label} timestamp: "${String(value)}"`); -} - -function parseUtcEpochMicros(raw: unknown, field: string): bigint { - if (typeof raw === 'bigint') { - return raw; - } - if (typeof raw === 'string' && CANONICAL_INT_RE.test(raw)) { - return BigInt(raw); - } - if (typeof raw === 'number' && Number.isSafeInteger(raw)) { - return BigInt(raw); - } - throw new Error(`Invalid bars_1m ${field} UTC epoch microseconds: "${String(raw)}"`); -} - -function parseRequiredFiniteNumber(raw: unknown, field: string): number { - const value = - typeof raw === 'number' - ? raw - : typeof raw === 'string' && raw.trim().length > 0 - ? Number(raw) - : Number.NaN; - if (!Number.isFinite(value)) { - throw new Error(`Invalid bars_1m ${field} value: "${String(raw)}"`); - } - return value; -} - -function parseNullableFiniteNumber(raw: unknown, field: string): number | null { - if (raw === null || raw === undefined) { - return null; - } - return parseRequiredFiniteNumber(raw, field); -} - -function parseNullableString(raw: unknown, field: string): string | null { - if (raw === null || raw === undefined) { - return null; - } - if (typeof raw === 'string') { - return raw; - } - throw new Error(`Invalid bars_1m ${field} value: expected string or null`); -} - -/** - * Read 1-minute bars for a single listing over `[from, to)` ordered by `ts ASC` from `bars_1m`. - * - * Binds `listingId` as its canonical decimal string (`SYMBOL`) and converts returned `listing_id` - * values back to signed `INT32` numbers at the boundary (`design/DATA-CONTRACTS.md` §3.B). - * - * Storage-layer read: preserves `known_at` on each row without applying replay cutoffs. - * Research callers (`MarketDataStore`) remain responsible for as-of availability and Vault fencing. - */ -export async function readBars1m( - client: QuestDBQueryable, - listingId: number, - from: Date | string, - to: Date | string -): Promise { - const listingIdParam = formatInt32ListingId(listingId); - const fromIso = toUtcIsoString(from, 'from'); - const toIso = toUtcIsoString(to, 'to'); - - const sql = - 'SELECT listing_id, open, high, low, close, volume, vwap, session, source, CAST(known_at AS LONG) AS known_at_us, CAST(ts AS LONG) AS ts_us ' + - 'FROM bars_1m ' + - 'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' + - 'ORDER BY ts ASC'; - - const result = await client.query>(sql, [listingIdParam, fromIso, toIso]); - - return result.rows.map(row => ({ - listing_id: parseInt32ListingSymbol(row.listing_id), - open: parseRequiredFiniteNumber(row.open, 'open'), - high: parseRequiredFiniteNumber(row.high, 'high'), - low: parseRequiredFiniteNumber(row.low, 'low'), - close: parseRequiredFiniteNumber(row.close, 'close'), - volume: parseRequiredFiniteNumber(row.volume, 'volume'), - vwap: parseNullableFiniteNumber(row.vwap, 'vwap'), - session: parseNullableString(row.session, 'session'), - source: parseNullableString(row.source, 'source'), - known_at: parseUtcEpochMicros(row.known_at_us, 'known_at'), - ts: parseUtcEpochMicros(row.ts_us, 'ts'), - })); -} - /** * QuestDB Client for Stock Bot * @@ -409,125 +231,72 @@ export class QuestDBClient { } /** - * Execute a time-series specific query with SAMPLE BY. - * `where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `params`. + * Execute a time-series specific query with SAMPLE BY */ async sampleBy( - table: TableNames | string, + table: TableNames, columns: string[], interval: string, - timeColumn: string = 'timestamp', + _timeColumn: string = 'timestamp', where?: string, params?: unknown[] ): Promise> { - const validTable = assertIdentifier(table, 'table name'); - if (columns.length === 0) { - throw new Error('SELECT columns cannot be empty'); - } - const validColumns = columns.map(col => assertSelectColumn(col)); - const validInterval = assertSampleInterval(interval); - assertIdentifier(timeColumn, 'timestamp column'); + const columnsStr = columns.join(', '); + const whereClause = where ? `WHERE ${where}` : ''; - let whereClause = ''; - const boundParams = params ? [...params] : []; - if (where !== undefined) { - const validatedWhere = rebaseWhereCondition(where, boundParams, 0); - whereClause = `WHERE ${validatedWhere}`; - } else if (boundParams.length > 0) { - throw new Error('params provided to sampleBy without a where clause'); - } + const sql = ` + SELECT ${columnsStr} + FROM ${table} + ${whereClause} + SAMPLE BY ${interval} + ALIGN TO CALENDAR + `; - const sql = [ - `SELECT ${validColumns.join(', ')}`, - `FROM ${validTable}`, - whereClause, - `SAMPLE BY ${validInterval}`, - 'ALIGN TO CALENDAR', - ] - .filter(Boolean) - .join(' '); - - return await this.query(sql, boundParams.length > 0 ? boundParams : undefined); + return await this.query(sql, params); } /** - * Get latest rows per partition key using QuestDB 10.2.0 `LATEST ON`. - * Defaults to `ts` for `bars_1m`/`fx_1m`, `revised_at` for `bar_revisions`, and `timestamp` otherwise. - * `options.where` is treated as a trusted SQL fragment with `$1..$n` placeholders bound via `options.params`. + * Get latest values by symbol using LATEST BY */ async latestBy( - table: TableNames | string, + table: TableNames, columns: string | string[] = '*', - keyColumns: string | string[] = 'symbol', - options?: LatestByOptions + keyColumns: string | string[] = 'symbol' ): Promise> { - const cols = Array.isArray(columns) ? columns : [columns]; - if (cols.length === 0) { - throw new Error('SELECT columns cannot be empty'); - } - const keys = Array.isArray(keyColumns) ? keyColumns : [keyColumns]; + const columnsStr = Array.isArray(columns) ? columns.join(', ') : columns; + const keyColumnsStr = Array.isArray(keyColumns) ? keyColumns.join(', ') : keyColumns; - const builder = this.queryBuilder().select(...cols).from(table); + const sql = ` + SELECT ${columnsStr} + FROM ${table} + LATEST BY ${keyColumnsStr} + `; - if (options?.where !== undefined) { - builder.where(options.where, options.params); - } else if (options?.params && options.params.length > 0) { - throw new Error('params provided to latestBy without a where clause'); - } - - if (options?.timestampColumn !== undefined) { - builder.latestOn(options.timestampColumn, ...keys); - } else { - builder.latestBy(...keys); - } - - return await builder.execute(); + return await this.query(sql); } /** - * Execute ASOF JOIN for time-series correlation. - * `joinCondition` and `where` are treated as trusted SQL fragments. + * Execute ASOF JOIN for time-series correlation */ async asofJoin( - leftTable: TableNames | string, - rightTable: TableNames | string, + leftTable: TableNames, + rightTable: TableNames, joinCondition: string, columns?: string[], where?: string, params?: unknown[] ): Promise> { - const validLeft = assertIdentifier(leftTable, 'left table name'); - const validRight = assertIdentifier(rightTable, 'right table name'); - if (typeof joinCondition !== 'string' || joinCondition.trim().length === 0) { - throw new Error('ASOF JOIN condition must be a non-empty SQL fragment'); - } - let columnsStr = '*'; - if (columns !== undefined) { - if (columns.length === 0) { - throw new Error('SELECT columns cannot be empty'); - } - columnsStr = columns.map(col => assertSelectColumn(col)).join(', '); - } + const columnsStr = columns ? columns.join(', ') : '*'; + const whereClause = where ? `WHERE ${where}` : ''; - let whereClause = ''; - const boundParams = params ? [...params] : []; - if (where !== undefined) { - const validatedWhere = rebaseWhereCondition(where, boundParams, 0); - whereClause = `WHERE ${validatedWhere}`; - } else if (boundParams.length > 0) { - throw new Error('params provided to asofJoin without a where clause'); - } + const sql = ` + SELECT ${columnsStr} + FROM ${leftTable} + ASOF JOIN ${rightTable} ON ${joinCondition} + ${whereClause} + `; - const sql = [ - `SELECT ${columnsStr}`, - `FROM ${validLeft}`, - `ASOF JOIN ${validRight} ON ${joinCondition}`, - whereClause, - ] - .filter(Boolean) - .join(' '); - - return await this.query(sql, boundParams.length > 0 ? boundParams : undefined); + return await this.query(sql, params); } /** @@ -551,7 +320,9 @@ export class QuestDBClient { * Get table information */ async getTableInfo(tableName: string): Promise { - const result = await this.query('SELECT * FROM table_columns($1)', [tableName]); + const result = await this.query(`SELECT * FROM table_columns WHERE table_name = ?`, [ + tableName, + ]); return result.rows; } @@ -603,9 +374,8 @@ export class QuestDBClient { * Optimize table by rebuilding partitions */ async optimizeTable(tableName: string): Promise { - const validTable = assertIdentifier(tableName, 'table name'); - await this.query(`VACUUM TABLE ${validTable}`); - this.logger.debug(`Optimized table: ${validTable}`); + await this.query(`VACUUM TABLE ${tableName}`); + this.logger.debug(`Optimized table: ${tableName}`); } /** @@ -617,19 +387,14 @@ export class QuestDBClient { partitionBy: string = 'DAY', timestampColumn: string = 'timestamp' ): Promise { - const validTable = assertIdentifier(tableName, 'table name'); - const validTimestamp = assertIdentifier(timestampColumn, 'timestamp column'); - if (!ALLOWED_PARTITIONS.has(partitionBy)) { - throw new Error(`Invalid PARTITION BY value: "${String(partitionBy)}"`); - } const sql = ` - CREATE TABLE IF NOT EXISTS ${validTable} ( + CREATE TABLE IF NOT EXISTS ${tableName} ( ${columns} - ) TIMESTAMP(${validTimestamp}) PARTITION BY ${partitionBy} + ) TIMESTAMP(${timestampColumn}) PARTITION BY ${partitionBy} `; await this.query(sql); - this.logger.info(`Created table: ${validTable}`); + this.logger.info(`Created table: ${tableName}`); } /** diff --git a/libs/data/questdb/src/index.ts b/libs/data/questdb/src/index.ts index 94841d60..46ab3687 100644 --- a/libs/data/questdb/src/index.ts +++ b/libs/data/questdb/src/index.ts @@ -5,39 +5,27 @@ * InfluxDB Line Protocol, SQL queries, and PostgreSQL wire protocol. */ -export { QuestDBClient, readBars1m } from './client'; +export { QuestDBClient } from './client'; export { QuestDBHealthMonitor } from './health'; export { QuestDBQueryBuilder } from './query-builder'; export { QuestDBInfluxWriter } from './influx-writer'; -export { - formatCreateTableSQL, - getM2IntradayDDL, - M2_INTRADAY_SCHEMAS, - QuestDBSchemaManager, - type M2IntradayTableName, -} from './schema'; +export { QuestDBSchemaManager } from './schema'; // Types export type { - Bar1mRow, - ColumnSchema, - InsertResult, - LatestByOptions, - OHLCVData, - ParameterizedQuery, - PerformanceData, - QueryResult, QuestDBClientConfig, QuestDBConnectionOptions, QuestDBHealthStatus, QuestDBMetrics, - QuestDBQueryable, - QuoteData, - RiskMetrics, TableNames, - TableSchema, + OHLCVData, TradeData, + QuoteData, IndicatorData, + PerformanceData, + RiskMetrics, + QueryResult, + InsertResult, } from './types'; // Note: Factory functions removed - instantiate directly with new QuestDBClient() diff --git a/libs/data/questdb/src/query-builder.ts b/libs/data/questdb/src/query-builder.ts index 652c75a3..7ebb56f1 100644 --- a/libs/data/questdb/src/query-builder.ts +++ b/libs/data/questdb/src/query-builder.ts @@ -1,272 +1,32 @@ import type { QueryResultRow } from 'pg'; import { getLogger } from '@stock-bot/logger'; -import type { - ParameterizedQuery, - QueryResult, - QuestDBQueryable, - TableNames, - TimeRange, -} from './types'; +import type { QueryResult, TableNames, TimeRange } from './types'; -const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/; -const SAMPLE_INTERVAL_RE = /^\d+[UTsmhdwMy]$/; - -/** - * Validate a SQL identifier (table, column, alias, or timestamp column). - */ -export function assertIdentifier(value: string, label: string): string { - if (typeof value !== 'string' || !IDENTIFIER_RE.test(value)) { - throw new Error(`Invalid ${label}: "${String(value)}"`); - } - return value; -} - -/** - * Validate a projection column (literal `*` or strict SQL identifier). - */ -export function assertSelectColumn(value: string): string { - if (value === '*') { - return value; - } - return assertIdentifier(value, 'SELECT column'); -} - -/** - * Validate a QuestDB SAMPLE BY interval (e.g. `1m`, `5m`, `1h`, `1d`). - */ -export function assertSampleInterval(value: string): string { - if (typeof value !== 'string' || !SAMPLE_INTERVAL_RE.test(value)) { - throw new Error(`Invalid SAMPLE BY interval: "${String(value)}"`); - } - return value; -} - -/** - * Validate a SQL sort direction. - */ -export function assertSortDirection(value: string): 'ASC' | 'DESC' { - if (value !== 'ASC' && value !== 'DESC') { - throw new Error(`Invalid ORDER BY direction: "${String(value)}"`); - } - return value; -} - -/** - * Resolve the default designated timestamp column for a QuestDB table. - */ -export function defaultTimestampColumnForTable(table: string): string { - switch (table) { - case 'bars_1m': - case 'fx_1m': - return 'ts'; - case 'bar_revisions': - return 'revised_at'; - default: - return 'timestamp'; - } -} - -/** - * Offset fragment-local `$1..$k` placeholders in a trusted SQL WHERE fragment by `offset`. - * Preserves repeated references and ignores `$n` inside single/double quotes and SQL comments. - * Rejects `$0`, out-of-range placeholders, and unused parameters. - */ -export function rebaseWhereCondition( - condition: string, - params: readonly unknown[] = [], - offset: number = 0 -): string { - if (typeof condition !== 'string' || condition.trim().length === 0) { - throw new Error('WHERE condition must be a non-empty SQL string'); - } - - const usedIndices = new Set(); - let out = ''; - let i = 0; - - while (i < condition.length) { - const ch = condition.charAt(i); - const next = condition.charAt(i + 1); - - // Single-quoted string literal ('...' with '' escape) - if (ch === "'") { - out += ch; - i += 1; - let closed = false; - while (i < condition.length) { - const cur = condition.charAt(i); - out += cur; - i += 1; - if (cur === "'") { - if (condition.charAt(i) === "'") { - out += "'"; - i += 1; - } else { - closed = true; - break; - } - } - } - if (!closed) { - throw new Error('Unterminated string literal in WHERE condition'); - } - continue; - } - - // Double-quoted identifier ("..." with "" escape) - if (ch === '"') { - out += ch; - i += 1; - let closed = false; - while (i < condition.length) { - const cur = condition.charAt(i); - out += cur; - i += 1; - if (cur === '"') { - if (condition.charAt(i) === '"') { - out += '"'; - i += 1; - } else { - closed = true; - break; - } - } - } - if (!closed) { - throw new Error('Unterminated quoted identifier in WHERE condition'); - } - continue; - } - - // Line comment (-- ... \n); terminate at EOF so subsequent clauses are never swallowed - if (ch === '-' && next === '-') { - out += '--'; - i += 2; - let sawNewline = false; - while (i < condition.length) { - const cur = condition.charAt(i); - out += cur; - i += 1; - if (cur === '\n') { - sawNewline = true; - break; - } - } - if (!sawNewline) { - out += '\n'; - } - continue; - } - - // Block comment (/* ... */) - if (ch === '/' && next === '*') { - out += '/*'; - i += 2; - let closed = false; - while (i < condition.length) { - if (condition.charAt(i) === '*' && condition.charAt(i + 1) === '/') { - out += '*/'; - i += 2; - closed = true; - break; - } - out += condition.charAt(i); - i += 1; - } - if (!closed) { - throw new Error('Unterminated block comment in WHERE condition'); - } - continue; - } - - // Parameter placeholder ($1, $2, ..., $10, ...) - if (ch === '$' && next >= '0' && next <= '9') { - const prev = i > 0 ? condition.charAt(i - 1) : ''; - const isPartOfIdentifier = /[A-Za-z0-9_]/.test(prev); - if (!isPartOfIdentifier) { - let j = i + 1; - while (j < condition.length) { - const digit = condition.charAt(j); - if (digit < '0' || digit > '9') { - break; - } - j += 1; - } - const digits = condition.slice(i + 1, j); - const index = Number(digits); - if (!Number.isSafeInteger(index) || index < 1) { - throw new Error(`Invalid parameter placeholder $${digits}: placeholders are 1-based`); - } - if (index > params.length) { - throw new Error( - `Parameter placeholder $${index} is out of range for ${params.length} provided parameter(s)` - ); - } - usedIndices.add(index); - out += `$${offset + index}`; - i = j; - continue; - } - } - - out += ch; - i += 1; - } - - for (let idx = 1; idx <= params.length; idx += 1) { - if (!usedIndices.has(idx)) { - throw new Error(`Unused parameter at index ${idx} in WHERE condition`); - } - } - - return out; -} - -interface WherePredicate { - sql: string; - params: unknown[]; -} - -interface LatestOnClause { - timestampColumn?: string; - partitionBy: string[]; -} - -function assertValidDate(value: Date, label: string): Date { - if (!(value instanceof Date) || Number.isNaN(value.getTime())) { - throw new Error(`Invalid ${label}: expected a valid Date`); - } - return value; -} - -function assertPositiveInteger(value: number, label: string): number { - if (!Number.isInteger(value) || value <= 0) { - throw new Error(`Invalid ${label}: expected a positive integer, received ${String(value)}`); - } - return value; +// Interface to avoid circular dependency +interface QuestDBClientInterface { + query(sql: string, params?: unknown[]): Promise>; } /** * QuestDB Query Builder * - * Provides a fluent interface for building parameterized PGWire time-series queries - * with support for QuestDB 10.2.0 SQL clauses (`LATEST ON`, `SAMPLE BY`). + * Provides a fluent interface for building optimized time-series queries + * with support for QuestDB-specific functions and optimizations. */ export class QuestDBQueryBuilder { private readonly logger: ReturnType; private query!: { select: string[]; from: string; - where: WherePredicate[]; + where: string[]; groupBy: string[]; orderBy: string[]; limit?: number; sampleBy?: string; - latestOn?: LatestOnClause; + latestBy?: string[]; timeRange?: TimeRange; }; - - constructor(private readonly client: QuestDBQueryable) { + constructor(private readonly client: QuestDBClientInterface) { this.logger = getLogger('questdb-query-builder'); this.reset(); } @@ -281,263 +41,193 @@ export class QuestDBQueryBuilder { where: [], groupBy: [], orderBy: [], - limit: undefined, sampleBy: undefined, - latestOn: undefined, + latestBy: undefined, timeRange: undefined, }; return this; } - /** * Start a new query */ - public static create(client: QuestDBQueryable): QuestDBQueryBuilder { + public static create(client: QuestDBClientInterface): QuestDBQueryBuilder { return new QuestDBQueryBuilder(client); } /** - * Select columns (`*` or validated SQL identifiers) + * Select columns */ public select(...columns: string[]): QuestDBQueryBuilder { - const validated = columns.map(col => assertSelectColumn(col)); - this.query.select.push(...validated); + this.query.select.push(...columns); return this; } /** - * Select with aggregation functions. - * Aliases are validated as SQL identifiers; aggregation expressions are treated as trusted SQL fragments. + * Select with aggregation functions */ public selectAgg(aggregations: Record): QuestDBQueryBuilder { - const validatedEntries = Object.entries(aggregations).map(([alias, expression]) => { - const validAlias = assertIdentifier(alias, 'aggregation alias'); - if (typeof expression !== 'string' || expression.trim().length === 0) { - throw new Error(`Invalid aggregation expression for alias "${validAlias}"`); - } - return `${expression} as ${validAlias}`; + Object.entries(aggregations).forEach(([alias, expression]) => { + this.query.select.push(`${expression} as ${alias}`); }); - this.query.select.push(...validatedEntries); return this; } /** - * From table (validated SQL identifier) + * From table */ public from(table: TableNames | string): QuestDBQueryBuilder { - this.query.from = assertIdentifier(table, 'table name'); + this.query.from = table; return this; } /** - * Raw WHERE predicate (trusted SQL fragment escape hatch). - * Supports fragment-local `$1..$n` placeholders, which are renumbered automatically during build. + * Where condition */ - public where(condition: string, params?: unknown[]): QuestDBQueryBuilder { - const boundParams = params ? [...params] : []; - // Validate fragment syntax and parameter indices eagerly before mutating builder state. - rebaseWhereCondition(condition, boundParams, 0); - this.query.where.push({ sql: condition, params: boundParams }); + public where(condition: string): QuestDBQueryBuilder { + this.query.where.push(condition); return this; } /** - * Where symbol equals (bound parameter) + * Where symbol equals */ public whereSymbol(symbol: string): QuestDBQueryBuilder { - this.query.where.push({ sql: 'symbol = $1', params: [symbol] }); + this.query.where.push(`symbol = '${symbol}'`); return this; } /** - * Where symbols in list (one bound parameter per element; rejects empty lists) + * Where symbols in list */ public whereSymbolIn(symbols: string[]): QuestDBQueryBuilder { - if (symbols.length === 0) { - throw new Error('whereSymbolIn requires at least one symbol'); - } - const placeholders = symbols.map((_, index) => `$${index + 1}`).join(', '); - this.query.where.push({ - sql: `symbol IN (${placeholders})`, - params: [...symbols], - }); + const symbolList = symbols.map(s => `'${s}'`).join(', '); + this.query.where.push(`symbol IN (${symbolList})`); return this; } /** - * Where exchange equals (bound parameter) + * Where exchange equals */ public whereExchange(exchange: string): QuestDBQueryBuilder { - this.query.where.push({ sql: 'exchange = $1', params: [exchange] }); + this.query.where.push(`exchange = '${exchange}'`); return this; } /** - * Time range filter with inclusive bounds (bound UTC ISO-8601 parameters) + * Time range filter */ public whereTimeRange(startTime: Date, endTime: Date): QuestDBQueryBuilder { - const validStart = assertValidDate(startTime, 'startTime'); - const validEnd = assertValidDate(endTime, 'endTime'); - this.query.timeRange = { startTime: validStart, endTime: validEnd }; - this.query.where.push({ - sql: 'timestamp >= $1 AND timestamp <= $2', - params: [validStart.toISOString(), validEnd.toISOString()], - }); + this.query.timeRange = { startTime, endTime }; + this.query.where.push( + `timestamp >= '${startTime.toISOString()}' AND timestamp <= '${endTime.toISOString()}'` + ); return this; } /** - * Last N hours (bound negative hour offset) + * Last N hours */ public whereLastHours(hours: number): QuestDBQueryBuilder { - const validHours = assertPositiveInteger(hours, 'hours'); - this.query.where.push({ - sql: "timestamp > dateadd('h', $1, now())", - params: [-validHours], - }); + this.query.where.push(`timestamp > dateadd('h', -${hours}, now())`); return this; } /** - * Last N days (bound negative day offset) + * Last N days */ public whereLastDays(days: number): QuestDBQueryBuilder { - const validDays = assertPositiveInteger(days, 'days'); - this.query.where.push({ - sql: "timestamp > dateadd('d', $1, now())", - params: [-validDays], - }); + this.query.where.push(`timestamp > dateadd('d', -${days}, now())`); return this; } /** - * Group by columns (validated SQL identifiers) + * Group by columns */ public groupBy(...columns: string[]): QuestDBQueryBuilder { - const validated = columns.map(col => assertIdentifier(col, 'GROUP BY column')); - this.query.groupBy.push(...validated); + this.query.groupBy.push(...columns); return this; } /** - * Order by column (validated identifier and direction) + * Order by column */ public orderBy(column: string, direction: 'ASC' | 'DESC' = 'ASC'): QuestDBQueryBuilder { - const validColumn = assertIdentifier(column, 'ORDER BY column'); - const validDirection = assertSortDirection(direction); - this.query.orderBy.push(`${validColumn} ${validDirection}`); + this.query.orderBy.push(`${column} ${direction}`); return this; } /** * Order by timestamp descending (most recent first) */ - public orderByTimeDesc(timestampColumn: string = 'timestamp'): QuestDBQueryBuilder { - const validColumn = assertIdentifier(timestampColumn, 'ORDER BY column'); - this.query.orderBy.push(`${validColumn} DESC`); + public orderByTimeDesc(): QuestDBQueryBuilder { + this.query.orderBy.push('timestamp DESC'); return this; } /** - * Limit results (bound non-negative integer parameter) + * Limit results */ public limit(count: number): QuestDBQueryBuilder { - if (!Number.isInteger(count) || count < 0) { - throw new Error(`Invalid LIMIT count: expected a non-negative integer, received ${String(count)}`); - } this.query.limit = count; return this; } /** - * Sample by time interval (QuestDB specific, validated interval) + * Sample by time interval (QuestDB specific) */ public sampleBy(interval: string): QuestDBQueryBuilder { - this.query.sampleBy = assertSampleInterval(interval); + this.query.sampleBy = interval; return this; } /** - * QuestDB 10.2.0 `LATEST ON PARTITION BY ` with explicit timestamp column. + * Latest by columns (QuestDB specific) */ - public latestOn(timestampColumn: string, ...partitionByColumns: string[]): QuestDBQueryBuilder { - const validTs = assertIdentifier(timestampColumn, 'LATEST ON timestamp column'); - if (partitionByColumns.length === 0) { - throw new Error('latestOn requires at least one partition column'); - } - const validKeys = partitionByColumns.map(col => - assertIdentifier(col, 'LATEST ON partition column') - ); - this.query.latestOn = { - timestampColumn: validTs, - partitionBy: validKeys, - }; + public latestBy(...columns: string[]): QuestDBQueryBuilder { + this.query.latestBy = columns; return this; } /** - * Convenience wrapper emitting `LATEST ON PARTITION BY `. - * Uses `ts` for `bars_1m`/`fx_1m`, `revised_at` for `bar_revisions`, and `timestamp` for legacy tables. - */ - public latestBy(...partitionByColumns: string[]): QuestDBQueryBuilder { - if (partitionByColumns.length === 0) { - throw new Error('latestBy requires at least one partition column'); - } - const validKeys = partitionByColumns.map(col => - assertIdentifier(col, 'LATEST ON partition column') - ); - this.query.latestOn = { - timestampColumn: undefined, - partitionBy: validKeys, - }; - return this; - } - - /** - * Build and execute the parameterized query + * Build and execute the query */ public async execute(): Promise> { - let built: ParameterizedQuery | undefined; + const sql = this.build(); + this.logger.debug('Executing query', { sql }); + try { - built = this.buildParameterized(); - this.logger.debug('Executing query', { sql: built.sql, paramCount: built.params.length }); - return await this.client.query(built.sql, built.params); + const result = await this.client.query(sql); + this.reset(); // Reset for next query + return result; } catch (error) { - this.logger.error('Query execution failed', { sql: built?.sql, error }); + this.logger.error('Query execution failed', { sql, error }); + this.reset(); // Reset even on error throw error; - } finally { - this.reset(); } } /** - * Build the parameterized SQL query and ordered parameter list (`$1..$n`). + * Build the SQL query string */ - public buildParameterized(): ParameterizedQuery { + public build(): string { if (!this.query.from) { throw new Error('FROM clause is required'); } - const selectColumns = this.query.select.length > 0 ? this.query.select : ['*']; - const params: unknown[] = []; - - let sql = `SELECT ${selectColumns.join(', ')} FROM ${this.query.from}`; - - // Add WHERE clause with consecutively renumbered $1..$n placeholders - if (this.query.where.length > 0) { - const renderedPredicates = this.query.where.map(predicate => { - const rebased = rebaseWhereCondition(predicate.sql, predicate.params, params.length); - params.push(...predicate.params); - return rebased; - }); - sql += ` WHERE ${renderedPredicates.join(' AND ')}`; + if (this.query.select.length === 0) { + this.query.select.push('*'); } - // Add LATEST ON (QuestDB 10.2.0 - placed after WHERE, before SAMPLE BY / GROUP BY) - if (this.query.latestOn && this.query.latestOn.partitionBy.length > 0) { - const tsColumn = - this.query.latestOn.timestampColumn ?? defaultTimestampColumnForTable(this.query.from); - sql += ` LATEST ON ${tsColumn} PARTITION BY ${this.query.latestOn.partitionBy.join(', ')}`; + let sql = `SELECT ${this.query.select.join(', ')} FROM ${this.query.from}`; + + // Add WHERE clause + if (this.query.where.length > 0) { + sql += ` WHERE ${this.query.where.join(' AND ')}`; + } + + // Add LATEST BY (QuestDB specific - must come before GROUP BY) + if (this.query.latestBy && this.query.latestBy.length > 0) { + sql += ` LATEST BY ${this.query.latestBy.join(', ')}`; } // Add SAMPLE BY (QuestDB specific) @@ -555,36 +245,27 @@ export class QuestDBQueryBuilder { sql += ` ORDER BY ${this.query.orderBy.join(', ')}`; } - // Add LIMIT (bound parameter) - if (this.query.limit !== undefined) { - params.push(this.query.limit); - sql += ` LIMIT $${params.length}`; + // Add LIMIT + if (this.query.limit) { + sql += ` LIMIT ${this.query.limit}`; } - return { sql, params }; + return sql; } /** - * Build the SQL query string (placeholder view of `buildParameterized().sql`) - */ - public build(): string { - return this.buildParameterized().sql; - } - - /** - * Get the built query string without executing + * Get the built query without executing */ public toSQL(): string { return this.build(); } // Predefined query methods for common use cases - /** * Get latest OHLCV data for symbols */ public static latestOHLCV( - client: QuestDBQueryable, + client: QuestDBClientInterface, symbols: string[], exchange?: string ): QuestDBQueryBuilder { @@ -601,12 +282,11 @@ export class QuestDBQueryBuilder { return builder; } - /** * Get OHLCV data with time sampling */ public static ohlcvTimeSeries( - client: QuestDBQueryable, + client: QuestDBClientInterface, symbol: string, interval: string, hours: number = 24 @@ -625,12 +305,11 @@ export class QuestDBQueryBuilder { .sampleBy(interval) .orderByTimeDesc(); } - /** * Get market analytics data */ public static marketAnalytics( - client: QuestDBQueryable, + client: QuestDBClientInterface, symbols: string[], hours: number = 1 ): QuestDBQueryBuilder { @@ -650,12 +329,11 @@ export class QuestDBQueryBuilder { .orderBy('symbol') .orderByTimeDesc(); } - /** * Get performance metrics for a time range */ public static performanceMetrics( - client: QuestDBQueryable, + client: QuestDBClientInterface, startTime: Date, endTime: Date ): QuestDBQueryBuilder { @@ -670,12 +348,11 @@ export class QuestDBQueryBuilder { .whereTimeRange(startTime, endTime) .sampleBy('1m'); } - /** * Get trade execution data */ public static tradeExecutions( - client: QuestDBQueryable, + client: QuestDBClientInterface, symbol?: string, hours: number = 24 ): QuestDBQueryBuilder { diff --git a/libs/data/questdb/src/schema.ts b/libs/data/questdb/src/schema.ts index 6e8458d2..55ca7e81 100644 --- a/libs/data/questdb/src/schema.ts +++ b/libs/data/questdb/src/schema.ts @@ -1,147 +1,11 @@ import type { QueryResultRow } from 'pg'; import { at } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; -import { assertIdentifier } from './query-builder'; -import type { ColumnSchema, QuestDBQueryable, TableSchema } from './types'; +import type { QueryResult, TableSchema } from './types'; -export type M2IntradayTableName = 'bars_1m' | 'fx_1m' | 'bar_revisions'; - -/** - * Contract schemas for M2 QuestDB 10.2.0 intraday tables (`design/DATA-CONTRACTS.md` §3.B). - * Kept opt-in (outside `QuestDBSchemaManager.initializeDatabase()`). - */ -export const M2_INTRADAY_SCHEMAS: Readonly> = { - bars_1m: { - tableName: 'bars_1m', - columns: [ - { name: 'listing_id', type: 'SYMBOL', capacity: 65536, cache: false }, - { name: 'open', type: 'DOUBLE' }, - { name: 'high', type: 'DOUBLE' }, - { name: 'low', type: 'DOUBLE' }, - { name: 'close', type: 'DOUBLE' }, - { name: 'volume', type: 'DOUBLE' }, - { name: 'vwap', type: 'DOUBLE' }, - { name: 'session', type: 'SYMBOL', capacity: 8, cache: true }, - { name: 'source', type: 'SYMBOL', capacity: 8, cache: true }, - { name: 'known_at', type: 'TIMESTAMP' }, - { name: 'ts', type: 'TIMESTAMP', designated: true }, - ], - partitionBy: 'MONTH', - wal: true, - dedupUpsertKeys: ['ts', 'listing_id'], - }, - fx_1m: { - tableName: 'fx_1m', - columns: [ - { name: 'pair', type: 'SYMBOL', capacity: 32, cache: true }, - { name: 'open', type: 'DOUBLE' }, - { name: 'high', type: 'DOUBLE' }, - { name: 'low', type: 'DOUBLE' }, - { name: 'close', type: 'DOUBLE' }, - { name: 'source', type: 'SYMBOL', capacity: 8, cache: true }, - { name: 'ts', type: 'TIMESTAMP', designated: true }, - ], - partitionBy: 'MONTH', - wal: true, - dedupUpsertKeys: ['ts', 'pair'], - }, - bar_revisions: { - tableName: 'bar_revisions', - columns: [ - { name: 'listing_id', type: 'SYMBOL', capacity: 65536, cache: false }, - { name: 'timeframe', type: 'SYMBOL', capacity: 8, cache: true }, - { name: 'bar_ts', type: 'TIMESTAMP' }, - { name: 'prev_close', type: 'DOUBLE' }, - { name: 'new_close', type: 'DOUBLE' }, - { name: 'prev_volume', type: 'DOUBLE' }, - { name: 'new_volume', type: 'DOUBLE' }, - { name: 'revised_at', type: 'TIMESTAMP', designated: true }, - ], - partitionBy: 'MONTH', - wal: true, - }, -}; - -function formatColumnDDL(col: ColumnSchema): string { - const name = assertIdentifier(col.name, 'column name'); - let def = `${name} ${col.type}`; - - if (col.type === 'SYMBOL') { - if (col.capacity !== undefined) { - if (!Number.isInteger(col.capacity) || col.capacity <= 0) { - throw new Error( - `Invalid SYMBOL capacity for column "${name}": expected positive integer, received ${String(col.capacity)}` - ); - } - def += ` CAPACITY ${col.capacity}`; - } - if (col.cache === true) { - def += ' CACHE'; - } else if (col.cache === false) { - def += ' NOCACHE'; - } - } - - return def; -} - -/** - * Pure QuestDB CREATE TABLE DDL formatter shared by legacy schemas and M2 contract tables. - */ -export function formatCreateTableSQL(schema: TableSchema): string { - const tableName = assertIdentifier(schema.tableName, 'table name'); - if (!schema.columns || schema.columns.length === 0) { - throw new Error('At least one column is required'); - } - - const columnNames = new Set(schema.columns.map(col => assertIdentifier(col.name, 'column name'))); - // QuestDB's column grammar has no PostgreSQL-style NOT NULL constraint. - // nullable remains descriptive metadata; the designated timestamp is declared below. - const columns = schema.columns.map(formatColumnDDL).join(', '); - - let sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columns})`; - - const timestampColumns = schema.columns.filter(col => col.designated); - if (timestampColumns.length > 1) { - throw new Error('Only one designated timestamp column is allowed'); - } - const timestampColumn = timestampColumns[0]; - if (timestampColumn) { - sql += ` TIMESTAMP(${assertIdentifier(timestampColumn.name, 'designated timestamp column')})`; - } - - if (schema.partitionBy) { - sql += ` PARTITION BY ${schema.partitionBy}`; - } - - if (schema.wal) { - sql += ' WAL'; - } - - if (schema.dedupUpsertKeys && schema.dedupUpsertKeys.length > 0) { - const keys = schema.dedupUpsertKeys.map(key => { - const validKey = assertIdentifier(key, 'DEDUP UPSERT key'); - if (!columnNames.has(validKey)) { - throw new Error(`DEDUP UPSERT key "${validKey}" does not exist on table "${tableName}"`); - } - return validKey; - }); - sql += ` DEDUP UPSERT KEYS(${keys.join(', ')})`; - } - - return sql; -} - -/** - * Return the QuestDB 10.2.0 DDL statements for `bars_1m`, `fx_1m`, and `bar_revisions`. - * Pure offline helper; requires no database connection. - */ -export function getM2IntradayDDL(): Record { - return { - bars_1m: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.bars_1m), - fx_1m: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.fx_1m), - bar_revisions: formatCreateTableSQL(M2_INTRADAY_SCHEMAS.bar_revisions), - }; +// Interface to avoid circular dependency +interface QuestDBClientInterface { + query(sql: string, params?: unknown[]): Promise>; } /** @@ -153,7 +17,7 @@ export function getM2IntradayDDL(): Record { export class QuestDBSchemaManager { private readonly logger: ReturnType; private readonly schemas: Map = new Map(); - constructor(private readonly client: QuestDBQueryable) { + constructor(private readonly client: QuestDBClientInterface) { this.logger = getLogger('questdb-schema-manager'); this.initializeSchemas(); } @@ -331,14 +195,13 @@ export class QuestDBSchemaManager { * Drop a table */ public async dropTable(tableName: string): Promise { - const validTable = assertIdentifier(tableName, 'table name'); - const sql = `DROP TABLE IF EXISTS ${validTable}`; + const sql = `DROP TABLE IF EXISTS ${tableName}`; try { await this.client.query(sql); - this.logger.warn(`Table ${validTable} dropped`); + this.logger.warn(`Table ${tableName} dropped`); } catch (error) { - this.logger.error(`Failed to drop table ${validTable}`, error); + this.logger.error(`Failed to drop table ${tableName}`, error); throw error; } } @@ -348,12 +211,13 @@ export class QuestDBSchemaManager { */ public async tableExists(tableName: string): Promise { try { - const result = await this.client.query<{ count: number | string }>( - 'SELECT COUNT(*) as count FROM tables() WHERE table_name = $1', - [tableName] - ); + const result = await this.client.query(` + SELECT COUNT(*) as count + FROM information_schema.tables + WHERE table_name = '${tableName}' + `); - return result.rows.length > 0 && Number(at(result.rows, 0).count) > 0; + return result.rows.length > 0 && at(result.rows, 0).count > 0; } catch (error) { this.logger.error(`Error checking if table exists: ${tableName}`, error); return false; @@ -405,19 +269,18 @@ export class QuestDBSchemaManager { * Get table statistics */ public async getTableStats(tableName: string): Promise { - const validTable = assertIdentifier(tableName, 'table name'); try { const result = await this.client.query(` SELECT COUNT(*) as row_count, MIN(timestamp) as min_timestamp, MAX(timestamp) as max_timestamp - FROM ${validTable} + FROM ${tableName} `); return result.rows[0] || {}; } catch (error) { - this.logger.error(`Failed to get table stats for ${validTable}`, error); + this.logger.error(`Failed to get table stats for ${tableName}`, error); throw error; } } @@ -426,12 +289,11 @@ export class QuestDBSchemaManager { * Truncate table (remove all data but keep structure) */ public async truncateTable(tableName: string): Promise { - const validTable = assertIdentifier(tableName, 'table name'); try { - await this.client.query(`TRUNCATE TABLE ${validTable}`); - this.logger.warn(`Table ${validTable} truncated`); + await this.client.query(`TRUNCATE TABLE ${tableName}`); + this.logger.warn(`Table ${tableName} truncated`); } catch (error) { - this.logger.error(`Failed to truncate table ${validTable}`, error); + this.logger.error(`Failed to truncate table ${tableName}`, error); throw error; } } @@ -449,7 +311,27 @@ export class QuestDBSchemaManager { * Build CREATE TABLE SQL statement */ private buildCreateTableSQL(schema: TableSchema): string { - return formatCreateTableSQL(schema); + // QuestDB's column grammar has no PostgreSQL-style NOT NULL constraint. + // nullable remains descriptive metadata; the designated timestamp is declared + // below. See https://questdb.com/docs/query/sql/create-table/. + const columns = schema.columns + .map(col => `${col.name} ${col.type}`) + .join(', '); + + let sql = `CREATE TABLE IF NOT EXISTS ${schema.tableName} (${columns})`; + + // Add designated timestamp + const timestampColumn = schema.columns.find(col => col.designated); + if (timestampColumn) { + sql += ` TIMESTAMP(${timestampColumn.name})`; + } + + // Add partition by + if (schema.partitionBy) { + sql += ` PARTITION BY ${schema.partitionBy}`; + } + + return sql; } /** diff --git a/libs/data/questdb/src/types.ts b/libs/data/questdb/src/types.ts index f52d6192..5aec03c7 100644 --- a/libs/data/questdb/src/types.ts +++ b/libs/data/questdb/src/types.ts @@ -62,54 +62,7 @@ export type TableNames = | 'risk_metrics' | 'market_events' | 'strategy_signals' - | 'portfolio_snapshots' - | 'bars_1m' - | 'fx_1m' - | 'bar_revisions'; - -/** - * Shared minimal query executor interface for QuestDB helpers. - */ -export interface QuestDBQueryable { - query(sql: string, params?: unknown[]): Promise>; -} - -/** - * Parameterized PGWire SQL query and ordered bound parameters ($1..$n). - */ -export interface ParameterizedQuery { - sql: string; - params: unknown[]; -} - -/** - * Options for QuestDBClient.latestBy(). - */ -export interface LatestByOptions { - timestampColumn?: string; - where?: string; - params?: unknown[]; -} - -/** - * Typed 1-minute bar row returned from QuestDB `bars_1m`. - * - `listing_id` is stored as decimal string SYMBOL in QuestDB and converted to INT32 at read boundary. - * - `known_at` and `ts` are lossless UTC epoch microseconds (`bigint`) projected via `CAST(... AS LONG)` - * to preserve all 6 fractional digits and avoid PGWire local-timezone `Date` coercion. - */ -export interface Bar1mRow { - listing_id: number; - open: number; - high: number; - low: number; - close: number; - volume: number; - vwap: number | null; - session: string | null; - source: string | null; - known_at: bigint; - ts: bigint; -} + | 'portfolio_snapshots'; /** * Time-Series Data Types @@ -261,14 +214,12 @@ export interface TableSchema { tableName: string; columns: ColumnSchema[]; partitionBy?: 'NONE' | 'HOUR' | 'DAY' | 'MONTH' | 'YEAR'; - wal?: boolean; - dedupUpsertKeys?: string[]; orderBy?: string[]; indices?: IndexDefinition[]; dedup?: boolean; } -export interface ColumnSchema { +interface ColumnSchema { name: string; type: | 'SYMBOL' @@ -284,7 +235,6 @@ export interface ColumnSchema { nullable?: boolean; designated?: boolean; // For designated timestamp column capacity?: number; // For SYMBOL type - cache?: boolean; // For SYMBOL type: true -> CACHE, false -> NOCACHE indexed?: boolean; } diff --git a/libs/data/questdb/test/questdb-query-layer-edges.test.ts b/libs/data/questdb/test/questdb-query-layer-edges.test.ts deleted file mode 100644 index e8089acd..00000000 --- a/libs/data/questdb/test/questdb-query-layer-edges.test.ts +++ /dev/null @@ -1,305 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import type { QueryResultRow } from 'pg'; -import { - formatCreateTableSQL, - QuestDBClient, - QuestDBQueryBuilder, - QuestDBSchemaManager, - readBars1m, - type QueryResult, - type QuestDBQueryable, -} from '../src'; - -interface RecordedQuery { - sql: string; - params: unknown[] | undefined; -} - -class RecordingClient implements QuestDBQueryable { - public readonly calls: RecordedQuery[] = []; - - public async query( - sql: string, - params?: unknown[] - ): Promise> { - this.calls.push({ sql, params }); - return { rows: [] as T[], rowCount: 0, executionTime: 0 }; - } -} - -function clientRoutedTo(fake: RecordingClient): QuestDBClient { - const client = new QuestDBClient( - { host: 'questdb.test.local', httpPort: 9000, pgPort: 8812, influxPort: 9009, database: 'qdb' }, - { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} } - ); - (client as unknown as { query: QuestDBQueryable['query'] }).query = fake.query.bind(fake); - return client; -} - -describe('QuestDB query layer edge cases (QA)', () => { - describe('predefined builders', () => { - it('latestOHLCV binds symbols and exchange and emits LATEST ON timestamp after WHERE', () => { - const fake = new RecordingClient(); - const hostile = "AAPL' OR '1'='1"; - - const { sql, params } = QuestDBQueryBuilder.latestOHLCV( - fake, - [hostile, 'MSFT'], - 'NASDAQ' - ).buildParameterized(); - - expect(sql).toBe( - 'SELECT symbol, timestamp, open, high, low, close, volume FROM ohlcv_data ' + - 'WHERE symbol IN ($1, $2) AND exchange = $3 ' + - 'LATEST ON timestamp PARTITION BY symbol ORDER BY timestamp DESC' - ); - expect(params).toEqual([hostile, 'MSFT', 'NASDAQ']); - expect(sql).not.toContain(hostile); - }); - - it('ohlcvTimeSeries and tradeExecutions bind values in placeholder order', () => { - const fake = new RecordingClient(); - - const series = QuestDBQueryBuilder.ohlcvTimeSeries(fake, 'AAPL', '5m', 12).buildParameterized(); - expect(series.sql).toBe( - 'SELECT first(open) as first_open, max(high) as max_high, min(low) as min_low, ' + - 'last(close) as last_close, sum(volume) as sum_volume FROM ohlcv_data ' + - "WHERE symbol = $1 AND timestamp > dateadd('h', $2, now()) SAMPLE BY 5m ORDER BY timestamp DESC" - ); - expect(series.params).toEqual(['AAPL', -12]); - - const trades = QuestDBQueryBuilder.tradeExecutions(fake, 'AAPL', 3).buildParameterized(); - expect(trades.sql).toBe( - 'SELECT symbol, timestamp, side, quantity, price, execution_time FROM trade_executions ' + - "WHERE timestamp > dateadd('h', $1, now()) AND symbol = $2 ORDER BY timestamp DESC" - ); - expect(trades.params).toEqual([-3, 'AAPL']); - }); - - it('ohlcvTimeSeries rejects a hostile SAMPLE BY interval at build time', () => { - const fake = new RecordingClient(); - expect(() => QuestDBQueryBuilder.ohlcvTimeSeries(fake, 'AAPL', '1h; DROP TABLE x')).toThrow( - /Invalid SAMPLE BY interval/ - ); - expect(fake.calls).toHaveLength(0); - }); - }); - - describe('builder input validation', () => { - it('binds LIMIT 0 instead of silently dropping it and rejects negative or fractional limits', () => { - const fake = new RecordingClient(); - expect(QuestDBQueryBuilder.create(fake).from('t').limit(0).buildParameterized()).toEqual({ - sql: 'SELECT * FROM t LIMIT $1', - params: [0], - }); - expect(() => QuestDBQueryBuilder.create(fake).limit(-1)).toThrow(/LIMIT/); - expect(() => QuestDBQueryBuilder.create(fake).limit(1.5)).toThrow(/LIMIT/); - }); - - it('rejects non-positive relative windows and invalid dates', () => { - const fake = new RecordingClient(); - expect(() => QuestDBQueryBuilder.create(fake).whereLastHours(0)).toThrow(/hours/); - expect(() => QuestDBQueryBuilder.create(fake).whereLastDays(-2)).toThrow(/days/); - expect(() => - QuestDBQueryBuilder.create(fake).whereTimeRange(new Date('nope'), new Date()) - ).toThrow(/startTime/); - }); - - it('rejects unterminated quotes and block comments in raw where() before mutating state', () => { - const fake = new RecordingClient(); - const builder = QuestDBQueryBuilder.create(fake).from('bars_1m'); - - expect(() => builder.where("session = 'RTH", [])).toThrow(/Unterminated string/); - expect(() => builder.where('"session = $1', ['RTH'])).toThrow(/Unterminated quoted/); - expect(() => builder.where('session = $1 /* open', ['RTH'])).toThrow(/Unterminated block/); - - // Rejected fragments must not leak into the next build. - expect(builder.where('session = $1', ['RTH']).buildParameterized()).toEqual({ - sql: 'SELECT * FROM bars_1m WHERE session = $1', - params: ['RTH'], - }); - }); - - it('keeps doubled quotes inside literals and still rebases the following placeholder', () => { - const fake = new RecordingClient(); - const { sql, params } = QuestDBQueryBuilder.create(fake) - .from('bars_1m') - .whereSymbol('X') - .where("note = 'it''s $1' AND close > $1", [10]) - .buildParameterized(); - - expect(sql).toBe("SELECT * FROM bars_1m WHERE symbol = $1 AND note = 'it''s $1' AND close > $2"); - expect(params).toEqual(['X', 10]); - }); - }); - - describe('QuestDBClient helpers', () => { - it('reject params without a where fragment before sending a query', async () => { - const fake = new RecordingClient(); - const client = clientRoutedTo(fake); - - await expect( - client.sampleBy('bars_1m', ['ts', 'close'], '1h', 'ts', undefined, ['RTH']) - ).rejects.toThrow(/without a where/); - await expect( - client.asofJoin('bars_1m', 'fx_1m', 'bars_1m.ts = fx_1m.ts', undefined, undefined, [1]) - ).rejects.toThrow(/without a where/); - await expect( - client.latestBy('bars_1m', '*', 'listing_id', { params: ['RTH'] }) - ).rejects.toThrow(/without a where/); - await expect(client.sampleBy('bars_1m', ['ts'], '1h', 'ts; --')).rejects.toThrow( - /Invalid timestamp column/ - ); - await expect( - client.createTable('bars_1m', 'ts TIMESTAMP', 'DAY; DROP TABLE x', 'ts') - ).rejects.toThrow(/PARTITION BY/); - await expect(client.optimizeTable('bars_1m; DROP TABLE x')).rejects.toThrow( - /Invalid table name/ - ); - - expect(fake.calls).toHaveLength(0); - }); - - it('asofJoin binds where params and keeps SQL on validated identifiers', async () => { - const fake = new RecordingClient(); - const client = clientRoutedTo(fake); - - await client.asofJoin( - 'bars_1m', - 'fx_1m', - 'bars_1m.ts = fx_1m.ts', - ['close'], - 'listing_id = $1 AND pair = $2', - ['1042', 'USDCAD'] - ); - - expect(fake.calls).toEqual([ - { - sql: - 'SELECT close FROM bars_1m ASOF JOIN fx_1m ON bars_1m.ts = fx_1m.ts ' + - 'WHERE listing_id = $1 AND pair = $2', - params: ['1042', 'USDCAD'], - }, - ]); - }); - }); - - describe('schema DDL', () => { - it('leaves legacy startup DDL unchanged (no CAPACITY, CACHE, WAL or DEDUP)', async () => { - const fake = new RecordingClient(); - await new QuestDBSchemaManager(fake).createAllTables(); - - const ddl = fake.calls.map(call => call.sql); - expect(ddl).toHaveLength(6); - expect(ddl[0]).toBe( - 'CREATE TABLE IF NOT EXISTS ohlcv_data (symbol SYMBOL, exchange SYMBOL, timestamp TIMESTAMP, ' + - 'open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, volume LONG, data_source SYMBOL) ' + - 'TIMESTAMP(timestamp) PARTITION BY DAY' - ); - for (const statement of ddl) { - expect(statement).not.toMatch(/CAPACITY|CACHE|WAL|DEDUP|bars_1m|fx_1m|bar_revisions/); - } - }); - - it('formatCreateTableSQL rejects hostile identifiers, bad capacities and multiple designated timestamps', () => { - expect(() => - formatCreateTableSQL({ - tableName: 'bars_1m; DROP TABLE x', - columns: [{ name: 'ts', type: 'TIMESTAMP', designated: true }], - }) - ).toThrow(/Invalid table name/); - expect(() => - formatCreateTableSQL({ - tableName: 't', - columns: [{ name: 'ts TIMESTAMP); --', type: 'TIMESTAMP' }], - }) - ).toThrow(/Invalid column name/); - expect(() => - formatCreateTableSQL({ - tableName: 't', - columns: [{ name: 's', type: 'SYMBOL', capacity: 0 }], - }) - ).toThrow(/capacity/); - expect(() => - formatCreateTableSQL({ - tableName: 't', - columns: [ - { name: 'a', type: 'TIMESTAMP', designated: true }, - { name: 'b', type: 'TIMESTAMP', designated: true }, - ], - }) - ).toThrow(/Only one designated/); - }); - }); - - describe('readBars1m bound normalisation', () => { - it('converts offset bounds to UTC with fractional digits intact, across a day boundary', async () => { - const fake = new RecordingClient(); - - await readBars1m(fake, -0, '2024-01-01T23:30:00.5-05:00', '2024-01-02T09:30:00.000123+05:30'); - - expect(fake.calls).toHaveLength(1); - expect(fake.calls[0]?.params).toEqual([ - '0', - '2024-01-02T04:30:00.5Z', - '2024-01-02T04:00:00.000123Z', - ]); - }); - - it('binds negative INT32 listing ids and parses negative SYMBOL values back', async () => { - const fake = new RecordingClient(); - (fake as unknown as { query: QuestDBQueryable['query'] }).query = async ( - sql: string, - params?: unknown[] - ) => { - fake.calls.push({ sql, params }); - return { - rows: [ - { - listing_id: '-2147483648', - open: 1, - high: 1, - low: 1, - close: 1, - volume: 1, - vwap: null, - session: null, - source: null, - known_at_us: '1704205800000000', - ts_us: '1704205800000000', - }, - ] as T[], - rowCount: 1, - executionTime: 0, - }; - }; - - const rows = await readBars1m( - fake, - -2147483648, - '2024-01-02T14:30:00Z', - '2024-01-02T14:31:00Z' - ); - - expect(fake.calls[0]?.params?.[0]).toBe('-2147483648'); - expect(rows[0]?.listing_id).toBe(-2147483648); - expect(rows[0]?.vwap).toBeNull(); - }); - - it('rejects impossible calendar dates, out-of-range offsets and NaN dates before querying', async () => { - const fake = new RecordingClient(); - const to = '2024-03-01T00:00:00Z'; - - await expect(readBars1m(fake, 1, '2024-02-30T00:00:00Z', to)).rejects.toThrow(/calendar/); - await expect(readBars1m(fake, 1, '2024-02-01T00:00:00+24:00', to)).rejects.toThrow( - /offset/ - ); - await expect(readBars1m(fake, 1, new Date('nope'), to)).rejects.toThrow(/NaN/); - await expect(readBars1m(fake, 1, '2024-02-01T00:00:00.1234567Z', to)).rejects.toThrow( - /timezone/ - ); - - expect(fake.calls).toHaveLength(0); - }); - }); -}); diff --git a/libs/data/questdb/test/questdb-query-layer.test.ts b/libs/data/questdb/test/questdb-query-layer.test.ts deleted file mode 100644 index ce587670..00000000 --- a/libs/data/questdb/test/questdb-query-layer.test.ts +++ /dev/null @@ -1,658 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; -import type { QueryResultRow } from 'pg'; -import { - formatCreateTableSQL, - getM2IntradayDDL, - QuestDBClient, - QuestDBQueryBuilder, - QuestDBSchemaManager, - readBars1m, - type QueryResult, - type QuestDBQueryable, -} from '../src'; - -interface RecordedQuery { - sql: string; - params: unknown[] | undefined; -} - -class FakeQuestDBClient implements QuestDBQueryable { - public readonly calls: RecordedQuery[] = []; - private nextRows: unknown[] = []; - private nextError: Error | null = null; - - public setRows(rows: unknown[]): void { - this.nextRows = rows; - } - - public failNext(error: Error): void { - this.nextError = error; - } - - public async query( - sql: string, - params?: unknown[] - ): Promise> { - this.calls.push({ sql, params }); - if (this.nextError) { - const err = this.nextError; - this.nextError = null; - throw err; - } - return { - rows: this.nextRows as T[], - rowCount: this.nextRows.length, - executionTime: 1, - }; - } -} - -function createClientWithFakeQuery(fake: FakeQuestDBClient): QuestDBClient { - const client = new QuestDBClient( - { - host: 'questdb.test.local', - httpPort: 9000, - pgPort: 8812, - influxPort: 9009, - database: 'qdb', - }, - { - info: () => {}, - warn: () => {}, - error: () => {}, - debug: () => {}, - } - ); - // Route PGWire query execution to the recording fake without opening a network socket. - (client as unknown as { query: QuestDBQueryable['query'] }).query = fake.query.bind(fake); - return client; -} - -function normalizeSql(sql: string): string { - return sql - .replace(/--[^\n]*/g, '') - .replace(/;/g, '') - .replace(/\s+/g, ' ') - .replace(/\(\s+/g, '(') - .replace(/\s+\)/g, ')') - .replace(/\s+,/g, ',') - .trim(); -} - -describe('QuestDB 10.2.0 query layer', () => { - describe('LATEST ON clause generation', () => { - it('emits LATEST ON after WHERE with explicit timestamp and partition key', async () => { - const fake = new FakeQuestDBClient(); - const builder = QuestDBQueryBuilder.create(fake) - .select('listing_id', 'ts', 'close') - .from('bars_1m') - .where('listing_id = $1', ['1042']) - .latestOn('ts', 'listing_id'); - - const built = builder.buildParameterized(); - expect(built.sql).toBe( - 'SELECT listing_id, ts, close FROM bars_1m WHERE listing_id = $1 LATEST ON ts PARTITION BY listing_id' - ); - expect(built.params).toEqual(['1042']); - expect(builder.build()).toBe(built.sql); - expect(builder.toSQL()).toBe(built.sql); - - await builder.execute(); - expect(fake.calls).toHaveLength(1); - expect(fake.calls[0]).toEqual({ - sql: built.sql, - params: ['1042'], - }); - }); - - it('preserves multi-key PARTITION BY ordering', () => { - const fake = new FakeQuestDBClient(); - const sql = QuestDBQueryBuilder.create(fake) - .select('listing_id', 'session', 'ts', 'close') - .from('bars_1m') - .latestOn('ts', 'listing_id', 'session') - .build(); - - expect(sql).toBe( - 'SELECT listing_id, session, ts, close FROM bars_1m LATEST ON ts PARTITION BY listing_id, session' - ); - }); - - it('resolves table-appropriate default timestamps for latestBy()', () => { - const fake = new FakeQuestDBClient(); - - expect(QuestDBQueryBuilder.create(fake).from('bars_1m').latestBy('listing_id').build()).toBe( - 'SELECT * FROM bars_1m LATEST ON ts PARTITION BY listing_id' - ); - expect(QuestDBQueryBuilder.create(fake).from('fx_1m').latestBy('pair').build()).toBe( - 'SELECT * FROM fx_1m LATEST ON ts PARTITION BY pair' - ); - expect( - QuestDBQueryBuilder.create(fake).from('bar_revisions').latestBy('listing_id').build() - ).toBe('SELECT * FROM bar_revisions LATEST ON revised_at PARTITION BY listing_id'); - expect(QuestDBQueryBuilder.create(fake).from('ohlcv_data').latestBy('symbol').build()).toBe( - 'SELECT * FROM ohlcv_data LATEST ON timestamp PARTITION BY symbol' - ); - }); - - it('routes QuestDBClient.latestBy() through the builder with timestamp override and bound filters', async () => { - const fake = new FakeQuestDBClient(); - const client = createClientWithFakeQuery(fake); - - await client.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', { - where: 'session = $1', - params: ['RTH'], - }); - await client.latestBy('bar_revisions', '*', ['listing_id', 'timeframe']); - await client.latestBy('bars_1m', 'close', 'listing_id', { - timestampColumn: 'known_at', - }); - - expect(fake.calls).toEqual([ - { - sql: 'SELECT listing_id, ts, close FROM bars_1m WHERE session = $1 LATEST ON ts PARTITION BY listing_id', - params: ['RTH'], - }, - { - sql: 'SELECT * FROM bar_revisions LATEST ON revised_at PARTITION BY listing_id, timeframe', - params: [], - }, - { - sql: 'SELECT close FROM bars_1m LATEST ON known_at PARTITION BY listing_id', - params: [], - }, - ]); - }); - }); - - describe('parameterized predicates and placeholder renumbering', () => { - it('binds all filter values and keeps hostile input out of SQL', () => { - const fake = new FakeQuestDBClient(); - const hostile = "x' OR '1'='1"; - const start = new Date('2024-01-02T14:30:00.000Z'); - const end = new Date('2024-01-02T15:30:00.000Z'); - - const { sql, params } = QuestDBQueryBuilder.create(fake) - .select('symbol', 'exchange', 'timestamp', 'close') - .from('ohlcv_data') - .whereSymbol(hostile) - .whereSymbolIn(['AAPL', 'MSFT']) - .whereExchange('NASDAQ') - .whereTimeRange(start, end) - .whereLastHours(6) - .whereLastDays(2) - .limit(25) - .buildParameterized(); - - expect(sql).toBe( - 'SELECT symbol, exchange, timestamp, close FROM ohlcv_data ' + - "WHERE symbol = $1 AND symbol IN ($2, $3) AND exchange = $4 AND timestamp >= $5 AND timestamp <= $6 AND timestamp > dateadd('h', $7, now()) AND timestamp > dateadd('d', $8, now()) " + - 'LIMIT $9' - ); - expect(sql).not.toContain(hostile); - expect(sql).not.toContain('AAPL'); - expect(sql).not.toContain('NASDAQ'); - expect(params).toEqual([ - hostile, - 'AAPL', - 'MSFT', - 'NASDAQ', - '2024-01-02T14:30:00.000Z', - '2024-01-02T15:30:00.000Z', - -6, - -2, - 25, - ]); - }); - - it('renumbers raw where() fragments consecutively across repeated, multi-digit, quoted, and commented placeholders', () => { - const fake = new FakeQuestDBClient(); - const tenParams = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p10']; - const tenPred = - 'c1=$1 AND c2=$2 AND c3=$3 AND c4=$4 AND c5=$5 AND c6=$6 AND c7=$7 AND c8=$8 AND c9=$9 AND c10=$10'; - - const { sql, params } = QuestDBQueryBuilder.create(fake) - .from('ohlcv_data') - .limit(10) - .whereSymbol('SPY') - .where( - "note = '$1' AND \"col_$2\" = $1 AND close >= $1 -- ignore $3\n/* ignore $4 */ AND volume > $2", - [100.5, 5000] - ) - .where(tenPred, tenParams) - .buildParameterized(); - - expect(sql).toBe( - 'SELECT * FROM ohlcv_data WHERE symbol = $1 ' + - 'AND note = \'$1\' AND "col_$2" = $2 AND close >= $2 -- ignore $3\n/* ignore $4 */ AND volume > $3 ' + - 'AND c1=$4 AND c2=$5 AND c3=$6 AND c4=$7 AND c5=$8 AND c6=$9 AND c7=$10 AND c8=$11 AND c9=$12 AND c10=$13 ' + - 'LIMIT $14' - ); - expect(params).toHaveLength(14); - expect(params).toEqual(['SPY', 100.5, 5000, ...tenParams, 10]); - }); - - it('rejects empty IN lists and malformed/mismatched where() placeholders before querying', () => { - const fake = new FakeQuestDBClient(); - - expect(() => QuestDBQueryBuilder.create(fake).whereSymbolIn([])).toThrow( - /at least one symbol/i - ); - expect(() => QuestDBQueryBuilder.create(fake).where('close > $0', [1])).toThrow(/1-based/i); - expect(() => QuestDBQueryBuilder.create(fake).where('close > $2', [1])).toThrow( - /out of range/i - ); - expect(() => QuestDBQueryBuilder.create(fake).where('close > $1', [1, 2])).toThrow( - /Unused parameter/i - ); - expect(() => QuestDBQueryBuilder.create(fake).where('close > 10', [1])).toThrow( - /Unused parameter/i - ); - expect(() => QuestDBQueryBuilder.create(fake).where(' ')).toThrow(/non-empty/i); - - expect(fake.calls).toHaveLength(0); - }); - - it('resets builder cleanly for reuse after execution and after rejection', async () => { - const fake = new FakeQuestDBClient(); - const builder = QuestDBQueryBuilder.create(fake); - - fake.failNext(new Error('simulated wire failure')); - await expect(builder.from('ohlcv_data').whereSymbol('AAPL').execute()).rejects.toThrow( - 'simulated wire failure' - ); - - // Builder must be reset after failed execute() - const nextBuilt = builder.select('close').from('bars_1m').where('listing_id = $1', ['7']).buildParameterized(); - expect(nextBuilt).toEqual({ - sql: 'SELECT close FROM bars_1m WHERE listing_id = $1', - params: ['7'], - }); - - await builder.execute(); - expect(fake.calls).toHaveLength(2); - expect(fake.calls[1]).toEqual(nextBuilt); - // Builder is reset again after successful execute() - expect(() => builder.build()).toThrow('FROM clause is required'); - }); - - it('terminates trailing line comments with a newline before subsequent predicates, LATEST ON, and SAMPLE BY', async () => { - const fake = new FakeQuestDBClient(); - const client = createClientWithFakeQuery(fake); - - const builderResult = QuestDBQueryBuilder.create(fake) - .select('listing_id', 'ts', 'close') - .from('bars_1m') - .where('session = $1 -- regular session', ['RTH']) - .where('close > $1 -- minimum price', [100]) - .latestOn('ts', 'listing_id') - .buildParameterized(); - - expect(builderResult.sql).toBe( - 'SELECT listing_id, ts, close FROM bars_1m ' + - 'WHERE session = $1 -- regular session\n ' + - 'AND close > $2 -- minimum price\n ' + - 'LATEST ON ts PARTITION BY listing_id' - ); - expect(builderResult.params).toEqual(['RTH', 100]); - - await client.latestBy('bars_1m', ['listing_id', 'ts', 'close'], 'listing_id', { - where: 'session = $1 -- regular session', - params: ['RTH'], - }); - await client.sampleBy( - 'bars_1m', - ['ts', 'close'], - '1h', - 'ts', - 'session = $1 -- regular session', - ['RTH'] - ); - - expect(fake.calls).toEqual([ - { - sql: - 'SELECT listing_id, ts, close FROM bars_1m ' + - 'WHERE session = $1 -- regular session\n ' + - 'LATEST ON ts PARTITION BY listing_id', - params: ['RTH'], - }, - { - sql: - 'SELECT ts, close FROM bars_1m ' + - 'WHERE session = $1 -- regular session\n ' + - 'SAMPLE BY 1h ALIGN TO CALENDAR', - params: ['RTH'], - }, - ]); - }); - }); - - describe('identifier and interval validation', () => { - it('rejects hostile table, column, alias, latestOn, sort, and sampleBy inputs before querying', async () => { - const fake = new FakeQuestDBClient(); - const client = createClientWithFakeQuery(fake); - - expect(() => QuestDBQueryBuilder.create(fake).from('bars_1m; DROP TABLE x')).toThrow( - /Invalid table name/i - ); - expect(() => QuestDBQueryBuilder.create(fake).select('close; --')).toThrow( - /Invalid SELECT column/i - ); - expect(() => - QuestDBQueryBuilder.create(fake).selectAgg({ 'bad alias': 'avg(close)' }) - ).toThrow(/Invalid aggregation alias/i); - expect(() => QuestDBQueryBuilder.create(fake).latestOn('ts; --', 'listing_id')).toThrow( - /Invalid LATEST ON timestamp column/i - ); - expect(() => QuestDBQueryBuilder.create(fake).latestOn('ts', 'listing_id; DROP')).toThrow( - /Invalid LATEST ON partition column/i - ); - expect(() => QuestDBQueryBuilder.create(fake).orderBy('ts', 'UP' as 'ASC')).toThrow( - /Invalid ORDER BY direction/i - ); - expect(() => QuestDBQueryBuilder.create(fake).sampleBy('1h; DROP TABLE x')).toThrow( - /Invalid SAMPLE BY interval/i - ); - expect(() => QuestDBQueryBuilder.create(fake).sampleBy('1x')).toThrow( - /Invalid SAMPLE BY interval/i - ); - - await expect( - client.sampleBy('bars_1m', ['ts', 'close'], 'bad_interval') - ).rejects.toThrow(/Invalid SAMPLE BY interval/i); - await expect( - client.latestBy('bars_1m; DROP TABLE x', '*', 'listing_id') - ).rejects.toThrow(/Invalid table name/i); - await expect( - client.asofJoin('bars_1m', 'fx_1m; DROP', 'bars_1m.ts = fx_1m.ts') - ).rejects.toThrow(/Invalid right table name/i); - - expect(fake.calls).toHaveLength(0); - }); - - it('binds table name in QuestDBSchemaManager.tableExists() via tables()', async () => { - const fake = new FakeQuestDBClient(); - fake.setRows([{ count: 1 }]); - const manager = new QuestDBSchemaManager(fake); - - const hostileTable = "bars_1m' OR '1'='1"; - const exists = await manager.tableExists(hostileTable); - - expect(exists).toBe(true); - expect(fake.calls).toHaveLength(1); - expect(fake.calls[0]).toEqual({ - sql: 'SELECT COUNT(*) as count FROM tables() WHERE table_name = $1', - params: [hostileTable], - }); - }); - - it('binds table name in QuestDBClient.getTableInfo() via table_columns($1)', async () => { - const fake = new FakeQuestDBClient(); - const client = createClientWithFakeQuery(fake); - fake.setRows([{ column: 'ts', type: 'TIMESTAMP' }]); - - const rows = await client.getTableInfo('bars_1m'); - - expect(rows).toEqual([{ column: 'ts', type: 'TIMESTAMP' }]); - expect(fake.calls).toEqual([ - { - sql: 'SELECT * FROM table_columns($1)', - params: ['bars_1m'], - }, - ]); - }); - }); - - describe('M2 intraday contract DDL', () => { - it('matches design/DATA-CONTRACTS.md §3.B exactly after whitespace and comment normalization', () => { - const contractPath = resolve(import.meta.dir, '../../../../design/DATA-CONTRACTS.md'); - const contractDoc = readFileSync(contractPath, 'utf8'); - const sectionMatch = contractDoc.match( - /### B\. QuestDB `10\.2\.0`[\s\S]*?```sql\n([\s\S]*?)```/ - ); - expect(sectionMatch).not.toBeNull(); - - const contractStatements = sectionMatch![1]! - .split(';') - .map(normalizeSql) - .filter(Boolean); - expect(contractStatements).toHaveLength(3); - - const generated = getM2IntradayDDL(); - expect(normalizeSql(generated.bars_1m)).toBe(contractStatements[0]!); - expect(normalizeSql(generated.fx_1m)).toBe(contractStatements[1]!); - expect(normalizeSql(generated.bar_revisions)).toBe(contractStatements[2]!); - - expect(generated.bars_1m).toContain('listing_id SYMBOL CAPACITY 65536 NOCACHE'); - expect(generated.bars_1m).toContain('session SYMBOL CAPACITY 8 CACHE'); - expect(generated.bars_1m).toContain('source SYMBOL CAPACITY 8 CACHE'); - expect(generated.bars_1m).toContain('TIMESTAMP(ts) PARTITION BY MONTH WAL'); - expect(generated.bars_1m).toContain('DEDUP UPSERT KEYS(ts, listing_id)'); - - expect(generated.fx_1m).toContain('pair SYMBOL CAPACITY 32 CACHE'); - expect(generated.fx_1m).toContain('TIMESTAMP(ts) PARTITION BY MONTH WAL'); - expect(generated.fx_1m).toContain('DEDUP UPSERT KEYS(ts, pair)'); - - expect(generated.bar_revisions).toContain('listing_id SYMBOL CAPACITY 65536 NOCACHE'); - expect(generated.bar_revisions).toContain('TIMESTAMP(revised_at) PARTITION BY MONTH WAL'); - expect(generated.bar_revisions).not.toContain('DEDUP'); - }); - - it('keeps M2 intraday tables opt-in outside legacy startup initialization', () => { - const fake = new FakeQuestDBClient(); - const manager = new QuestDBSchemaManager(fake); - const startupNames = manager.getSchemaNames(); - - expect(startupNames).not.toContain('bars_1m'); - expect(startupNames).not.toContain('fx_1m'); - expect(startupNames).not.toContain('bar_revisions'); - - // Shared formatter also validates dedup keys exist on the table - expect(() => - formatCreateTableSQL({ - tableName: 'bad_table', - columns: [{ name: 'ts', type: 'TIMESTAMP', designated: true }], - dedupUpsertKeys: ['ts', 'missing_col'], - }) - ).toThrow(/does not exist/i); - }); - }); - - describe('readBars1m storage reader', () => { - it('sends one parameterized [from, to) query with UTC epoch-microsecond projection and converts listing_id to INT32', async () => { - const fake = new FakeQuestDBClient(); - // 2024-01-02T14:30:00.000000Z = 1704205800000000 us - // 2024-01-02T14:31:00.000700Z = 1704205860000700 us (6 fractional digits preserved) - // 2024-01-02T14:31:00.000000Z = 1704205860000000 us - // 2024-01-02T14:32:00.123456Z = 1704205920123456 us - const fixtureRows = [ - { - listing_id: '1042', - open: 185.1, - high: 185.5, - low: 184.9, - close: 185.4, - volume: 12500, - vwap: 185.28, - session: 'RTH', - source: 'eod_unadj', - known_at_us: '1704205860000700', - ts_us: '1704205800000000', - }, - { - listing_id: '1042', - open: 185.4, - high: 185.6, - low: 185.3, - close: 185.55, - volume: 0, - vwap: null, - session: 'RTH', - source: 'ib_live', - known_at_us: 1704205920123456n, - ts_us: 1704205860000000, - }, - ]; - fake.setRows(fixtureRows); - - const from = new Date('2024-01-02T14:30:00.000Z'); - const to = new Date('2024-01-02T14:32:00.000Z'); - - const firstRead = await readBars1m(fake, 1042, from, to); - const secondRead = await readBars1m(fake, 1042, from, to); - - expect(fake.calls).toHaveLength(2); - expect(fake.calls[0]).toEqual({ - sql: - 'SELECT listing_id, open, high, low, close, volume, vwap, session, source, CAST(known_at AS LONG) AS known_at_us, CAST(ts AS LONG) AS ts_us ' + - 'FROM bars_1m ' + - 'WHERE listing_id = $1 AND ts >= $2 AND ts < $3 ' + - 'ORDER BY ts ASC', - params: ['1042', '2024-01-02T14:30:00.000Z', '2024-01-02T14:32:00.000Z'], - }); - - expect(firstRead).toEqual(secondRead); - expect(firstRead).toEqual([ - { - listing_id: 1042, - open: 185.1, - high: 185.5, - low: 184.9, - close: 185.4, - volume: 12500, - vwap: 185.28, - session: 'RTH', - source: 'eod_unadj', - known_at: 1704205860000700n, - ts: 1704205800000000n, - }, - { - listing_id: 1042, - open: 185.4, - high: 185.6, - low: 185.3, - close: 185.55, - volume: 0, - vwap: null, - session: 'RTH', - source: 'ib_live', - known_at: 1704205920123456n, - ts: 1704205860000000n, - }, - ]); - expect(typeof firstRead[0]!.listing_id).toBe('number'); - // Verify sub-millisecond ordering is preserved (14:31:00.000700Z > 14:31:00.000000Z) - expect(firstRead[0]!.known_at > 1704205860000000n).toBe(true); - }); - - it('preserves 6-digit microsecond bounds and produces identical results under non-UTC TZ', async () => { - const fake = new FakeQuestDBClient(); - fake.setRows([ - { - listing_id: '1042', - open: 185.1, - high: 185.5, - low: 184.9, - close: 185.4, - volume: 12500, - vwap: 185.28, - session: 'RTH', - source: 'eod_unadj', - known_at_us: '1704205860000700', - ts_us: '1704205800000000', - }, - ]); - - const previousTz = process.env.TZ; - try { - process.env.TZ = 'UTC'; - const utcRows = await readBars1m( - fake, - 1042, - '2024-01-02T14:30:00.000000Z', - '2024-01-02T14:31:00.000700Z' - ); - - process.env.TZ = 'America/Toronto'; - const torontoRows = await readBars1m( - fake, - 1042, - '2024-01-02T14:30:00.000000Z', - '2024-01-02T14:31:00.000700Z' - ); - - expect(torontoRows).toEqual(utcRows); - expect(torontoRows[0]!.known_at).toBe(1704205860000700n); - expect(torontoRows[0]!.ts).toBe(1704205800000000n); - expect(fake.calls[0]?.params).toEqual([ - '1042', - '2024-01-02T14:30:00.000000Z', - '2024-01-02T14:31:00.000700Z', - ]); - expect(fake.calls[1]?.params).toEqual(fake.calls[0]?.params); - } finally { - if (previousTz === undefined) { - delete process.env.TZ; - } else { - process.env.TZ = previousTz; - } - } - - // Reject timezone-naive string bounds that would depend on host local timezone - await expect( - readBars1m(fake, 1042, '2024-01-02T14:30:00', '2024-01-02T14:35:00Z') - ).rejects.toThrow(/timezone/i); - }); - - it('returns empty array when no bars exist in range', async () => { - const fake = new FakeQuestDBClient(); - fake.setRows([]); - - const rows = await readBars1m( - fake, - 0, - '2024-01-02T14:30:00.000Z', - '2024-01-02T14:35:00.000Z' - ); - - expect(rows).toEqual([]); - expect(fake.calls[0]?.params).toEqual([ - '0', - '2024-01-02T14:30:00.000Z', - '2024-01-02T14:35:00.000Z', - ]); - }); - - it('rejects invalid input listingIds and malformed returned SYMBOL listing_id values', async () => { - const fake = new FakeQuestDBClient(); - const from = new Date('2024-01-02T14:30:00.000Z'); - const to = new Date('2024-01-02T14:35:00.000Z'); - - await expect(readBars1m(fake, 1.5, from, to)).rejects.toThrow(/INT32/i); - await expect(readBars1m(fake, 2147483648, from, to)).rejects.toThrow(/INT32/i); - expect(fake.calls).toHaveLength(0); - - for (const badSymbol of ['abc', '007', '12.5', '2147483648', null]) { - fake.setRows([ - { - listing_id: badSymbol, - open: 1, - high: 2, - low: 1, - close: 2, - volume: 10, - vwap: 1.5, - session: 'RTH', - source: 'eod_unadj', - known_at_us: '1704205800000000', - ts_us: '1704205800000000', - }, - ]); - await expect(readBars1m(fake, 42, from, to)).rejects.toThrow(/listing_id SYMBOL/i); - } - }); - }); -}); diff --git a/libs/data/questdb/test/questdb.test.ts b/libs/data/questdb/test/questdb.test.ts index 80a682f3..09c5377d 100644 --- a/libs/data/questdb/test/questdb.test.ts +++ b/libs/data/questdb/test/questdb.test.ts @@ -252,20 +252,19 @@ describe('QuestDB', () => { const builder = new QuestDBQueryBuilder(mockClient); - const { sql, params } = builder + const query = builder .select('symbol', 'close', 'volume') .from('ohlcv_data') .whereSymbol('AAPL') .orderBy('timestamp', 'DESC') .limit(100) - .buildParameterized(); + .build(); - expect(sql).toContain('SELECT symbol, close, volume'); - expect(sql).toContain('FROM ohlcv_data'); - expect(sql).toContain('symbol = $1'); - expect(sql).toContain('ORDER BY timestamp DESC'); - expect(sql).toContain('LIMIT $2'); - expect(params).toEqual(['AAPL', 100]); + expect(query).toContain('SELECT symbol, close, volume'); + expect(query).toContain('FROM ohlcv_data'); + expect(query).toContain("symbol = 'AAPL'"); + expect(query).toContain('ORDER BY timestamp DESC'); + expect(query).toContain('LIMIT 100'); }); it('should build query with time range', () => { diff --git a/libs/research/README.md b/libs/research/README.md index 93e29a1d..919c2b6d 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -85,10 +85,9 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-st - **`planAdjFactorsMetadataQuery(adjPath)`** / **`parseAdjFactorsSnapshotMetadata(adjPath, kvRows)`** — Plans the `parquet_kv_metadata('')` query for `stock_bot.adj_factors.*` footer keys and strictly parses/validates them (mirroring `tools/curate-etl/src/curate_adj.rs`). - **`planEventsQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `/events/year=*/part.parquet` (`hive_partitioning = true`) filtered by allow-listed `kinds` and optional `listingIds`, preserving the Parquet writer's total sort order `(listing_id, ts, kind, subtype, payload_json, known_at, known_at_source)`. - **`planShortsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `/shorts/part.parquet`, binding UTC `YYYY-MM-DD` `report_date` bounds and microsecond UTC ISO-8601 `known_at <= ?`. -- **`planFundamentalsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` point-in-time query over `/fundamentals_pit/year=*/part.parquet` (`hive_partitioning = true`) selecting at most one latest snapshot (`effective_known_at <= asOf`, clamped strictly below `vaultCutoffTs`) per requested `listing_id` across allow-listed `FUNDAMENTALS_PIT_VALUE_FIELDS`, with `allowEstimatedLag` (default `true`) failing closed on snapshot-level `has_estimated_lag` without fallback and masking `ttm_*` values/date/currency when `ttm_has_estimated_lag` is `true`. - **`planFx1dQuery(q, ctx)`** — Plans a `'vault_fenced'` query (with default `asOf = vaultCutoffTs * 1000 - 1` µs) over `/fx_1d/part.parquet` for `timeframe: '1d'`, mapping `'USD.CAD'` to the stored bound parameter `'USDCAD'`. Rejects `'1m'` with `MarketDataStoreNotImplementedError`. - **`planUniverseQuery(q, ctx)`** — Plans a `'vault_fenced'`, survivorship-free query over `/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) returning `SELECT DISTINCT b.listing_id ... ORDER BY b.listing_id ASC` for supported `UNIVERSE_REFS` (`'US_EQ'`, `'CA_EQ'`, `'US_CA_EQ'`) within `[date - lookbackDays, date]` (default `DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7`, configurable via `ctx.universeLookbackDays`). -- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table` / strictly ascending INT32 `universe` `number[]`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `macroAsOf`) with `MarketDataStoreNotImplementedError` and zero executor calls. +- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table` / strictly ascending INT32 `universe` `number[]`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `fundamentalsAsOf`, `macroAsOf`) with `MarketDataStoreNotImplementedError` and zero executor calls. ### Mandatory Vault, PIT, Microsecond & Boundary Validation Rules @@ -124,37 +123,6 @@ Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across - **Mixed planners (`120,000` queries):** `elapsedMs = 225.79 ms`, `queriesPerSec = 531,470 queries/s` (`758,061` bound params, pinned checksum `8606c98c`) - **`universe` plan + adapter mapping (`200` calls × `15,000` listings):** `elapsedMs = 23.44 ms`, `callsPerSec = 8,534 calls/s`, `rowsPerSec = 128,011,137 rows/s` (`3,000,000` mapped IDs, pinned checksum `ef5f1136`) -## Routed `MarketDataStore` (DuckDB Daily + QuestDB `1m` Intraday) - -Exported from `@stock-bot/research` and `@stock-bot/research/market-data-store-routed` (`libs/research/src/market-data-store-routed.ts`). The QuestDB intraday reader is also exported from `@stock-bot/research/market-data-store-questdb`. Both modules are pure, dependency-free, and browser-safe. - -- **`createRoutedMarketDataStore({ daily, intraday })`** — Composes a full daily `MarketDataStore` (e.g. `createDuckDbMarketDataStore`) with an intraday `bars` reader (`Pick`, e.g. `createQuestDbIntradayBarsReader`). - - `bars(q)` with `timeframe: '1m'` delegates directly to `intraday.bars(q)` (preserving lazy iteration, receiver, query identity, and error propagation). Note that `createQuestDbIntradayBarsReader` supports split-unadjusted raw (`adjustment: 'raw'`) `1m` bars. - - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed inputs) and all other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly to `daily`. - - **Shared Vault fence requirement:** The router adds no Vault logic of its own; each delegate enforces its own fence. Always construct `daily` and `intraday` with the exact same `vaultCutoffTs` and `vaultOperatorAuthorized`, and pass that same `vaultCutoffTs` to `createQueryDataTool` (which is always Vault-fenced and accepts only `{ vaultCutoffTs }`): - -```ts -const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); -const vaultOperatorAuthorized = false; - -const daily = createDuckDbMarketDataStore({ - executor: duckDbExecutor, - curatedRoot: '/mnt/data/stockbot/curated', - vaultCutoffTs, - vaultOperatorAuthorized, -}); -const intraday = createQuestDbIntradayBarsReader({ - executor: questDbExecutor, - vaultCutoffTs, - vaultOperatorAuthorized, -}); -const store = createRoutedMarketDataStore({ daily, intraday }); -const queryDataTool = createQueryDataTool({ - store, - vaultContext: { vaultCutoffTs }, -}); -``` - ## Signal Panel Builder Exported from both `@stock-bot/research` and `@stock-bot/research/signal-panel` (`libs/research/src/signal-panel.ts`). The module is pure, synchronous (except `collectBars`), dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers). @@ -228,59 +196,3 @@ Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3 - **Command:** `bun run libs/research/scripts/benchmark-event-panel.ts` - **Observed (Bun 1.2.16):** `elapsedMs = 731.06 ms`, `barsPerSec = 20,682,279 bars/s`, `eventsPerSec = 328,290 events/s` (`5,020` pre-Vault sessions, `240,000` anchored events, `20` Vault-excluded dates, pinned checksum `01b356d3`) - -## MCP Copilot Core - -Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported via the `@stock-bot/research/mcp` subpath (`libs/research/src/mcp/index.ts`). It is intentionally **not** re-exported from the browser-safe `@stock-bot/research` default entrypoint. - -### Registering Tools & Running Stdio Framing - -- **`defineMcpTool({ name, description, inputSchema, jsonSchema?, handler })`** — Registers a strict Zod-validated tool, converts `inputSchema` into a strict JSON Schema (`additionalProperties: false`, or uses an explicit `jsonSchema` override), returns `isError: true` on invalid arguments without calling the handler, and sanitizes thrown handler errors so stack traces never leak. -- **`createMcpServer({ name, version, tools })`** — Transport-agnostic JSON-RPC 2.0 dispatcher implementing `initialize`, `notifications/initialized`, `ping`, `tools/list`, and `tools/call` via `handleMessage(raw: string): Promise`. Rejects duplicate tool names at creation time. -- **`runStdioServer(server, { input?, output?, maxLineBytes? })`** — Newline-delimited JSON-RPC stdio transport over injectable streams (defaulting to `process.stdin` / `process.stdout`), with streaming UTF-8 decoding across arbitrary chunk boundaries, strict sequential dispatch in arrival order, `maxLineBytes` frame-size protection (default `4 MiB`), and zero non-protocol bytes on `output`. - -### `query_data` Tool (Vault-Fenced) - -- **`createQueryDataTool({ store, vaultContext })`** — Wraps an injected `MarketDataStore` for explicit `listingIds` (max `QUERY_DATA_MAX_LISTING_IDS = 500`) or a survivorship-free `universe` ref, with bounded output rows (`QUERY_DATA_DEFAULT_LIMIT = 500`, hard max `QUERY_DATA_MAX_LIMIT = 5_000`). -- Always enforces `scope: 'vault_fenced'` via `applyVaultFence` before any store call, omits `scope` / `vault_evaluation_only` from the strict schema (rejecting unknown keys with zero store calls), drops any post-cutoff row (`ts >= vaultCutoffTs` or `knownAt >= vaultCutoffTs`) as defense in depth, and maps `VaultHoldoutFenceError`, `VaultScopeNotAuthorizedError`, `MarketDataStoreValidationError`, `MarketDataStoreNotImplementedError`, and `AdjFactorsSnapshotError` to `isError: true` responses naming the error class. - -### `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`. - -### `file_finding` Tool (Append-Only) - -- **`createFileFindingTool({ port, trialLookup, newId, now })`** — Files an append-only empirical `finding` or `dead_end` record linked to 1–32 research-visible `trial_ledger` references (`trialRefs`, capped at 256 chars each) and 0–32 optional opaque snapshot identifiers (`evidenceRefs`, never dereferenced by the tool). Trims and enforces hard limits (`title` ≤ 256, `summary` ≤ 4,096, `idempotencyKey` ≤ 128), applies array bounds before case-sensitive deduplication and sorting, and rejects unknown fields with a fixed message. -- **Review status & Vault safety:** Server-controlled metadata (`id`, UTC ISO `createdAt`, and initial `status: 'pending_review'`) cannot be supplied by callers; director approval occurs out-of-band. Every unique `trialRef` is verified via the injected read-only `trialLookup.hasResearchVisibleTrial(ref)` before generating metadata or writing (treating unknown and Vault-only refs identically). Callers must describe research-visible evidence only in `title` and `summary` and keep Vault holdout observations out of filing text. -- **Idempotency & receipts:** `FindingWritePort` exposes only `appendFinding(record, idempotencyKey?)` with atomic `created` / `replayed` / `conflict` semantics comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs`. Retries with the same key and normalized payload return the original `{ id, createdAt, created: false }` without appending; key reuse with a different payload returns a fixed `isError: true` conflict error with zero writes; unkeyed calls are independent. Filed records extend `FindingRecord` and can be read back by receipt ID via `read_knowledge`. - -### Copilot Server - -- **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions. - -### Remaining M2 MCP Items (Later Tasks) - -- SSE/HTTP transport wrapper in `apps/stock/web-api`. -- Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters. - -## Versioned Feature Library - -Exported from both `@stock-bot/research` and `@stock-bot/research/feature-library` (`libs/research/src/feature-library.ts`). The module is pure, dependency-free, and browser-safe (zero `node:*` imports, zero DuckDB driver dependency); SQL execution is injected via `DuckDbExecutor` (`{ run(sql), query(sql, params) }`). - -### API & Immutability - -- **`validateFeatureDefinition(def)`** — Fail-closed validator for declarative `duckdb_sql` feature definitions using a single quote-aware tokenizer shared with hashing and placeholder expansion. Accepts a single `SELECT` or non-recursive `WITH ... SELECT` statement projecting exactly `(listing_id, ts, known_at, value)` in contract order. Rejects `WITH RECURSIVE`, semicolons, comments, caller bind markers (`?`, `$1`, `:name`), prohibited DDL/DML/admin keywords (`COPY`, `ATTACH`, `INSERT`, `CREATE`, `PRAGMA`, `SET`, etc.), external readers (`read_parquet`, `read_csv`, `glob`, etc.), quoted file paths/URIs, catalog relations, table functions, and non-allow-listed functions. Relation sources are restricted to declared `{{input:}}` placeholders (`bars_1d`, `adj_factors`, `events`, `shorts`, `fx_1d`, `fundamentals_pit`), in-scope non-recursive CTEs, and validated subqueries; every declared input must be used and every placeholder must be declared. -- **`featureRef(def)` / `parseFeatureRef(ref)`** — Formats and parses canonical `@v` refs (`^[a-z][a-z0-9_]{0,62}$` and positive safe integer version; rejects non-canonical forms such as `ret_1d@v01`). -- **`featureDefinitionHash(def)`** — Deterministic 64-char SHA-256 hex digest over `{ name, version, kind, sql (canonical tokens), inputs (sorted), warmupBars, knownAtRule }`. Invariant across inter-token whitespace, object key order, and input array order; preserves whitespace inside string literals. `family` and `description` are stored as metadata from the first registration. -- **`createFeatureRegistry()`** — In-memory registry exposing `registerSignal(def)` (D11), `get(ref)`, and `list()`. Re-registering an identical hash is idempotent; re-registering `@v` with a different hash throws `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. Defensive copies isolate stored definitions from caller mutation. -- **`planFeatureBatch(def, { curatedRoot, fromYear, toYear, vaultCutoffDate })`** — Validates `curatedRoot`, four-digit ordered years, and strict UTC `YYYY-MM-DD` `vaultCutoffDate` via `applyVaultFence`. Plans one yearly ZSTD Parquet write to `/features//v/year=YYYY/part.parquet` through the last year with any pre-cutoff time (a January 1 cutoff excludes that calendar year; an entirely post-cutoff range throws `VAULT_RANGE_VIOLATION`). Expands `{{input:}}` scans with bound upper availability predicates (`ts <= ? AND known_at <= ?`, `known_at <= ?`, or `effective_known_at <= ?` for `fundamentals_pit`) strictly `< vaultCutoffDate` (last included microsecond `.999999Z`) before authored SQL runs, preserving earlier history for SQL-owned warm-up. -- **`runFeatureBatch(def, opts, executor)`** — Validates and plans upfront (0 executor calls on invalid inputs), awaits `executor.query(sql, params)` sequentially in year order, and returns `{ ref, definitionHash, knownAtRule, warmupBars, inputs, writes }`. On write failure, stops immediately and throws `FeatureLibraryError('BATCH_WRITE_FAILED')` exposing `cause`, `failedYear`, `completedYears`, and `completedWrites` (earlier completed files may remain on disk for operator inspection before retry). -- **`RET_1D_V1`** — Built-in `ret_1d@v1` example computing 1-day listing-partitioned raw-close return `(close / LAG(close)) - 1.0` with `known_at = ts` and `warmupBars: 1` (omitting rows without a positive prior close). - -### Operational & Research Governance Notes - -- **Executor & directory requirements:** Callers running plans against DuckDB must configure the executor session timezone to UTC (`TZ=UTC`) and ensure output parent directories (`/features//v/year=YYYY/`) exist before executing `COPY`. -- **Point-in-time & `adj_factors` snapshots:** Feature definitions own per-observation availability (`knownAtRule` and projected `known_at`). Because `adj_factors` stores cumulative suffix products, features referencing `{{input:adj_factors}}` require a caller-verified, immutable point-in-time snapshot compatible with `vaultCutoffDate`. -- **Economic ownership & evidence:** The Quant research role owns each feature's economic specification. `RET_1D_V1` uses a zero-return comparison baseline with no execution or transaction cost model. Any future research claim built on materialized features must retain the feature `ref` and `definitionHash`, immutable dataset identifier, sample window, `vaultCutoffDate`, baseline, and execution assumptions. diff --git a/libs/research/package.json b/libs/research/package.json index eb1522e3..89c29140 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -11,12 +11,8 @@ "./dataset-contracts": "./src/dataset-contracts.ts", "./datasets": "./src/datasets.ts", "./event-panel": "./src/event-panel.ts", - "./feature-library": "./src/feature-library.ts", "./market-data-store": "./src/market-data-store.ts", "./market-data-store-duckdb": "./src/market-data-store-duckdb.ts", - "./market-data-store-questdb": "./src/market-data-store-questdb.ts", - "./market-data-store-routed": "./src/market-data-store-routed.ts", - "./mcp": "./src/mcp/index.ts", "./results": "./src/results.ts", "./signal-panel": "./src/signal-panel.ts", "./signal-study": "./src/signal-study.ts", diff --git a/libs/research/src/feature-library.ts b/libs/research/src/feature-library.ts deleted file mode 100644 index 680a3bf1..00000000 --- a/libs/research/src/feature-library.ts +++ /dev/null @@ -1,2193 +0,0 @@ -/** - * Versioned Feature Library core: declarative DuckDB SQL feature definitions, - * immutable `registerSignal` registry, and Vault-fenced yearly Parquet - * batch-plan runner (`design/PLATFORM-PLAN.md` §8 & D11, - * `design/DATA-CONTRACTS.md` §3.A). - * - * Pure, dependency-free, and browser-safe: zero `node:*` imports, zero DuckDB - * driver dependency, zero bare `process` access. SQL execution is injected via - * {@link DuckDbExecutor} from `./market-data-store-duckdb`. - * - * Output Parquet contract (`design/DATA-CONTRACTS.md` §3.A): - * - `/features//v/year=YYYY/part.parquet` - * - Columns: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, value DOUBLE)` - * - Compression: `ZSTD`, ordered by `(listing_id, ts)`. - * - * Point-in-time & `adj_factors` note: - * - Each expanded `{{input:}}` scan binds upper availability - * predicates strictly below `vaultCutoffDate` before authored SQL executes, - * while preserving earlier history for SQL-owned warm-up windows. - * - Feature definitions own per-observation availability (`knownAtRule` and - * projected `known_at`). Because `adj_factors` stores cumulative suffix - * products, any feature consuming `{{input:adj_factors}}` requires a - * caller-verified, immutable point-in-time snapshot compatible with the job - * cutoff. - * - * Economic ownership & research evidence: - * - The Quant research role owns the economic specification of each feature - * definition. - * - {@link RET_1D_V1} is a built-in 1-session raw-close return example using a - * zero-return comparison baseline and no execution or transaction cost model. - * - Any future research result claim built on materialized features must retain - * the feature ref and `definitionHash`, immutable dataset identifier, sample - * window, Vault cutoff, baseline, and execution assumptions. - */ - -import { - MarketDataStoreValidationError, - VaultHoldoutFenceError, - applyVaultFence, -} from './market-data-store'; -import { - type DuckDbExecutor, - type DuckDbParam, - validateCuratedRoot, -} from './market-data-store-duckdb'; -import { sha256HexUtf8 } from './sha256'; - -export const FEATURE_FAMILIES = [ - 'technical', - 'cross_sectional', - 'fundamental', - 'event', - 'fx', - 'regime', -] as const; -export type FeatureFamily = (typeof FEATURE_FAMILIES)[number]; - -export const FEATURE_KINDS = ['duckdb_sql'] as const; -export type FeatureKind = (typeof FEATURE_KINDS)[number]; - -export const FEATURE_INPUT_DATASETS = [ - 'bars_1d', - 'adj_factors', - 'events', - 'shorts', - 'fx_1d', - 'fundamentals_pit', -] as const; -export type FeatureInputDataset = (typeof FEATURE_INPUT_DATASETS)[number]; - -export const FEATURE_KNOWN_AT_RULES = [ - 'bar_close', - 'source_known_at', - 'max_input_known_at', -] as const; -export type FeatureKnownAtRule = (typeof FEATURE_KNOWN_AT_RULES)[number]; - -export const FEATURE_OUTPUT_COLUMNS = ['listing_id', 'ts', 'known_at', 'value'] as const; - -const FEATURE_FAMILY_SET: ReadonlySet = new Set(FEATURE_FAMILIES); -const FEATURE_INPUT_SET: ReadonlySet = new Set(FEATURE_INPUT_DATASETS); -const FEATURE_KNOWN_AT_RULE_SET: ReadonlySet = new Set(FEATURE_KNOWN_AT_RULES); - -const FEATURE_NAME_RE = /^[a-z][a-z0-9_]{0,62}$/; -const FEATURE_REF_RE = /^([a-z][a-z0-9_]{0,62})@v([1-9]\d*)$/; -const PLACEHOLDER_INNER_RE = /^input:([a-z][a-z0-9_]*)$/; -const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; - -const MIN_FOUR_DIGIT_YEAR = 1000; -const MAX_FOUR_DIGIT_YEAR = 9999; - -export type FeatureLibraryErrorCode = - | 'INVALID_DEFINITION' - | 'INVALID_NAME' - | 'INVALID_VERSION' - | 'INVALID_FAMILY' - | 'INVALID_KIND' - | 'INVALID_WARMUP_BARS' - | 'INVALID_KNOWN_AT_RULE' - | 'INVALID_FEATURE_REF' - | 'INVALID_SQL_STATEMENT' - | 'PROHIBITED_SQL_OPERATION' - | 'EXTERNAL_DATA_ACCESS' - | 'INVALID_SQL_PROJECTION' - | 'UNSUPPORTED_INPUT_DATASET' - | 'UNDECLARED_INPUT' - | 'UNUSED_INPUT' - | 'FEATURE_VERSION_IMMUTABLE' - | 'INVALID_BATCH_OPTIONS' - | 'VAULT_RANGE_VIOLATION' - | 'BATCH_WRITE_FAILED'; - -export interface FeatureBatchWriteReceipt { - readonly year: number; - readonly outputPath: string; -} - -export interface FeatureLibraryErrorDetails { - readonly cause?: unknown; - readonly failedYear?: number; - readonly completedYears?: readonly number[]; - readonly completedWrites?: readonly FeatureBatchWriteReceipt[]; - readonly ref?: string; -} - -/** Typed fail-closed error thrown by the Feature Library SDK. */ -export class FeatureLibraryError extends Error { - override readonly name = 'FeatureLibraryError'; - readonly code: FeatureLibraryErrorCode; - readonly failedYear?: number; - readonly completedYears?: readonly number[]; - readonly completedWrites?: readonly FeatureBatchWriteReceipt[]; - readonly ref?: string; - - constructor( - code: FeatureLibraryErrorCode, - message: string, - details?: FeatureLibraryErrorDetails - ) { - super(message, details?.cause !== undefined ? { cause: details.cause } : undefined); - this.code = code; - this.failedYear = details?.failedYear; - this.completedYears = - details?.completedYears !== undefined - ? Object.freeze([...details.completedYears]) - : undefined; - this.completedWrites = - details?.completedWrites !== undefined - ? Object.freeze(details.completedWrites.map(w => Object.freeze({ ...w }))) - : undefined; - this.ref = details?.ref; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -export interface FeatureDefinition { - readonly name: string; - readonly version: number; - readonly family: FeatureFamily; - readonly kind: FeatureKind; - readonly sql: string; - readonly inputs: readonly FeatureInputDataset[]; - readonly warmupBars: number; - readonly knownAtRule: FeatureKnownAtRule; - readonly description?: string; -} - -export interface FeatureRefParts { - readonly name: string; - readonly version: number; -} - -export interface RegisteredFeature { - readonly ref: string; - readonly definitionHash: string; - readonly definition: FeatureDefinition; -} - -export interface FeatureRegistry { - registerSignal(def: FeatureDefinition): RegisteredFeature; - get(ref: string): FeatureDefinition | undefined; - list(): readonly string[]; -} - -export interface PlanFeatureBatchOptions { - readonly curatedRoot: string; - readonly fromYear: number; - readonly toYear: number; - readonly vaultCutoffDate: string; -} - -export interface PlannedFeatureWrite { - readonly year: number; - readonly outputPath: string; - readonly sql: string; - readonly params: readonly DuckDbParam[]; -} - -export interface FeatureBatchManifest { - readonly ref: string; - readonly definitionHash: string; - readonly knownAtRule: FeatureKnownAtRule; - readonly warmupBars: number; - readonly inputs: readonly FeatureInputDataset[]; - readonly writes: readonly FeatureBatchWriteReceipt[]; -} - -const PROHIBITED_SQL_KEYWORDS: ReadonlySet = new Set([ - 'ALTER', - 'ANALYZE', - 'ATTACH', - 'BEGIN', - 'CALL', - 'CHECKPOINT', - 'COMMIT', - 'COPY', - 'CREATE', - 'DEALLOCATE', - 'DELETE', - 'DESCRIBE', - 'DETACH', - 'DROP', - 'EXECUTE', - 'EXPLAIN', - 'EXPORT', - 'GRANT', - 'IMPORT', - 'INSERT', - 'INSTALL', - 'LOAD', - 'MERGE', - 'PIVOT', - 'PRAGMA', - 'PREPARE', - 'RESET', - 'REVOKE', - 'ROLLBACK', - 'SET', - 'SHOW', - 'SUMMARIZE', - 'TRUNCATE', - 'UNPIVOT', - 'UPDATE', - 'UPSERT', - 'USE', - 'VACUUM', -]); - -const EXTERNAL_READER_IDENTIFIERS: ReadonlySet = new Set([ - 'CURRENT_SETTING', - 'DELTA_SCAN', - 'DUCKDB_COLUMNS', - 'DUCKDB_CONSTRAINTS', - 'DUCKDB_DATABASES', - 'DUCKDB_DEPENDENCIES', - 'DUCKDB_EXTENSIONS', - 'DUCKDB_FUNCTIONS', - 'DUCKDB_INDEXES', - 'DUCKDB_KEYWORDS', - 'DUCKDB_MEMORY', - 'DUCKDB_OPTIMIZERS', - 'DUCKDB_SCHEMAS', - 'DUCKDB_SECRETS', - 'DUCKDB_SEQUENCES', - 'DUCKDB_SETTINGS', - 'DUCKDB_TABLES', - 'DUCKDB_TEMPORARY_FILES', - 'DUCKDB_TYPES', - 'DUCKDB_VIEWS', - 'GETENV', - 'GLOB', - 'HTTP_GET', - 'ICEBERG_SCAN', - 'MYSQL_SCAN', - 'PARQUET_FILE_METADATA', - 'PARQUET_KV_METADATA', - 'PARQUET_METADATA', - 'PARQUET_SCAN', - 'PARQUET_SCHEMA', - 'POSTGRES_SCAN', - 'PRAGMA_DATABASE_LIST', - 'PRAGMA_STORAGE_INFO', - 'PRAGMA_TABLE_INFO', - 'READ_BLOB', - 'READ_CSV', - 'READ_CSV_AUTO', - 'READ_EXCEL', - 'READ_JSON', - 'READ_JSON_AUTO', - 'READ_NDJSON', - 'READ_NDJSON_AUTO', - 'READ_PARQUET', - 'READ_STAT', - 'READ_TEXT', - 'SQLITE_SCAN', - 'ST_READ', -]); - -/** - * Pure built-in scalar, aggregate, window, date/time, string, and type-cast - * functions permitted in declarative feature SQL. Excludes all file, network, - * catalog, secret, and system-inspection functions. - */ -const ALLOWED_SQL_FUNCTIONS: ReadonlySet = new Set([ - // Casting & type constructors - 'BIT', - 'CAST', - 'CHAR', - 'CHARACTER', - 'DECIMAL', - 'INTERVAL', - 'NUMERIC', - 'TIME', - 'TIMESTAMP', - 'TIMESTAMPTZ', - 'TRY_CAST', - 'TYPEOF', - 'VARCHAR', - // Null / conditional - 'COALESCE', - 'GREATEST', - 'IF', - 'IFNULL', - 'ISFINITE', - 'ISINF', - 'ISNAN', - 'LEAST', - 'NULLIF', - // Math - 'ABS', - 'ACOS', - 'ASIN', - 'ATAN', - 'ATAN2', - 'CBRT', - 'CEIL', - 'CEILING', - 'COS', - 'COT', - 'DEGREES', - 'EXP', - 'FLOOR', - 'LN', - 'LOG', - 'LOG10', - 'LOG2', - 'MOD', - 'PI', - 'POW', - 'POWER', - 'RADIANS', - 'ROUND', - 'SIGN', - 'SIN', - 'SQRT', - 'TAN', - 'TRUNC', - // Aggregate - 'ANY_VALUE', - 'ARG_MAX', - 'ARG_MIN', - 'AVG', - 'CORR', - 'COUNT', - 'COVAR_POP', - 'COVAR_SAMP', - 'FIRST', - 'GEOMEAN', - 'KURTOSIS', - 'LAST', - 'MAD', - 'MAX', - 'MEDIAN', - 'MIN', - 'MODE', - 'PERCENTILE_CONT', - 'PERCENTILE_DISC', - 'PRODUCT', - 'QUANTILE', - 'QUANTILE_CONT', - 'QUANTILE_DISC', - 'REGR_INTERCEPT', - 'REGR_R2', - 'REGR_SLOPE', - 'SKEWNESS', - 'STDDEV', - 'STDDEV_POP', - 'STDDEV_SAMP', - 'SUM', - 'VAR_POP', - 'VAR_SAMP', - 'VARIANCE', - // Window - 'CUME_DIST', - 'DENSE_RANK', - 'FIRST_VALUE', - 'LAG', - 'LAST_VALUE', - 'LEAD', - 'NTH_VALUE', - 'NTILE', - 'PERCENT_RANK', - 'RANK', - 'ROW_NUMBER', - // Date / time - 'DATE_ADD', - 'DATE_DIFF', - 'DATE_PART', - 'DATE_SUB', - 'DATE_TRUNC', - 'DATEDIFF', - 'DAY', - 'DAYOFWEEK', - 'DAYOFYEAR', - 'EPOCH', - 'EPOCH_MS', - 'EPOCH_NS', - 'EPOCH_US', - 'EXTRACT', - 'HOUR', - 'LAST_DAY', - 'MAKE_DATE', - 'MAKE_TIMESTAMP', - 'MINUTE', - 'MONTH', - 'QUARTER', - 'SECOND', - 'STRFTIME', - 'STRPTIME', - 'TIME_BUCKET', - 'WEEK', - 'YEAR', - // String & pure JSON - 'CONCAT', - 'CONCAT_WS', - 'CONTAINS', - 'ENDS_WITH', - 'JSON_EXTRACT', - 'JSON_EXTRACT_PATH', - 'JSON_EXTRACT_PATH_TEXT', - 'JSON_EXTRACT_STRING', - 'LEFT', - 'LENGTH', - 'LOWER', - 'LTRIM', - 'POSITION', - 'RIGHT', - 'RTRIM', - 'SPLIT_PART', - 'STARTS_WITH', - 'STRLEN', - 'STRPOS', - 'SUBSTR', - 'SUBSTRING', - 'TRIM', - 'UPPER', -]); - -/** SQL keywords that can syntactically precede `(` without being a function call. */ -const KEYWORD_BEFORE_LPAREN: ReadonlySet = new Set([ - 'ALL', - 'AND', - 'ANY', - 'AS', - 'ASC', - 'BETWEEN', - 'BY', - 'CASE', - 'DESC', - 'DISTINCT', - 'ELSE', - 'EXISTS', - 'FILTER', - 'FIRST', - 'FROM', - 'HAVING', - 'IN', - 'IS', - 'JOIN', - 'LAST', - 'NOT', - 'NULLS', - 'ON', - 'OR', - 'ORDER', - 'OVER', - 'PARTITION', - 'QUALIFY', - 'SELECT', - 'SOME', - 'THEN', - 'USING', - 'VALUES', - 'WHEN', - 'WHERE', - 'WITHIN', -]); - -const CLAUSE_TERMINATOR_KEYWORDS: ReadonlySet = new Set([ - 'EXCEPT', - 'FETCH', - 'FROM', - 'GROUP', - 'HAVING', - 'INTERSECT', - 'LIMIT', - 'OFFSET', - 'ORDER', - 'QUALIFY', - 'UNION', - 'WHERE', - 'WINDOW', -]); - -const JOIN_MODIFIER_KEYWORDS: ReadonlySet = new Set([ - 'ANTI', - 'ASOF', - 'CROSS', - 'FULL', - 'INNER', - 'JOIN', - 'LEFT', - 'NATURAL', - 'OUTER', - 'POSITIONAL', - 'RIGHT', - 'SEMI', -]); - -const NON_ALIAS_KEYWORDS: ReadonlySet = new Set([ - ...CLAUSE_TERMINATOR_KEYWORDS, - ...JOIN_MODIFIER_KEYWORDS, - 'ON', - 'USING', -]); - -const PATH_OR_URI_PREFIX_RE = /^(?:\/|\.\/|\.\.\/|~\/|(?:s3|gs|http|https|file|hf|az|r2):\/\/)/i; -const PATH_EXTENSION_RE = /\.(?:parquet|csv|tsv|json|jsonl|ndjson|duckdb|db|sqlite|txt|gz|zst)$/i; -const PATH_GLOB_OR_TRAVERSAL_RE = /(?:^|\/)\.\.(?:\/|$)|\/\*|\*\./; - -type SqlToken = - | { readonly kind: 'word'; readonly value: string; readonly upper: string; readonly raw: string } - | { readonly kind: 'quoted_ident'; readonly value: string; readonly raw: string } - | { readonly kind: 'string'; readonly value: string; readonly raw: string } - | { readonly kind: 'number'; readonly raw: string } - | { readonly kind: 'placeholder'; readonly dataset: string; readonly raw: string } - | { readonly kind: 'lparen'; readonly raw: '(' } - | { readonly kind: 'rparen'; readonly raw: ')' } - | { readonly kind: 'comma'; readonly raw: ',' } - | { readonly kind: 'dot'; readonly raw: '.' } - | { readonly kind: 'op'; readonly raw: string }; - -interface DatasetScanSpec { - readonly relativePath: string; - readonly hivePartitioning: boolean; - readonly predicateKind: 'ts_and_known_at' | 'known_at' | 'effective_known_at'; -} - -const DATASET_SCAN_SPECS: Readonly> = { - bars_1d: { - relativePath: 'bars_1d/year=*/part.parquet', - hivePartitioning: true, - predicateKind: 'ts_and_known_at', - }, - adj_factors: { - relativePath: 'adj_factors/part.parquet', - hivePartitioning: false, - predicateKind: 'known_at', - }, - events: { - relativePath: 'events/year=*/part.parquet', - hivePartitioning: true, - predicateKind: 'ts_and_known_at', - }, - shorts: { - relativePath: 'shorts/part.parquet', - hivePartitioning: false, - predicateKind: 'known_at', - }, - fx_1d: { - relativePath: 'fx_1d/part.parquet', - hivePartitioning: false, - predicateKind: 'ts_and_known_at', - }, - fundamentals_pit: { - relativePath: 'fundamentals_pit/year=*/part.parquet', - hivePartitioning: true, - predicateKind: 'effective_known_at', - }, -}; - -function isPlainRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function compareAscii(a: string, b: string): number { - return a < b ? -1 : a > b ? 1 : 0; -} - -function isAsciiWhitespace(code: number): boolean { - return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d || code === 0x0c; -} - -function isIdentStart(code: number): boolean { - return ( - (code >= 0x41 && code <= 0x5a) || // A-Z - (code >= 0x61 && code <= 0x7a) || // a-z - code === 0x5f // _ - ); -} - -function isIdentContinue(code: number): boolean { - return isIdentStart(code) || (code >= 0x30 && code <= 0x39); -} - -function isDigit(code: number): boolean { - return code >= 0x30 && code <= 0x39; -} - -function looksLikeExternalPath(value: string): boolean { - return ( - PATH_OR_URI_PREFIX_RE.test(value) || - PATH_EXTENSION_RE.test(value) || - PATH_GLOB_OR_TRAVERSAL_RE.test(value) - ); -} - -/** - * Quote-aware SQL tokenizer shared by validation, canonical hashing, and - * `{{input:}}` placeholder expansion. - */ -function tokenizeFeatureSql(sql: string): SqlToken[] { - const tokens: SqlToken[] = []; - const len = sql.length; - let i = 0; - - while (i < len) { - const code = sql.charCodeAt(i); - if (isAsciiWhitespace(code)) { - i += 1; - continue; - } - - // Reject SQL comments (-- or /* ... */). - if (code === 0x2d && i + 1 < len && sql.charCodeAt(i + 1) === 0x2d) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'SQL line comments ("--") are not permitted in feature definitions.' - ); - } - if (code === 0x2f && i + 1 < len && sql.charCodeAt(i + 1) === 0x2a) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'SQL block comments ("/* ... */") are not permitted in feature definitions.' - ); - } - if (code === 0x2a && i + 1 < len && sql.charCodeAt(i + 1) === 0x2f) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unexpected SQL block comment terminator ("*/") in feature definition.' - ); - } - - // Reject statement separators (;). - if (code === 0x3b) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Multiple SQL statements or semicolons (";") are not permitted in feature definitions.' - ); - } - - // Reject caller-supplied bind markers (?, $1, $name, :name). - if (code === 0x3f) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Caller-supplied bind markers ("?") are not permitted in feature definitions.' - ); - } - if (code === 0x24) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Dollar-prefixed parameters or dollar-quoted strings ("$") are not permitted in feature definitions.' - ); - } - - // Placeholder: {{input:}} - if (code === 0x7b && i + 1 < len && sql.charCodeAt(i + 1) === 0x7b) { - const closeIdx = sql.indexOf('}}', i + 2); - if (closeIdx === -1) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unterminated placeholder "{{" in feature SQL.' - ); - } - const inner = sql.slice(i + 2, closeIdx); - const match = PLACEHOLDER_INNER_RE.exec(inner); - if (match === null) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Malformed input placeholder "{{${inner}}}". Expected "{{input:}}".` - ); - } - const dataset = match[1] as string; - const raw = sql.slice(i, closeIdx + 2); - tokens.push({ kind: 'placeholder', dataset, raw }); - i = closeIdx + 2; - continue; - } - - // Single-quoted string literal ('...'). - if (code === 0x27) { - const start = i; - i += 1; - let value = ''; - let closed = false; - while (i < len) { - const c = sql.charCodeAt(i); - if (c === 0x27) { - if (i + 1 < len && sql.charCodeAt(i + 1) === 0x27) { - value += "'"; - i += 2; - continue; - } - i += 1; - closed = true; - break; - } - value += sql[i] as string; - i += 1; - } - if (!closed) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unterminated single-quoted string literal in feature SQL.' - ); - } - tokens.push({ kind: 'string', value, raw: sql.slice(start, i) }); - continue; - } - - // Double-quoted identifier ("..."). - if (code === 0x22) { - const start = i; - i += 1; - let value = ''; - let closed = false; - while (i < len) { - const c = sql.charCodeAt(i); - if (c === 0x22) { - if (i + 1 < len && sql.charCodeAt(i + 1) === 0x22) { - value += '"'; - i += 2; - continue; - } - i += 1; - closed = true; - break; - } - value += sql[i] as string; - i += 1; - } - if (!closed || value.length === 0) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unterminated or empty double-quoted identifier in feature SQL.' - ); - } - tokens.push({ kind: 'quoted_ident', value, raw: sql.slice(start, i) }); - continue; - } - - // Unquoted word (keyword or identifier). - if (isIdentStart(code)) { - const start = i; - i += 1; - while (i < len && isIdentContinue(sql.charCodeAt(i))) { - i += 1; - } - const value = sql.slice(start, i); - tokens.push({ kind: 'word', value, upper: value.toUpperCase(), raw: value }); - continue; - } - - // Numeric literal (digits or .digits). - if (isDigit(code) || (code === 0x2e && i + 1 < len && isDigit(sql.charCodeAt(i + 1)))) { - const start = i; - let hasDot = false; - if (code === 0x2e) { - hasDot = true; - i += 1; - } - while (i < len && isDigit(sql.charCodeAt(i))) { - i += 1; - } - if (!hasDot && i < len && sql.charCodeAt(i) === 0x2e) { - i += 1; - while (i < len && isDigit(sql.charCodeAt(i))) { - i += 1; - } - } - if (i < len && (sql.charCodeAt(i) === 0x65 || sql.charCodeAt(i) === 0x45)) { - const expPos = i; - i += 1; - if (i < len && (sql.charCodeAt(i) === 0x2b || sql.charCodeAt(i) === 0x2d)) { - i += 1; - } - if (i >= len || !isDigit(sql.charCodeAt(i))) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Malformed numeric exponent at offset ${expPos} in feature SQL.` - ); - } - while (i < len && isDigit(sql.charCodeAt(i))) { - i += 1; - } - } - tokens.push({ kind: 'number', raw: sql.slice(start, i) }); - continue; - } - - // Punctuation. - if (code === 0x28) { - tokens.push({ kind: 'lparen', raw: '(' }); - i += 1; - continue; - } - if (code === 0x29) { - tokens.push({ kind: 'rparen', raw: ')' }); - i += 1; - continue; - } - if (code === 0x2c) { - tokens.push({ kind: 'comma', raw: ',' }); - i += 1; - continue; - } - if (code === 0x2e) { - tokens.push({ kind: 'dot', raw: '.' }); - i += 1; - continue; - } - - // Two-character operators. - if (i + 1 < len) { - const two = sql.slice(i, i + 2); - if ( - two === '<>' || - two === '!=' || - two === '<=' || - two === '>=' || - two === '||' || - two === '::' - ) { - tokens.push({ kind: 'op', raw: two }); - i += 2; - continue; - } - } - - // Reject single ':' (named bind marker). - if (code === 0x3a) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Colon-prefixed bind markers (":name") are not permitted in feature definitions.' - ); - } - - // Single-character operators. - if ( - code === 0x2b || // + - code === 0x2d || // - - code === 0x2a || // * - code === 0x2f || // / - code === 0x25 || // % - code === 0x3d || // = - code === 0x3c || // < - code === 0x3e // > - ) { - tokens.push({ kind: 'op', raw: sql[i] as string }); - i += 1; - continue; - } - - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Unsupported token character "${sql[i] as string}" at offset ${i} in feature SQL.` - ); - } - - return tokens; -} - -function findMatchingParen(tokens: readonly SqlToken[], openIndex: number, end: number): number { - let depth = 0; - for (let i = openIndex; i < end; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - if (depth === 0) { - return i; - } - } - } - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unbalanced parentheses in feature SQL.' - ); -} - -function assertBalancedParens(tokens: readonly SqlToken[]): void { - let depth = 0; - for (let i = 0; i < tokens.length; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - if (depth < 0) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unbalanced closing parenthesis ")" in feature SQL.' - ); - } - } - } - if (depth !== 0) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unbalanced opening parenthesis "(" in feature SQL.' - ); - } -} - -function extractIdentifierText(tok: SqlToken | undefined): string | null { - if (tok === undefined) { - return null; - } - if (tok.kind === 'word') { - return tok.value.toLowerCase(); - } - if (tok.kind === 'quoted_ident') { - return tok.value; - } - return null; -} - -function extractProjectionOutputName(tokens: readonly SqlToken[], start: number, end: number): string { - if (start >= end) { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - 'Empty projection expression in final SELECT list.' - ); - } - - // Reject wildcard projections (* or alias.*) at top level of the projection item. - let depth = 0; - for (let i = start; i < end; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - } else if (depth === 0 && tok.kind === 'op' && tok.raw === '*') { - const prev = i > start ? tokens[i - 1] : undefined; - if (prev === undefined || prev.kind === 'dot') { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - 'Wildcard projections ("*" / "alias.*") are not permitted; final SELECT must explicitly project listing_id, ts, known_at, value.' - ); - } - } - } - - // Case 1: explicit `... AS ` at top level. - if (end - start >= 3) { - const asTok = tokens[end - 2]; - const aliasTok = tokens[end - 1]; - if (asTok?.kind === 'word' && asTok.upper === 'AS') { - const alias = extractIdentifierText(aliasTok); - if (alias === null) { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - 'Expected an output column identifier after AS in final SELECT projection.' - ); - } - return alias; - } - } - - // Case 2: simple column reference `` or `.`. - if (end - start === 1) { - const name = extractIdentifierText(tokens[start]); - if (name !== null) { - return name; - } - } - if (end - start === 3 && tokens[start + 1]?.kind === 'dot') { - const qual = extractIdentifierText(tokens[start]); - const col = extractIdentifierText(tokens[start + 2]); - if (qual !== null && col !== null) { - return col; - } - } - - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - 'Every expression in the final SELECT list must be a direct column reference or use an explicit AS alias matching (listing_id, ts, known_at, value).' - ); -} - -function hasTopLevelSetOperator(tokens: readonly SqlToken[], start: number, end: number): boolean { - let depth = 0; - for (let i = start; i < end; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - } else if ( - depth === 0 && - tok.kind === 'word' && - (tok.upper === 'UNION' || tok.upper === 'INTERSECT' || tok.upper === 'EXCEPT') - ) { - return true; - } - } - return false; -} - -function validateExpressionSlice( - tokens: readonly SqlToken[], - start: number, - end: number, - inScopeCtes: ReadonlySet -): void { - let i = start; - while (i < end) { - const tok = tokens[i] as SqlToken; - - // Nested subquery: (SELECT ...), (WITH ...), or compound subquery ((SELECT ...) UNION ...); - // reject DuckDB FROM-first / TABLE subqueries. - if (tok.kind === 'lparen') { - const closeIdx = findMatchingParen(tokens, i, end); - const innerFirst = tokens[i + 1]; - if ( - (innerFirst?.kind === 'word' && - (innerFirst.upper === 'SELECT' || innerFirst.upper === 'WITH')) || - hasTopLevelSetOperator(tokens, i + 1, closeIdx) - ) { - validateQuerySlice(tokens, i + 1, closeIdx, inScopeCtes, false); - i = closeIdx + 1; - continue; - } - if ( - innerFirst?.kind === 'word' && - (innerFirst.upper === 'FROM' || innerFirst.upper === 'TABLE') - ) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Unsupported subquery form "(${innerFirst.upper} ...)" in feature SQL; subqueries must begin with SELECT or WITH.` - ); - } - i += 1; - continue; - } - - // Fail closed if an unparsed JOIN token appears inside an expression or clause tail. - if (tok.kind === 'word' && tok.upper === 'JOIN') { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Unexpected JOIN outside a parsed FROM/JOIN clause in feature SQL.' - ); - } - - // Callable function check: followed by '('. - if ( - (tok.kind === 'word' || tok.kind === 'quoted_ident') && - i + 1 < end && - tokens[i + 1]?.kind === 'lparen' - ) { - const upper = tok.kind === 'word' ? tok.upper : tok.value.toUpperCase(); - if (tok.kind === 'word' && KEYWORD_BEFORE_LPAREN.has(upper)) { - i += 1; - continue; - } - // Reject schema-qualified function calls (e.g. main.read_parquet(...)). - if (i > start && tokens[i - 1]?.kind === 'dot') { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Schema-qualified function call ".${tok.raw}(...)" is not permitted in feature SQL.` - ); - } - if (!ALLOWED_SQL_FUNCTIONS.has(upper)) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Unsupported or prohibited SQL function "${tok.raw}(...)" in feature SQL.` - ); - } - } - - i += 1; - } -} - -// DuckDB folds identifier case for ASCII letters only; mirror that exact rule for CTE scope. -function foldAsciiIdentifier(identifier: string): string { - return identifier.replace(/[A-Z]/g, (ch) => String.fromCharCode(ch.charCodeAt(0) + 32)); -} - -function parseTableReference( - tokens: readonly SqlToken[], - start: number, - end: number, - inScopeCtes: ReadonlySet -): number { - if (start >= end) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Expected a relation source after FROM or JOIN in feature SQL.' - ); - } - - let pos = start; - const tok = tokens[pos] as SqlToken; - - if (tok.kind === 'placeholder') { - pos += 1; - } else if (tok.kind === 'lparen') { - const closeIdx = findMatchingParen(tokens, pos, end); - const innerFirst = tokens[pos + 1]; - if ( - innerFirst === undefined || - innerFirst.kind !== 'word' || - (innerFirst.upper !== 'SELECT' && innerFirst.upper !== 'WITH') - ) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - 'Parenthesized relation source must be a SELECT or WITH subquery.' - ); - } - validateQuerySlice(tokens, pos + 1, closeIdx, inScopeCtes, false); - pos = closeIdx + 1; - } else if (tok.kind === 'word' || tok.kind === 'quoted_ident') { - // Reject table functions (`fn(...)`) and qualified catalog relations (`schema.table`). - const next = pos + 1 < end ? tokens[pos + 1] : undefined; - if (next?.kind === 'lparen') { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Table function "${tok.raw}(...)" is not permitted as a relation source in feature SQL.` - ); - } - if (next?.kind === 'dot') { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Catalog or schema-qualified relation "${tok.raw}...." is not permitted; use {{input:}} placeholders.` - ); - } - const cteName = foldAsciiIdentifier(tok.value); - if (!inScopeCtes.has(cteName)) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Direct table reference "${tok.raw}" is not an in-scope CTE; use {{input:}} placeholders.` - ); - } - pos += 1; - } else { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Unsupported relation source "${tok.raw}" in feature SQL; use {{input:}}, an in-scope CTE, or a subquery.` - ); - } - - // Optional table alias: `[AS] [(col1, col2, ...)]`. - if (pos < end) { - const maybeAs = tokens[pos] as SqlToken; - if (maybeAs.kind === 'word' && maybeAs.upper === 'AS') { - pos += 1; - if (pos >= end || (tokens[pos]?.kind !== 'word' && tokens[pos]?.kind !== 'quoted_ident')) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Expected table alias identifier after AS.' - ); - } - pos += 1; - } else if ( - (maybeAs.kind === 'word' && !NON_ALIAS_KEYWORDS.has(maybeAs.upper)) || - maybeAs.kind === 'quoted_ident' - ) { - pos += 1; - } - - // Optional column alias list `(c1, c2)`. - if (pos < end && tokens[pos]?.kind === 'lparen') { - const closeIdx = findMatchingParen(tokens, pos, end); - pos = closeIdx + 1; - } - } - - return pos; -} - -function isJoinClauseStart(tokens: readonly SqlToken[], start: number, end: number): boolean { - let pos = start; - while (pos < end) { - const tok = tokens[pos] as SqlToken; - if (tok.kind !== 'word' || !JOIN_MODIFIER_KEYWORDS.has(tok.upper)) { - return false; - } - if (tok.upper === 'JOIN') { - return true; - } - pos += 1; - } - return false; -} - -function validateSelectBranch( - tokens: readonly SqlToken[], - start: number, - end: number, - inScopeCtes: ReadonlySet, - requireContractProjection: boolean -): void { - if (start >= end) { - throw new FeatureLibraryError('INVALID_SQL_STATEMENT', 'Empty SELECT branch in feature SQL.'); - } - - // Parenthesized SELECT branch: `(SELECT ...)` - if (tokens[start]?.kind === 'lparen') { - const closeIdx = findMatchingParen(tokens, start, end); - if (closeIdx === end - 1) { - validateQuerySlice(tokens, start + 1, closeIdx, inScopeCtes, requireContractProjection); - return; - } - } - - const first = tokens[start]; - if (first?.kind !== 'word' || first.upper !== 'SELECT') { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Expected SELECT statement, got "${first?.raw ?? ''}".` - ); - } - - let pos = start + 1; - if ( - pos < end && - tokens[pos]?.kind === 'word' && - ((tokens[pos] as { upper: string }).upper === 'DISTINCT' || - (tokens[pos] as { upper: string }).upper === 'ALL') - ) { - pos += 1; - } - - // Find end of SELECT projection list (first top-level FROM or other clause terminator). - let depth = 0; - let projEnd = end; - for (let i = pos; i < end; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - } else if (depth === 0 && tok.kind === 'word' && CLAUSE_TERMINATOR_KEYWORDS.has(tok.upper)) { - projEnd = i; - break; - } - } - - if (projEnd === pos) { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - 'SELECT clause has an empty projection list.' - ); - } - - // Validate expressions inside projection list. - validateExpressionSlice(tokens, pos, projEnd, inScopeCtes); - - if (requireContractProjection) { - const itemBounds: Array<{ start: number; end: number }> = []; - let itemStart = pos; - depth = 0; - for (let i = pos; i < projEnd; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - } else if (depth === 0 && tok.kind === 'comma') { - itemBounds.push({ start: itemStart, end: i }); - itemStart = i + 1; - } - } - itemBounds.push({ start: itemStart, end: projEnd }); - - if (itemBounds.length !== FEATURE_OUTPUT_COLUMNS.length) { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - `Final SELECT must project exactly ${FEATURE_OUTPUT_COLUMNS.length} columns (${FEATURE_OUTPUT_COLUMNS.join(', ')}), got ${itemBounds.length}.` - ); - } - - for (let idx = 0; idx < FEATURE_OUTPUT_COLUMNS.length; idx += 1) { - const bound = itemBounds[idx] as { start: number; end: number }; - const actualName = extractProjectionOutputName(tokens, bound.start, bound.end); - const expectedName = FEATURE_OUTPUT_COLUMNS[idx] as string; - if (actualName !== expectedName) { - throw new FeatureLibraryError( - 'INVALID_SQL_PROJECTION', - `Final SELECT column #${idx + 1} must be named "${expectedName}", got "${actualName}".` - ); - } - } - } - - // Scan FROM / JOIN clauses and remaining clauses at paren depth 0. - pos = projEnd; - while (pos < end) { - const tok = tokens[pos] as SqlToken; - - if (tok.kind === 'word' && tok.upper === 'FROM') { - pos += 1; - // Parse one or more comma-separated table references, plus any chained JOINs. - pos = parseTableReference(tokens, pos, end, inScopeCtes); - while (pos < end) { - const nextTok = tokens[pos] as SqlToken; - if (nextTok.kind === 'comma') { - pos += 1; - pos = parseTableReference(tokens, pos, end, inScopeCtes); - continue; - } - if (nextTok.kind === 'word' && JOIN_MODIFIER_KEYWORDS.has(nextTok.upper)) { - // Consume join modifiers up to and including JOIN. - let foundJoin = false; - while (pos < end) { - const jTok = tokens[pos] as SqlToken; - if (jTok.kind === 'word' && JOIN_MODIFIER_KEYWORDS.has(jTok.upper)) { - pos += 1; - if (jTok.upper === 'JOIN') { - foundJoin = true; - break; - } - } else { - break; - } - } - if (!foundJoin) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Malformed JOIN clause in feature SQL.' - ); - } - pos = parseTableReference(tokens, pos, end, inScopeCtes); - - // Optional ON or USING (...) before next JOIN or clause terminator. - if (pos < end && tokens[pos]?.kind === 'word') { - const condKw = (tokens[pos] as { upper: string }).upper; - if (condKw === 'ON' || condKw === 'USING') { - const condStart = pos + 1; - let condEnd = end; - let cDepth = 0; - for (let k = condStart; k < end; k += 1) { - const ct = tokens[k] as SqlToken; - if (ct.kind === 'lparen') { - cDepth += 1; - } else if (ct.kind === 'rparen') { - cDepth -= 1; - } else if ( - cDepth === 0 && - (ct.kind === 'comma' || - (ct.kind === 'word' && - (CLAUSE_TERMINATOR_KEYWORDS.has(ct.upper) || - isJoinClauseStart(tokens, k, end)))) - ) { - condEnd = k; - break; - } - } - validateExpressionSlice(tokens, condStart, condEnd, inScopeCtes); - pos = condEnd; - } - } - continue; - } - break; - } - if (pos < end) { - const afterFrom = tokens[pos] as SqlToken; - if ( - afterFrom.kind !== 'word' || - !CLAUSE_TERMINATOR_KEYWORDS.has(afterFrom.upper) || - afterFrom.upper === 'FROM' - ) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Unexpected token "${afterFrom.raw}" after FROM/JOIN clause in feature SQL.` - ); - } - } - continue; - } - - // Remaining clause expressions (WHERE, GROUP BY, HAVING, WINDOW, QUALIFY, ORDER BY, LIMIT, OFFSET). - const exprStart = pos; - let exprEnd = end; - let eDepth = 0; - for (let k = exprStart + 1; k < end; k += 1) { - const et = tokens[k] as SqlToken; - if (et.kind === 'lparen') { - eDepth += 1; - } else if (et.kind === 'rparen') { - eDepth -= 1; - } else if (eDepth === 0 && et.kind === 'word' && et.upper === 'FROM') { - exprEnd = k; - break; - } - } - validateExpressionSlice(tokens, exprStart, exprEnd, inScopeCtes); - pos = exprEnd; - } -} - -function validateQuerySlice( - tokens: readonly SqlToken[], - start: number, - end: number, - outerCtes: ReadonlySet, - requireContractProjection: boolean -): void { - if (start >= end) { - throw new FeatureLibraryError('INVALID_SQL_STATEMENT', 'Empty SQL query in feature definition.'); - } - - const inScopeCtes = new Set(outerCtes); - let pos = start; - - // Optional leading WITH clause (non-recursive CTEs only). - if (tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'WITH') { - pos += 1; - if (pos < end && tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'RECURSIVE') { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'WITH RECURSIVE CTEs are not permitted in feature SQL; use non-recursive CTEs.' - ); - } - - while (pos < end) { - const nameTok = tokens[pos]; - if (nameTok === undefined || (nameTok.kind !== 'word' && nameTok.kind !== 'quoted_ident')) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Expected CTE name identifier after WITH in feature SQL.' - ); - } - const cteName = foldAsciiIdentifier(nameTok.value); - pos += 1; - - // Optional CTE column list `(col1, col2)`. - if (pos < end && tokens[pos]?.kind === 'lparen') { - pos = findMatchingParen(tokens, pos, end) + 1; - } - - if (pos >= end || tokens[pos]?.kind !== 'word' || (tokens[pos] as { upper: string }).upper !== 'AS') { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Expected AS after CTE name "${nameTok.raw}" in feature SQL.` - ); - } - pos += 1; - - // Optional `[NOT] MATERIALIZED`. - if (pos < end && tokens[pos]?.kind === 'word' && (tokens[pos] as { upper: string }).upper === 'NOT') { - pos += 1; - } - if ( - pos < end && - tokens[pos]?.kind === 'word' && - (tokens[pos] as { upper: string }).upper === 'MATERIALIZED' - ) { - pos += 1; - } - - if (pos >= end || tokens[pos]?.kind !== 'lparen') { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Expected "(" opening CTE body for "${nameTok.raw}" in feature SQL.` - ); - } - const bodyClose = findMatchingParen(tokens, pos, end); - validateQuerySlice(tokens, pos + 1, bodyClose, inScopeCtes, false); - inScopeCtes.add(cteName); - pos = bodyClose + 1; - - if (pos < end && tokens[pos]?.kind === 'comma') { - pos += 1; - continue; - } - break; - } - } - - // Split remaining query by top-level set operators (UNION [ALL|DISTINCT], INTERSECT, EXCEPT). - const branches: Array<{ start: number; end: number }> = []; - let branchStart = pos; - let depth = 0; - for (let i = pos; i < end; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'lparen') { - depth += 1; - } else if (tok.kind === 'rparen') { - depth -= 1; - } else if ( - depth === 0 && - tok.kind === 'word' && - (tok.upper === 'UNION' || tok.upper === 'INTERSECT' || tok.upper === 'EXCEPT') - ) { - branches.push({ start: branchStart, end: i }); - let nextPos = i + 1; - if ( - nextPos < end && - tokens[nextPos]?.kind === 'word' && - ((tokens[nextPos] as { upper: string }).upper === 'ALL' || - (tokens[nextPos] as { upper: string }).upper === 'DISTINCT') - ) { - nextPos += 1; - } - branchStart = nextPos; - i = nextPos - 1; - } - } - branches.push({ start: branchStart, end }); - - for (let b = 0; b < branches.length; b += 1) { - const branch = branches[b] as { start: number; end: number }; - validateSelectBranch(tokens, branch.start, branch.end, inScopeCtes, requireContractProjection); - } -} - -interface ValidatedFeatureInternal { - readonly def: FeatureDefinition; - readonly tokens: readonly SqlToken[]; - readonly normalizedInputs: readonly FeatureInputDataset[]; -} - -function validateName(name: unknown): string { - if (typeof name !== 'string' || !FEATURE_NAME_RE.test(name)) { - throw new FeatureLibraryError( - 'INVALID_NAME', - `Invalid feature name "${String(name)}". Expected ^[a-z][a-z0-9_]{0,62}$.` - ); - } - return name; -} - -function validateVersion(version: unknown): number { - if (typeof version !== 'number' || !Number.isSafeInteger(version) || version < 1) { - throw new FeatureLibraryError( - 'INVALID_VERSION', - `Invalid feature version "${String(version)}". Expected a positive safe integer.` - ); - } - return version; -} - -function validateFeatureDefinitionInternal(def: FeatureDefinition): ValidatedFeatureInternal { - if (!isPlainRecord(def)) { - throw new FeatureLibraryError( - 'INVALID_DEFINITION', - 'Feature definition must be a plain object.' - ); - } - - validateName(def.name); - validateVersion(def.version); - - if (typeof def.family !== 'string' || !FEATURE_FAMILY_SET.has(def.family)) { - throw new FeatureLibraryError( - 'INVALID_FAMILY', - `Invalid feature family "${String(def.family)}". Expected one of: ${FEATURE_FAMILIES.join(', ')}.` - ); - } - - if (def.kind !== 'duckdb_sql') { - throw new FeatureLibraryError( - 'INVALID_KIND', - `Invalid feature kind "${String(def.kind)}". Expected 'duckdb_sql'.` - ); - } - - if (typeof def.warmupBars !== 'number' || !Number.isSafeInteger(def.warmupBars) || def.warmupBars < 0) { - throw new FeatureLibraryError( - 'INVALID_WARMUP_BARS', - `Invalid warmupBars "${String(def.warmupBars)}". Expected a non-negative safe integer.` - ); - } - - if (typeof def.knownAtRule !== 'string' || !FEATURE_KNOWN_AT_RULE_SET.has(def.knownAtRule)) { - throw new FeatureLibraryError( - 'INVALID_KNOWN_AT_RULE', - `Invalid knownAtRule "${String(def.knownAtRule)}". Expected one of: ${FEATURE_KNOWN_AT_RULES.join(', ')}.` - ); - } - - if (def.description !== undefined && typeof def.description !== 'string') { - throw new FeatureLibraryError( - 'INVALID_DEFINITION', - 'Feature description must be a string when provided.' - ); - } - - if (!Array.isArray(def.inputs) || def.inputs.length === 0) { - throw new FeatureLibraryError( - 'INVALID_DEFINITION', - 'Feature definition must declare a non-empty inputs array.' - ); - } - - const declaredSet = new Set(); - const normalizedInputs: FeatureInputDataset[] = []; - for (let i = 0; i < def.inputs.length; i += 1) { - const rawInput: unknown = def.inputs[i]; - if (typeof rawInput !== 'string' || !FEATURE_INPUT_SET.has(rawInput)) { - throw new FeatureLibraryError( - 'UNSUPPORTED_INPUT_DATASET', - `Unsupported input dataset "${String(rawInput)}". Allowed datasets: ${FEATURE_INPUT_DATASETS.join(', ')}.` - ); - } - const ds = rawInput as FeatureInputDataset; - if (!declaredSet.has(ds)) { - declaredSet.add(ds); - normalizedInputs.push(ds); - } - } - - if (typeof def.sql !== 'string' || def.sql.trim().length === 0) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Feature SQL must be a non-empty string.' - ); - } - - const tokens = tokenizeFeatureSql(def.sql); - if (tokens.length === 0) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - 'Feature SQL must contain a SELECT or WITH statement.' - ); - } - - // Pass 1: check prohibited statement/operation keywords. - for (let i = 0; i < tokens.length; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'word' && PROHIBITED_SQL_KEYWORDS.has(tok.upper)) { - throw new FeatureLibraryError( - 'PROHIBITED_SQL_OPERATION', - `Prohibited SQL operation "${tok.raw}" is not permitted in feature definitions.` - ); - } - } - - // Pass 2: check external readers and quoted file paths/URIs. - for (let i = 0; i < tokens.length; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'word' && EXTERNAL_READER_IDENTIFIERS.has(tok.upper)) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Direct external reader "${tok.raw}" is not permitted; reference datasets via {{input:}}.` - ); - } - if (tok.kind === 'quoted_ident' && EXTERNAL_READER_IDENTIFIERS.has(tok.value.toUpperCase())) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Direct external reader ${tok.raw} is not permitted; reference datasets via {{input:}}.` - ); - } - if ((tok.kind === 'string' || tok.kind === 'quoted_ident') && looksLikeExternalPath(tok.value)) { - throw new FeatureLibraryError( - 'EXTERNAL_DATA_ACCESS', - `Quoted file path or URI ${tok.raw} is not permitted in feature SQL; reference datasets via {{input:}}.` - ); - } - } - - // Pass 3: check leading statement keyword and balanced parentheses. - const firstTok = tokens[0] as SqlToken; - if (firstTok.kind !== 'word' || (firstTok.upper !== 'SELECT' && firstTok.upper !== 'WITH')) { - throw new FeatureLibraryError( - 'INVALID_SQL_STATEMENT', - `Feature SQL must begin with SELECT or WITH, got "${firstTok.raw}".` - ); - } - assertBalancedParens(tokens); - - // Pass 4: structural validation of CTEs, FROM/JOIN sources, functions, and final projection. - validateQuerySlice(tokens, 0, tokens.length, new Set(), true); - - // Pass 5: verify placeholder declarations and usage. - const usedInputs = new Set(); - for (let i = 0; i < tokens.length; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind !== 'placeholder') { - continue; - } - if (!declaredSet.has(tok.dataset as FeatureInputDataset)) { - throw new FeatureLibraryError( - 'UNDECLARED_INPUT', - `SQL placeholder "{{input:${tok.dataset}}}" is not declared in definition.inputs.` - ); - } - usedInputs.add(tok.dataset as FeatureInputDataset); - } - - for (let i = 0; i < normalizedInputs.length; i += 1) { - const declared = normalizedInputs[i] as FeatureInputDataset; - if (!usedInputs.has(declared)) { - throw new FeatureLibraryError( - 'UNUSED_INPUT', - `Declared input dataset "${declared}" is not referenced via "{{input:${declared}}}" in feature SQL.` - ); - } - } - - return { def, tokens, normalizedInputs }; -} - -/** - * Validates a declarative feature definition and throws a typed - * {@link FeatureLibraryError} on any contract, SQL safety, projection, or - * input-declaration violation. - */ -export function validateFeatureDefinition(def: FeatureDefinition): void { - validateFeatureDefinitionInternal(def); -} - -/** - * Formats the canonical versioned feature reference `'@v'`. - */ -export function featureRef(def: Pick): string { - if (!isPlainRecord(def)) { - throw new FeatureLibraryError( - 'INVALID_DEFINITION', - 'Expected an object with name and version for featureRef.' - ); - } - const name = validateName(def.name); - const version = validateVersion(def.version); - return `${name}@v${version}`; -} - -/** - * Parses a canonical versioned feature reference `'@v'`, - * rejecting non-canonical forms such as `'ret_1d@v01'` or `'RSI-14@v1'`. - */ -export function parseFeatureRef(ref: string): FeatureRefParts { - if (typeof ref !== 'string') { - throw new FeatureLibraryError( - 'INVALID_FEATURE_REF', - `Invalid feature ref "${String(ref)}". Expected "@v".` - ); - } - const match = FEATURE_REF_RE.exec(ref); - if (match === null) { - throw new FeatureLibraryError( - 'INVALID_FEATURE_REF', - `Invalid feature ref "${ref}". Expected "@v" with lowercase name and canonical positive integer version.` - ); - } - const name = match[1] as string; - const version = Number(match[2]); - if (!Number.isSafeInteger(version) || version < 1) { - throw new FeatureLibraryError( - 'INVALID_FEATURE_REF', - `Invalid feature version in ref "${ref}". Expected a positive safe integer.` - ); - } - return Object.freeze({ name, version }); -} - -function canonicalizeSqlTokens(tokens: readonly SqlToken[]): string { - const parts = new Array(tokens.length); - for (let i = 0; i < tokens.length; i += 1) { - parts[i] = (tokens[i] as SqlToken).raw; - } - return parts.join(' '); -} - -/** - * Computes a deterministic 64-character lowercase SHA-256 hex digest over the - * semantic specification of a validated feature definition (name, version, - * kind, canonicalized SQL tokens, sorted inputs, `warmupBars`, and - * `knownAtRule`). Inter-token whitespace, object key order, and input array - * order do not affect the hash; literal whitespace and semantic changes do. - */ -export function featureDefinitionHash(def: FeatureDefinition): string { - const validated = validateFeatureDefinitionInternal(def); - const sortedInputs = [...validated.normalizedInputs].sort(compareAscii); - const canonicalPayload = JSON.stringify({ - name: def.name, - version: def.version, - kind: def.kind, - sql: canonicalizeSqlTokens(validated.tokens), - inputs: sortedInputs, - warmupBars: def.warmupBars, - knownAtRule: def.knownAtRule, - }); - return sha256HexUtf8(canonicalPayload); -} - -function cloneFeatureDefinition(def: FeatureDefinition): FeatureDefinition { - const copy: FeatureDefinition = { - name: def.name, - version: def.version, - family: def.family, - kind: def.kind, - sql: def.sql, - inputs: Object.freeze([...def.inputs]), - warmupBars: def.warmupBars, - knownAtRule: def.knownAtRule, - ...(def.description !== undefined ? { description: def.description } : {}), - }; - return Object.freeze(copy); -} - -/** - * Creates an in-memory immutable versioned feature registry (`registerSignal` - * SDK entrypoint, D11). Re-registering an identical definition hash is - * idempotent; re-registering the same `@v` with a different - * semantic hash throws `FeatureLibraryError('FEATURE_VERSION_IMMUTABLE')`. - */ -export function createFeatureRegistry(): FeatureRegistry { - const entries = new Map(); - - return { - registerSignal(def: FeatureDefinition): RegisteredFeature { - validateFeatureDefinitionInternal(def); - const ref = featureRef(def); - const definitionHash = featureDefinitionHash(def); - const existing = entries.get(ref); - if (existing !== undefined) { - if (existing.definitionHash === definitionHash) { - return Object.freeze({ - ref: existing.ref, - definitionHash: existing.definitionHash, - definition: cloneFeatureDefinition(existing.definition), - }); - } - throw new FeatureLibraryError( - 'FEATURE_VERSION_IMMUTABLE', - `Feature "${ref}" is already registered with hash ${existing.definitionHash}; cannot overwrite with ${definitionHash}. Bump version to register a changed definition.`, - { ref } - ); - } - - const stored: RegisteredFeature = Object.freeze({ - ref, - definitionHash, - definition: cloneFeatureDefinition(def), - }); - entries.set(ref, stored); - return Object.freeze({ - ref: stored.ref, - definitionHash: stored.definitionHash, - definition: cloneFeatureDefinition(stored.definition), - }); - }, - - get(ref: string): FeatureDefinition | undefined { - if (typeof ref !== 'string') { - return undefined; - } - const existing = entries.get(ref); - return existing !== undefined ? cloneFeatureDefinition(existing.definition) : undefined; - }, - - list(): readonly string[] { - return Array.from(entries.keys()); - }, - }; -} - -function joinCuratedPath(normalizedRoot: string, relativePath: string): string { - return normalizedRoot === '/' ? `/${relativePath}` : `${normalizedRoot}/${relativePath}`; -} - -function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { - const isoMs = new Date(epochMs).toISOString(); - if (subMsMicros === 0) { - return isoMs; - } - const extra = String(subMsMicros).padStart(3, '0'); - return `${isoMs.slice(0, -1)}${extra}Z`; -} - -function validateFourDigitYear(value: unknown, field: string): number { - if ( - typeof value !== 'number' || - !Number.isSafeInteger(value) || - value < MIN_FOUR_DIGIT_YEAR || - value > MAX_FOUR_DIGIT_YEAR - ) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - `Invalid "${field}": "${String(value)}". Expected a four-digit integer year (${MIN_FOUR_DIGIT_YEAR}..${MAX_FOUR_DIGIT_YEAR}).` - ); - } - return value; -} - -function parseVaultCutoffDateMs(raw: unknown): number { - if (typeof raw !== 'string' || !DATE_ONLY_RE.test(raw)) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - `Invalid "vaultCutoffDate": "${String(raw)}". Expected strict UTC YYYY-MM-DD date string.` - ); - } - try { - const parsed = applyVaultFence( - { from: raw, to: raw, scope: 'vault_evaluation_only' }, - { vaultCutoffTs: 0, vaultOperatorAuthorized: true } - ); - return parsed.fromMs; - } catch (error) { - if (error instanceof MarketDataStoreValidationError) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - `Invalid "vaultCutoffDate": ${error.message}`, - { cause: error } - ); - } - throw error; - } -} - -function expandSqlForYear( - tokens: readonly SqlToken[], - curatedRoot: string, - tsUpperIso: string, - knownAtUpperIso: string -): { sql: string; scanParams: DuckDbParam[] } { - const scanParams: DuckDbParam[] = []; - const parts: string[] = []; - - for (let i = 0; i < tokens.length; i += 1) { - const tok = tokens[i] as SqlToken; - if (tok.kind === 'placeholder') { - const ds = tok.dataset as FeatureInputDataset; - const spec = DATASET_SCAN_SPECS[ds]; - const fullPath = joinCuratedPath(curatedRoot, spec.relativePath); - const readCall = spec.hivePartitioning - ? `read_parquet('${fullPath}', hive_partitioning = true)` - : `read_parquet('${fullPath}')`; - - if (spec.predicateKind === 'ts_and_known_at') { - parts.push(`(SELECT * FROM ${readCall} WHERE ts <= ? AND known_at <= ?)`); - scanParams.push(tsUpperIso, knownAtUpperIso); - } else if (spec.predicateKind === 'effective_known_at') { - parts.push(`(SELECT * FROM ${readCall} WHERE effective_known_at <= ?)`); - scanParams.push(knownAtUpperIso); - } else { - parts.push(`(SELECT * FROM ${readCall} WHERE known_at <= ?)`); - scanParams.push(knownAtUpperIso); - } - continue; - } - - parts.push(tok.raw); - } - - return { - sql: parts.join(' '), - scanParams, - }; -} - -/** - * Plans ordered yearly Vault-fenced DuckDB `COPY ... TO ... (FORMAT PARQUET, - * COMPRESSION ZSTD)` statements for a validated feature definition. - */ -export function planFeatureBatch( - def: FeatureDefinition, - options: PlanFeatureBatchOptions -): readonly PlannedFeatureWrite[] { - const validated = validateFeatureDefinitionInternal(def); - - if (!isPlainRecord(options)) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - 'Feature batch options must be a plain object.' - ); - } - - let curatedRoot: string; - try { - curatedRoot = validateCuratedRoot(options.curatedRoot); - } catch (error) { - if (error instanceof MarketDataStoreValidationError) { - throw new FeatureLibraryError('INVALID_BATCH_OPTIONS', error.message, { cause: error }); - } - throw error; - } - - const fromYear = validateFourDigitYear(options.fromYear, 'fromYear'); - const toYear = validateFourDigitYear(options.toYear, 'toYear'); - if (fromYear > toYear) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - `Invalid year range: fromYear (${fromYear}) must not exceed toYear (${toYear}).` - ); - } - - const cutoffMs = parseVaultCutoffDateMs(options.vaultCutoffDate); - const rangeFrom = `${String(fromYear).padStart(4, '0')}-01-01`; - const rangeTo = `${String(toYear).padStart(4, '0')}-12-31`; - - let fenced; - try { - fenced = applyVaultFence( - { from: rangeFrom, to: rangeTo, scope: 'vault_fenced' }, - { vaultCutoffTs: cutoffMs } - ); - } catch (error) { - if (error instanceof VaultHoldoutFenceError) { - throw new FeatureLibraryError( - 'VAULT_RANGE_VIOLATION', - `Requested year range [${fromYear}, ${toYear}] falls on or after vaultCutoffDate "${options.vaultCutoffDate}".`, - { cause: error } - ); - } - if (error instanceof MarketDataStoreValidationError) { - throw new FeatureLibraryError('INVALID_BATCH_OPTIONS', error.message, { cause: error }); - } - throw error; - } - - const lastPlannedYear = Math.min(toYear, new Date(fenced.toMs).getUTCFullYear()); - if (lastPlannedYear < fromYear) { - throw new FeatureLibraryError( - 'VAULT_RANGE_VIOLATION', - `No pre-cutoff years remain in [${fromYear}, ${toYear}] for vaultCutoffDate "${options.vaultCutoffDate}".` - ); - } - - // Last included Parquet microsecond strictly before vaultCutoffDate (00:00:00.000Z). - const vaultCeilingMs = cutoffMs - 1; - const knownAtUpperIso = formatUtcIsoWithMicros(vaultCeilingMs, 999); - - const writes: PlannedFeatureWrite[] = []; - for (let year = fromYear; year <= lastPlannedYear; year += 1) { - const yearEndMs = Date.UTC(year, 11, 31, 23, 59, 59, 999); - const effectiveTsEndMs = Math.min(yearEndMs, vaultCeilingMs); - const tsUpperIso = formatUtcIsoWithMicros(effectiveTsEndMs, 999); - - const { sql: expandedSql, scanParams } = expandSqlForYear( - validated.tokens, - curatedRoot, - tsUpperIso, - knownAtUpperIso - ); - - const outputPath = joinCuratedPath( - curatedRoot, - `features/${def.name}/v${def.version}/year=${year}/part.parquet` - ); - - const sql = - 'COPY (SELECT listing_id, ts, known_at, value ' + - 'FROM (SELECT CAST(listing_id AS INTEGER) AS listing_id, CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, CAST(value AS DOUBLE) AS value ' + - `FROM (${expandedSql}) AS __feature_source) AS __feature_typed ` + - 'WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ' + - `ORDER BY listing_id, ts) TO '${outputPath}' (FORMAT PARQUET, COMPRESSION ZSTD)`; - - const params: DuckDbParam[] = [...scanParams, year, tsUpperIso, knownAtUpperIso]; - - writes.push( - Object.freeze({ - year, - outputPath, - sql, - params: Object.freeze(params), - }) - ); - } - - return Object.freeze(writes); -} - -/** - * Validates and plans a feature batch upfront, executes each yearly Parquet - * `COPY` sequentially via `executor.query(sql, params)`, and returns a - * manifest. Stops on the first executor failure and throws - * `FeatureLibraryError('BATCH_WRITE_FAILED')` exposing `cause`, `failedYear`, - * `completedYears`, and `completedWrites`. - */ -export async function runFeatureBatch( - def: FeatureDefinition, - options: PlanFeatureBatchOptions, - executor: DuckDbExecutor -): Promise { - if ( - typeof executor !== 'object' || - executor === null || - typeof (executor as { query?: unknown }).query !== 'function' - ) { - throw new FeatureLibraryError( - 'INVALID_BATCH_OPTIONS', - 'Expected a DuckDbExecutor object with a query(sql, params) method.' - ); - } - - validateFeatureDefinitionInternal(def); - const snapshot = cloneFeatureDefinition(def); - const plannedWrites = planFeatureBatch(snapshot, options); - const ref = featureRef(snapshot); - const definitionHash = featureDefinitionHash(snapshot); - const sortedInputs = [...new Set(snapshot.inputs)].sort(compareAscii); - const { knownAtRule, warmupBars } = snapshot; - - const completedWrites: FeatureBatchWriteReceipt[] = []; - for (let i = 0; i < plannedWrites.length; i += 1) { - const write = plannedWrites[i] as PlannedFeatureWrite; - try { - await executor.query(write.sql, write.params); - } catch (cause) { - const completedYears = completedWrites.map(w => w.year); - throw new FeatureLibraryError( - 'BATCH_WRITE_FAILED', - `Feature batch write failed for "${ref}" on year ${write.year} (completed years: ${completedYears.length > 0 ? completedYears.join(', ') : 'none'}).`, - { - cause, - failedYear: write.year, - completedYears, - completedWrites, - ref, - } - ); - } - completedWrites.push( - Object.freeze({ - year: write.year, - outputPath: write.outputPath, - }) - ); - } - - return Object.freeze({ - ref, - definitionHash, - knownAtRule, - warmupBars, - inputs: Object.freeze(sortedInputs), - writes: Object.freeze(completedWrites), - }); -} - -/** - * Built-in example feature definition (`ret_1d@v1`): 1-day simple raw-close - * return per listing with bar-close availability (`known_at = ts`) and 1-bar - * warm-up. Omits rows without a usable positive prior close. - * - * Comparison baseline: zero return (`0.0`); no execution or transaction cost - * model is included. - */ -export const RET_1D_V1: FeatureDefinition = Object.freeze({ - name: 'ret_1d', - version: 1, - family: 'technical', - kind: 'duckdb_sql', - inputs: Object.freeze(['bars_1d'] as const), - warmupBars: 1, - knownAtRule: 'bar_close', - description: - '1-day simple raw-close return per listing with bar-close availability; comparison baseline is 0 return with no execution or cost model.', - sql: [ - 'WITH lagged AS (', - ' SELECT', - ' listing_id,', - ' ts,', - ' close,', - ' LAG(close) OVER (PARTITION BY listing_id ORDER BY ts ASC) AS prev_close', - ' FROM {{input:bars_1d}}', - ')', - 'SELECT', - ' listing_id,', - ' ts,', - ' ts AS known_at,', - ' (close / prev_close) - 1.0 AS value', - 'FROM lagged', - 'WHERE prev_close IS NOT NULL AND prev_close > 0 AND close > 0', - ].join('\n'), -}); diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index bb5e7062..3d57d822 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -1,11 +1,8 @@ // The default entrypoint is browser safe; server validation is an explicit subpath. export * from './dataset-contracts'; export * from './event-panel'; -export * from './feature-library'; export * from './market-data-store'; export * from './market-data-store-duckdb'; -export * from './market-data-store-questdb'; -export * from './market-data-store-routed'; export * from './signal-panel'; export * from './signal-study'; export * from './trial-ledger'; diff --git a/libs/research/src/market-data-store-duckdb.ts b/libs/research/src/market-data-store-duckdb.ts index fd6dd8ae..0d3013ba 100644 --- a/libs/research/src/market-data-store-duckdb.ts +++ b/libs/research/src/market-data-store-duckdb.ts @@ -14,7 +14,6 @@ * - `/events/year=*\/part.parquet` (`hive_partitioning = true`) * - `/shorts/part.parquet` * - `/fx_1d/part.parquet` - * - `/fundamentals_pit/year=*\/part.parquet` (`hive_partitioning = true`) * * `bars` (`timeframe: '1d'`) adjustment formulas (`tools/curate-etl/README.md`): * - `bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share @@ -75,7 +74,6 @@ import { type Table, type TableCell, type TableRow, - VaultHoldoutFenceError, applyVaultFence, resolveDuckDbConnectionBudget, } from './market-data-store'; @@ -157,29 +155,7 @@ export const FX_1D_COLUMNS = [ 'known_at', ] as const; -export const FUNDAMENTALS_PIT_VALUE_FIELDS = [ - 'revenue', - 'net_income', - 'operating_cash_flow', - 'total_assets', - 'total_equity', - 'shares_outstanding', - 'ttm_revenue', - 'ttm_net_income', - 'ttm_operating_cash_flow', -] as const; -export type FundamentalsPitValueField = (typeof FUNDAMENTALS_PIT_VALUE_FIELDS)[number]; - -const FUNDAMENTALS_PIT_VALUE_FIELD_MAP: ReadonlyMap = new Map( - FUNDAMENTALS_PIT_VALUE_FIELDS.map(field => [field, field]) -); -const FUNDAMENTALS_TTM_VALUE_FIELD_SET: ReadonlySet = new Set([ - 'ttm_revenue', - 'ttm_net_income', - 'ttm_operating_cash_flow', -]); - -type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string' | 'boolean'; +type ColumnScalarKind = 'int32' | 'safe_int' | 'number' | 'string'; interface TableColumnSpec { readonly name: string; @@ -219,23 +195,6 @@ const FX_1D_SCHEMA: readonly TableColumnSpec[] = [ { name: 'known_at', kind: 'safe_int', nullable: false }, ]; -const FUNDAMENTALS_BASE_SCHEMA: readonly TableColumnSpec[] = [ - { name: 'listing_id', kind: 'int32', nullable: false }, - { name: 'effective_known_at', kind: 'safe_int', nullable: false }, - { name: 'known_at_source', kind: 'string', nullable: false }, - { name: 'has_estimated_lag', kind: 'boolean', nullable: false }, - { name: 'period_end', kind: 'string', nullable: false }, - { name: 'fiscal_period', kind: 'string', nullable: false }, - { name: 'currency', kind: 'string', nullable: false }, - { name: 'period_known_at', kind: 'safe_int', nullable: false }, -]; - -const FUNDAMENTALS_TTM_META_SCHEMA: readonly TableColumnSpec[] = [ - { name: 'ttm_period_end', kind: 'string', nullable: true }, - { name: 'ttm_currency', kind: 'string', nullable: true }, - { name: 'ttm_has_estimated_lag', kind: 'boolean', nullable: true }, -]; - /** Scalar parameter value bound separately from SQL text. */ export type DuckDbParam = string | number | boolean | null; @@ -398,7 +357,6 @@ export type EventsQuery = Parameters[0]; export type ShortsAsOfQuery = Parameters[0]; export type FxQuery = Parameters[0]; export type UniverseQuery = Parameters[0]; -export type FundamentalsAsOfQuery = Parameters[0]; /** * Thrown when a `MarketDataStore` method or timeframe is outside the curated @@ -619,50 +577,6 @@ function validateEventKinds(raw: readonly EventKind[], field = 'kinds'): EventKi return normalized; } -function validateFundamentalsFields( - raw: readonly string[], - field = 'fields' -): FundamentalsPitValueField[] { - if (!Array.isArray(raw) || raw.length === 0) { - throw new MarketDataStoreValidationError( - `Expected a non-empty array of fundamentals value fields for "${field}".`, - field - ); - } - - const seen = new Set(); - const normalized: FundamentalsPitValueField[] = []; - for (let i = 0; i < raw.length; i += 1) { - const name: unknown = raw[i]; - const canonical = - typeof name === 'string' ? FUNDAMENTALS_PIT_VALUE_FIELD_MAP.get(name) : undefined; - if (canonical === undefined) { - throw new MarketDataStoreValidationError( - `Unknown fundamentals field "${String(name)}". Expected one of: ${FUNDAMENTALS_PIT_VALUE_FIELDS.join(', ')}.`, - field - ); - } - if (!seen.has(canonical)) { - seen.add(canonical); - normalized.push(canonical); - } - } - return normalized; -} - -function validateAllowEstimatedLag(raw: unknown): boolean { - if (raw === undefined) { - return true; - } - if (typeof raw !== 'boolean') { - throw new MarketDataStoreValidationError( - `Invalid allowEstimatedLag "${String(raw)}". Expected a boolean.`, - 'allowEstimatedLag' - ); - } - return raw; -} - function validateAdjustment(raw: unknown): (typeof BARS_ADJUSTMENTS)[number] { if (typeof raw !== 'string' || !BARS_ADJUSTMENT_SET.has(raw)) { throw new MarketDataStoreValidationError( @@ -1661,158 +1575,6 @@ export function planUniverseQuery(q: UniverseQuery, ctx: DuckDbPlanContext): Pla }; } -interface PlannedFundamentalsAsOfInternal { - readonly planned: PlannedDuckDbQuery; - readonly columns: readonly string[]; - readonly schema: readonly TableColumnSpec[]; -} - -function planFundamentalsAsOfInternal( - q: FundamentalsAsOfQuery, - ctx: DuckDbPlanContext -): PlannedFundamentalsAsOfInternal { - const curatedRoot = validateContext(ctx); - if (!isPlainRecord(q)) { - throw new MarketDataStoreValidationError( - 'Expected a fundamentalsAsOf query object.', - 'query' - ); - } - - const listingIds = validateListingIds(q.listingIds); - const fields = validateFundamentalsFields(q.fields); - const allowEstimatedLag = validateAllowEstimatedLag(q.allowEstimatedLag); - - let fenced: FencedTimeRange; - try { - fenced = applyVaultFence( - { - from: q.asOf, - to: q.asOf, - asOf: q.asOf, - scope: 'vault_fenced', - }, - { - vaultCutoffTs: ctx.vaultCutoffTs, - } - ); - } catch (err: unknown) { - if (err instanceof VaultHoldoutFenceError) { - const maxAllowedMs = ctx.vaultCutoffTs - 1; - fenced = { - fromMs: maxAllowedMs, - toMs: maxAllowedMs, - asOfMs: maxAllowedMs, - scope: 'vault_fenced', - clampedTo: true, - clampedAsOf: true, - }; - } else if ( - err instanceof MarketDataStoreValidationError && - (err.field === 'from' || err.field === 'to') - ) { - throw new MarketDataStoreValidationError(err.message, 'asOf'); - } else { - throw err; - } - } - - const asOfSubMs = resolveAsOfSubMsMicros(q.asOf, q.asOf, fenced); - const asOfIso = formatUtcIsoWithMicros(fenced.asOfMs, asOfSubMs); - const fundamentalsPath = joinCuratedPath(curatedRoot, 'fundamentals_pit/year=*/part.parquet'); - const listingPlaceholders = buildPlaceholders(listingIds.length); - - let hasTtmField = false; - for (const field of fields) { - if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) { - hasTtmField = true; - break; - } - } - - const innerCols: string[] = [ - 'f.listing_id', - 'f.effective_known_at', - 'f.known_at_source', - 'f.has_estimated_lag', - 'f.period_end', - 'f.fiscal_period', - 'f.currency', - 'f.period_known_at', - ]; - const outerCols: string[] = [ - 's.listing_id', - 'epoch_ms(s.effective_known_at) AS effective_known_at', - 's.known_at_source', - 's.has_estimated_lag', - 'CAST(s.period_end AS VARCHAR) AS period_end', - 's.fiscal_period', - 's.currency', - 'epoch_ms(s.period_known_at) AS period_known_at', - ]; - const schema: TableColumnSpec[] = [...FUNDAMENTALS_BASE_SCHEMA]; - - for (const field of fields) { - innerCols.push(`f.${field}`); - if (FUNDAMENTALS_TTM_VALUE_FIELD_SET.has(field)) { - outerCols.push( - `CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.${field} ELSE NULL END AS ${field}` - ); - } else { - outerCols.push(`s.${field}`); - } - schema.push({ name: field, kind: 'number', nullable: true }); - } - - if (hasTtmField) { - innerCols.push('f.ttm_period_end', 'f.ttm_currency', 'f.ttm_has_estimated_lag'); - outerCols.push( - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end', - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency', - 's.ttm_has_estimated_lag' - ); - schema.push(...FUNDAMENTALS_TTM_META_SCHEMA); - } - - const columns = schema.map(spec => spec.name); - const sql = - `WITH latest AS (SELECT ${innerCols.join(', ')} ` + - 'FROM read_parquet(?, hive_partitioning = true) AS f ' + - `WHERE f.listing_id IN (${listingPlaceholders}) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ` + - 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + - `SELECT ${outerCols.join(', ')} ` + - 'FROM latest AS s ' + - 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + - 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + - 'ORDER BY s.listing_id ASC'; - const params: DuckDbParam[] = [fundamentalsPath, ...listingIds, asOfIso, allowEstimatedLag]; - - return { - planned: { sql, params, fenced }, - columns, - schema, - }; -} - -/** - * Plans a Vault-fenced point-in-time DuckDB SQL query over curated - * `fundamentals_pit/year=*\/part.parquet` snapshots. - * - * Selects at most one snapshot per requested `listing_id` — the latest with - * `effective_known_at <= asOf` (clamped strictly below `vaultCutoffTs`). When - * `allowEstimatedLag` is `false`, listings whose selected snapshot has - * `has_estimated_lag = true` are omitted without falling back to an older - * snapshot, and requested `ttm_*` value fields plus `ttm_period_end` / - * `ttm_currency` are masked to `NULL` when `ttm_has_estimated_lag` is `true` - * while preserving `ttm_has_estimated_lag`. - */ -export function planFundamentalsAsOfQuery( - q: FundamentalsAsOfQuery, - ctx: DuckDbPlanContext -): PlannedDuckDbQuery { - return planFundamentalsAsOfInternal(q, ctx).planned; -} - function readRequiredInt32(row: Record, key: string, rowIndex: number): number { const val = row[key]; if (typeof val !== 'number' || !Number.isSafeInteger(val) || val < INT32_MIN || val > INT32_MAX) { @@ -1950,14 +1712,6 @@ function readValidatedTableCell( ); } return val; - case 'boolean': - if (typeof val !== 'boolean') { - throw new MarketDataStoreValidationError( - `Expected boolean for column "${spec.name}" in result row ${rowIndex}, got ${typeof val} (${String(val)}).`, - spec.name - ); - } - return val; } } @@ -2284,11 +2038,8 @@ export function createDuckDbMarketDataStore(options: DuckDbMarketDataStoreOption return Promise.reject(new MarketDataStoreNotImplementedError('crossSection')); }, - async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ - const { planned, columns, schema } = planFundamentalsAsOfInternal(q, planCtx); - await ensureBudgetInitialized(); - const rawRows = await typedExecutor.query(planned.sql, planned.params); - return mapTableRows(columns, schema, rawRows); + fundamentalsAsOf(): Promise
{ + return Promise.reject(new MarketDataStoreNotImplementedError('fundamentalsAsOf')); }, macroAsOf(): Promise
{ diff --git a/libs/research/src/market-data-store-questdb.ts b/libs/research/src/market-data-store-questdb.ts deleted file mode 100644 index c6da320c..00000000 --- a/libs/research/src/market-data-store-questdb.ts +++ /dev/null @@ -1,462 +0,0 @@ -/** - * Pure, dependency-free QuestDB `bars_1m` query planner and injected-executor - * intraday reader for `MarketDataStore.bars` (`timeframe: '1m'`, - * `design/DATA-CONTRACTS.md` §3.B & §4). - * - * Browser-safe and dependency-free: zero `node:*` imports, zero `pg` or - * `@stock-bot/questdb` dependency, zero bare `process` access. SQL execution - * is injected via {@link QuestDbQueryExecutor}, which is structurally - * compatible with `QuestDBClient.query(sql, params)`. - * - * Storage and point-in-time semantics: - * - `bars_1m` stores split-unadjusted raw 1-minute OHLCV, nullable `vwap`, - * `listing_id` (`SYMBOL`, canonical positive decimal string), `known_at` - * (`TIMESTAMP`), and designated timestamp `ts` (`TIMESTAMP`, - * `PARTITION BY MONTH`). - * - Only `adjustment: 'raw'` is supported; `'split'` and `'total'` throw - * {@link MarketDataStoreNotImplementedError}. - * - Query bounds are Vault-fenced via {@link applyVaultFence} before SQL - * planning. Every user-supplied value is bound via `$1..$n` placeholders; - * only ordinal placeholder tokens are generated in SQL text. - * - `ts` and `known_at` are projected as `CAST(... AS LONG)` (UTC epoch - * microseconds) and verified in exact microseconds against the fenced bounds - * before converting to epoch milliseconds or yielding any batch. - */ - -import { - type BarBatch, - type BarRecord, - type FencedTimeRange, - type MarketDataStore, - MarketDataStoreValidationError, - type VaultFenceContext, - applyVaultFence, -} from './market-data-store'; -import { MarketDataStoreNotImplementedError } from './market-data-store-duckdb'; - -const INT32_MAX = 2_147_483_647; -const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; -const CANONICAL_POSITIVE_INT_RE = /^[1-9]\d*$/; -const CANONICAL_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/; - -/** Default maximum number of `BarRecord` rows yielded per `BarBatch`. */ -export const DEFAULT_QUESTDB_BARS_BATCH_SIZE = 50_000; - -/** Input query type derived from `MarketDataStore['bars']`. */ -export type QuestDbBars1mQuery = Parameters[0]; - -/** - * Injected PGWire SQL executor port, structurally compatible with - * `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`. - */ -export interface QuestDbQueryExecutor { - query( - sql: string, - params: readonly unknown[] - ): Promise<{ readonly rows: readonly Record[] }>; -} - -/** Pure output of {@link planBars1mQuery}. */ -export interface PlannedQuestDbBars1mQuery { - readonly sql: string; - readonly params: readonly string[]; - readonly fence: FencedTimeRange; -} - -/** Configuration for {@link createQuestDbIntradayBarsReader}. */ -export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext { - readonly executor: QuestDbQueryExecutor; - /** Maximum number of bars per yielded `BarBatch`. Defaults to `50_000`. */ - readonly batchSize?: number; -} - -interface InternalPlannedBars1mQuery { - readonly planned: PlannedQuestDbBars1mQuery; - readonly requestedListingIds: ReadonlySet; -} - -function isPlainRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function validateVaultCutoffTs(vaultCutoffTs: unknown): number { - if ( - typeof vaultCutoffTs !== 'number' || - !Number.isSafeInteger(vaultCutoffTs) || - Math.abs(vaultCutoffTs) > MAX_ECMASCRIPT_EPOCH_MS || - vaultCutoffTs <= -MAX_ECMASCRIPT_EPOCH_MS - ) { - throw new MarketDataStoreValidationError( - `Invalid epoch millisecond timestamp for "vaultCutoffTs": ${String(vaultCutoffTs)}.`, - 'vaultCutoffTs' - ); - } - return vaultCutoffTs === 0 ? 0 : vaultCutoffTs; -} - -function validatePositiveInt32ListingIds(raw: unknown): number[] { - if (!Array.isArray(raw) || raw.length === 0) { - throw new MarketDataStoreValidationError( - 'Expected a non-empty array of positive INT32 listing IDs for "listingIds".', - 'listingIds' - ); - } - - const seen = new Set(); - const normalized: number[] = []; - for (let i = 0; i < raw.length; i += 1) { - const id: unknown = raw[i]; - if ( - typeof id !== 'number' || - !Number.isSafeInteger(id) || - id < 1 || - id > INT32_MAX - ) { - throw new MarketDataStoreValidationError( - `Invalid positive INT32 listing ID at listingIds[${i}]: ${String(id)}.`, - 'listingIds' - ); - } - if (!seen.has(id)) { - seen.add(id); - normalized.push(id); - } - } - - normalized.sort((a, b) => a - b); - return normalized; -} - -function formatUtcIsoMs(epochMs: number): string { - return new Date(epochMs).toISOString(); -} - -function planBars1mQueryInternal( - q: QuestDbBars1mQuery, - ctx: VaultFenceContext -): InternalPlannedBars1mQuery { - if (!isPlainRecord(ctx)) { - throw new MarketDataStoreValidationError('Expected a VaultFenceContext object.', 'ctx'); - } - if (!isPlainRecord(q)) { - throw new MarketDataStoreValidationError('Expected a bars query object.', 'query'); - } - - const timeframe: unknown = q.timeframe; - if (timeframe !== '1m') { - throw new MarketDataStoreValidationError( - `Invalid bars timeframe "${String(timeframe)}". Expected '1m'.`, - 'timeframe' - ); - } - - const adjustment: unknown = q.adjustment; - if (adjustment === 'split' || adjustment === 'total') { - throw new MarketDataStoreNotImplementedError( - 'bars', - `Adjustment '${adjustment}' is not supported for intraday '1m' bars; bars_1m stores raw split-unadjusted values.` - ); - } - if (adjustment !== 'raw') { - throw new MarketDataStoreValidationError( - `Invalid bars adjustment "${String(adjustment)}". Expected 'raw'.`, - 'adjustment' - ); - } - - const sortedListingIds = validatePositiveInt32ListingIds(q.listingIds); - - const fence = applyVaultFence( - { - from: q.from, - to: q.to, - asOf: q.asOf, - scope: q.scope, - }, - { - vaultCutoffTs: ctx.vaultCutoffTs, - vaultOperatorAuthorized: ctx.vaultOperatorAuthorized === true, - } - ); - - const listingPlaceholders = sortedListingIds.map((_, index) => `$${index + 3}`).join(', '); - const asOfPlaceholder = `$${sortedListingIds.length + 3}`; - - const sql = - 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + - 'FROM bars_1m ' + - `WHERE ts >= $1 AND ts <= $2 AND listing_id IN (${listingPlaceholders}) AND known_at <= ${asOfPlaceholder} ` + - 'ORDER BY ts, listing_id'; - - const params: string[] = [ - formatUtcIsoMs(fence.fromMs), - formatUtcIsoMs(fence.toMs), - ...sortedListingIds.map(id => String(id)), - formatUtcIsoMs(fence.asOfMs), - ]; - - return { - planned: { sql, params, fence }, - requestedListingIds: new Set(sortedListingIds), - }; -} - -/** - * Pure, Vault-fenced, parameterized SQL planner for QuestDB `bars_1m`. - * - * Binds `from`, `to`, and `asOf` as exact millisecond UTC ISO-8601 strings and - * deduplicated, numerically sorted positive INT32 `listingIds` as canonical - * decimal `SYMBOL` strings. - */ -export function planBars1mQuery( - q: QuestDbBars1mQuery, - ctx: VaultFenceContext -): PlannedQuestDbBars1mQuery { - return planBars1mQueryInternal(q, ctx).planned; -} - -function parseListingIdSymbol( - row: Record, - rowIndex: number, - requestedListingIds: ReadonlySet -): number { - const raw = row.listing_id; - if (typeof raw !== 'string' || !CANONICAL_POSITIVE_INT_RE.test(raw)) { - throw new MarketDataStoreValidationError( - `Invalid bars_1m listing_id SYMBOL in result row ${rowIndex}: ${String(raw)}.`, - 'listing_id' - ); - } - const parsed = Number(raw); - if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > INT32_MAX) { - throw new MarketDataStoreValidationError( - `Out-of-range bars_1m listing_id SYMBOL in result row ${rowIndex}: "${raw}".`, - 'listing_id' - ); - } - if (!requestedListingIds.has(parsed)) { - throw new MarketDataStoreValidationError( - `Unexpected unrequested listing_id ${parsed} in bars_1m result row ${rowIndex}.`, - 'listing_id' - ); - } - return parsed; -} - -function parseTimestampMicros( - row: Record, - column: 'ts_us' | 'known_at_us', - field: 'ts' | 'known_at', - rowIndex: number -): bigint { - const raw = row[column]; - if (typeof raw === 'bigint') { - return raw; - } - if (typeof raw === 'string' && CANONICAL_SIGNED_INT_RE.test(raw)) { - return BigInt(raw); - } - if (typeof raw === 'number' && Number.isSafeInteger(raw)) { - return BigInt(raw); - } - throw new MarketDataStoreValidationError( - `Invalid bars_1m timestamp column "${column}" in result row ${rowIndex}: ${String(raw)}.`, - field - ); -} - -function microsToEpochMs( - us: bigint, - field: 'ts' | 'known_at', - rowIndex: number, - rounding: 'floor' | 'ceil' -): number { - const quotient = us / 1000n; - const remainder = us % 1000n; - const msBigInt = - rounding === 'ceil' - ? remainder > 0n - ? quotient + 1n - : quotient - : remainder < 0n - ? quotient - 1n - : quotient; - const ms = Number(msBigInt); - if (!Number.isSafeInteger(ms) || Math.abs(ms) > MAX_ECMASCRIPT_EPOCH_MS) { - throw new MarketDataStoreValidationError( - `Out-of-range bars_1m timestamp "${field}" (${us.toString()} us) in result row ${rowIndex}.`, - field - ); - } - return ms === 0 ? 0 : ms; -} - -function readRequiredFiniteNumber( - row: Record, - key: 'open' | 'high' | 'low' | 'close' | 'volume', - rowIndex: number -): number { - const val = row[key]; - if (typeof val !== 'number' || !Number.isFinite(val)) { - throw new MarketDataStoreValidationError( - `Invalid numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`, - key - ); - } - return val === 0 ? 0 : val; -} - -function readNullableFiniteNumber( - row: Record, - key: 'vwap', - rowIndex: number -): number | null { - const val = row[key]; - if (val === null || val === undefined) { - return null; - } - if (typeof val !== 'number' || !Number.isFinite(val)) { - throw new MarketDataStoreValidationError( - `Invalid nullable numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`, - key - ); - } - return val === 0 ? 0 : val; -} - -function mapBars1mRows( - rows: readonly Record[], - fence: FencedTimeRange, - requestedListingIds: ReadonlySet -): BarRecord[] { - const fromUs = BigInt(fence.fromMs) * 1000n; - const toUs = BigInt(fence.toMs) * 1000n; - const asOfUs = BigInt(fence.asOfMs) * 1000n; - - const out: BarRecord[] = new Array(rows.length); - for (let i = 0; i < rows.length; i += 1) { - const raw = rows[i]; - if (!isPlainRecord(raw)) { - throw new MarketDataStoreValidationError( - `Executor returned a non-object bar row at index ${i}.`, - 'rows' - ); - } - - const listingId = parseListingIdSymbol(raw, i, requestedListingIds); - const tsUs = parseTimestampMicros(raw, 'ts_us', 'ts', i); - if (tsUs < fromUs || tsUs > toUs) { - throw new MarketDataStoreValidationError( - `Row ${i} timestamp ts (${tsUs.toString()} us) is outside fenced range [${fromUs.toString()}, ${toUs.toString()}] us.`, - 'ts' - ); - } - - const knownAtUs = parseTimestampMicros(raw, 'known_at_us', 'known_at', i); - if (knownAtUs > asOfUs) { - throw new MarketDataStoreValidationError( - `Row ${i} availability timestamp known_at (${knownAtUs.toString()} us) exceeds fenced asOf (${asOfUs.toString()} us).`, - 'known_at' - ); - } - - out[i] = { - listingId, - ts: microsToEpochMs(tsUs, 'ts', i, 'floor'), - open: readRequiredFiniteNumber(raw, 'open', i), - high: readRequiredFiniteNumber(raw, 'high', i), - low: readRequiredFiniteNumber(raw, 'low', i), - close: readRequiredFiniteNumber(raw, 'close', i), - volume: readRequiredFiniteNumber(raw, 'volume', i), - vwap: readNullableFiniteNumber(raw, 'vwap', i), - // Round sub-millisecond availability up so replay never treats a bar as known before arrival. - knownAt: microsToEpochMs(knownAtUs, 'known_at', i, 'ceil'), - }; - } - - return out; -} - -/** - * Creates a read-only intraday `bars` reader backed by an injected - * {@link QuestDbQueryExecutor} over QuestDB `bars_1m`. - * - * Validates all inputs and applies the Vault fence before invoking - * `executor.query(...)`. Validates and maps all returned rows (including - * exact-microsecond defence-in-depth checks against `fence`) before yielding - * batches of at most `batchSize` rows (default `50_000`). - */ -export function createQuestDbIntradayBarsReader( - options: QuestDbIntradayBarsReaderOptions -): Pick { - if (!isPlainRecord(options)) { - throw new MarketDataStoreValidationError( - 'Expected a QuestDbIntradayBarsReaderOptions object.', - 'options' - ); - } - - const executor: unknown = options.executor; - if (!isPlainRecord(executor) || typeof executor.query !== 'function') { - throw new MarketDataStoreValidationError( - 'Expected `executor` with a `query(sql, params)` method.', - 'executor' - ); - } - const typedExecutor = executor as unknown as QuestDbQueryExecutor; - - const vaultCutoffTs = validateVaultCutoffTs(options.vaultCutoffTs); - - if ( - options.vaultOperatorAuthorized !== undefined && - typeof options.vaultOperatorAuthorized !== 'boolean' - ) { - throw new MarketDataStoreValidationError( - `Invalid vaultOperatorAuthorized "${String(options.vaultOperatorAuthorized)}". Expected a boolean.`, - 'vaultOperatorAuthorized' - ); - } - - const batchSize = - options.batchSize === undefined ? DEFAULT_QUESTDB_BARS_BATCH_SIZE : options.batchSize; - if (typeof batchSize !== 'number' || !Number.isSafeInteger(batchSize) || batchSize < 1) { - throw new MarketDataStoreValidationError( - `Invalid batchSize "${String(options.batchSize)}". Expected a positive safe integer.`, - 'batchSize' - ); - } - - const planCtx: VaultFenceContext = { - vaultCutoffTs, - vaultOperatorAuthorized: options.vaultOperatorAuthorized === true, - }; - - return { - async *bars(q: QuestDbBars1mQuery): AsyncIterable { - const { planned, requestedListingIds } = planBars1mQueryInternal(q, planCtx); - const result: unknown = await typedExecutor.query(planned.sql, [...planned.params]); - if (!isPlainRecord(result) || !Array.isArray(result.rows)) { - throw new MarketDataStoreValidationError( - 'Executor returned a malformed result; expected `{ rows: Record[] }`.', - 'rows' - ); - } - - const mapped = mapBars1mRows( - result.rows as readonly Record[], - planned.fence, - requestedListingIds - ); - if (mapped.length === 0) { - return; - } - if (mapped.length <= batchSize) { - yield { rows: mapped }; - return; - } - for (let offset = 0; offset < mapped.length; offset += batchSize) { - yield { rows: mapped.slice(offset, offset + batchSize) }; - } - }, - }; -} diff --git a/libs/research/src/market-data-store-routed.ts b/libs/research/src/market-data-store-routed.ts deleted file mode 100644 index a7b52608..00000000 --- a/libs/research/src/market-data-store-routed.ts +++ /dev/null @@ -1,192 +0,0 @@ -/** - * Pure, dependency-free `MarketDataStore` router that dispatches intraday - * `bars` queries (`timeframe: '1m'`) to an injected intraday reader (such as - * {@link createQuestDbIntradayBarsReader}) and routes every other `bars` - * timeframe and all other `MarketDataStore` methods to the injected daily - * store (such as {@link createDuckDbMarketDataStore}). - * - * Browser-safe and dependency-free: zero `node:*` imports, zero bare `process` - * access, and no database or filesystem I/O. - * - * Vault & point-in-time semantics: - * - This router adds no Vault logic of its own; each delegate continues to - * enforce its own Vault holdout fence and point-in-time predicates. - * - Callers MUST construct both `daily` and `intraday` with the exact same - * `vaultCutoffTs` and `vaultOperatorAuthorized` values (and pass the same - * `vaultCutoffTs` to MCP tools such as `createQueryDataTool`, which is - * always Vault-fenced) so the holdout boundary is identical across - * timeframes. - * - The QuestDB intraday reader (`createQuestDbIntradayBarsReader`) supports - * split-unadjusted `adjustment: 'raw'` `1m` bars; non-`'raw'` `1m` requests - * and unsupported timeframes (`'5m'`, `'1h'`) are handled by the respective - * delegate without modification. - */ - -import { type MarketDataStore, MarketDataStoreValidationError } from './market-data-store'; - -/** Configuration for {@link createRoutedMarketDataStore}. */ -export interface RoutedMarketDataStoreOptions { - /** Backing store for daily (`'1d'`) and non-`'1m'` bars plus all other `MarketDataStore` methods. */ - readonly daily: MarketDataStore; - /** Backing intraday reader for `bars` queries with `timeframe: '1m'`. */ - readonly intraday: Pick; -} - -const REQUIRED_DAILY_METHODS = [ - 'bars', - 'crossSection', - 'fundamentalsAsOf', - 'events', - 'shortsAsOf', - 'macroAsOf', - 'fx', - 'universe', -] as const satisfies readonly (keyof MarketDataStore)[]; - -function isPlainObject(value: unknown): value is Record { - if (typeof value !== 'object' || value === null) { - return false; - } - const proto: unknown = Object.getPrototypeOf(value); - return proto === Object.prototype || proto === null; -} - -function isDelegateObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function isIntraday1mBarsQuery(q: unknown): boolean { - return ( - typeof q === 'object' && - q !== null && - !Array.isArray(q) && - (q as { readonly timeframe?: unknown }).timeframe === '1m' - ); -} - -/** - * Composes a daily `MarketDataStore` and an intraday `bars` reader into a - * single read-only `MarketDataStore`. - * - * Routing rules: - * - `bars(q)` with `q.timeframe === '1m'` delegates directly to - * `options.intraday.bars(q)` and returns its `AsyncIterable` - * unchanged (preserving receiver, query identity, lazy iteration, and error - * timing). - * - `bars(q)` with any other timeframe (`'1d'`, `'5m'`, `'1h'`, or malformed - * runtime inputs) delegates directly to `options.daily.bars(q)`. - * - All other `MarketDataStore` methods (`crossSection`, `fundamentalsAsOf`, - * `events`, `shortsAsOf`, `macroAsOf`, `fx`, `universe`) delegate directly - * to `options.daily` and return its original promise. - * - * Vault fence note: - * Both `daily` and `intraday` MUST be constructed with the exact same - * `vaultCutoffTs` and `vaultOperatorAuthorized` settings. The QuestDB intraday - * reader serves raw (`adjustment: 'raw'`) `1m` bars. - * - * @example - * ```ts - * const vaultCutoffTs = Date.UTC(2025, 6, 1, 0, 0, 0, 0); - * const vaultOperatorAuthorized = false; - * - * const daily = createDuckDbMarketDataStore({ - * executor: duckDbExecutor, - * curatedRoot: '/mnt/data/stockbot/curated', - * vaultCutoffTs, - * vaultOperatorAuthorized, - * }); - * const intraday = createQuestDbIntradayBarsReader({ - * executor: questDbExecutor, - * vaultCutoffTs, - * vaultOperatorAuthorized, - * }); - * const store = createRoutedMarketDataStore({ daily, intraday }); - * // `createQueryDataTool` is always Vault-fenced and accepts only `vaultCutoffTs`. - * const queryDataTool = createQueryDataTool({ - * store, - * vaultContext: { vaultCutoffTs }, - * }); - * ``` - */ -export function createRoutedMarketDataStore( - options: RoutedMarketDataStoreOptions -): MarketDataStore { - if (!isPlainObject(options)) { - throw new MarketDataStoreValidationError( - 'Expected a plain RoutedMarketDataStoreOptions object.', - 'options' - ); - } - - const rawDaily: unknown = options.daily; - if (!isDelegateObject(rawDaily)) { - throw new MarketDataStoreValidationError( - 'Expected `daily` to be a MarketDataStore object.', - 'daily' - ); - } - - for (const method of REQUIRED_DAILY_METHODS) { - if (typeof rawDaily[method] !== 'function') { - throw new MarketDataStoreValidationError( - `Expected \`daily.${method}\` to be a function.`, - `daily.${method}` - ); - } - } - - const rawIntraday: unknown = options.intraday; - if (!isDelegateObject(rawIntraday)) { - throw new MarketDataStoreValidationError( - 'Expected `intraday` to be an object with a `bars` method.', - 'intraday' - ); - } - - if (typeof rawIntraday.bars !== 'function') { - throw new MarketDataStoreValidationError( - 'Expected `intraday.bars` to be a function.', - 'intraday.bars' - ); - } - - const daily = options.daily; - const intraday = options.intraday; - - return { - bars(q) { - if (isIntraday1mBarsQuery(q)) { - return intraday.bars(q); - } - return daily.bars(q); - }, - - crossSection(q) { - return daily.crossSection(q); - }, - - fundamentalsAsOf(q) { - return daily.fundamentalsAsOf(q); - }, - - events(q) { - return daily.events(q); - }, - - shortsAsOf(q) { - return daily.shortsAsOf(q); - }, - - macroAsOf(q) { - return daily.macroAsOf(q); - }, - - fx(q) { - return daily.fx(q); - }, - - universe(q) { - return daily.universe(q); - }, - }; -} diff --git a/libs/research/src/mcp/copilot-server.ts b/libs/research/src/mcp/copilot-server.ts deleted file mode 100644 index 98b412ee..00000000 --- a/libs/research/src/mcp/copilot-server.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { type McpServer, type McpServerOptions, createMcpServer } from './server'; -import { type AnalyzeSignalToolOptions, createAnalyzeSignalTool } from './tools/analyze-signal'; -import { type EventStudyToolOptions, createEventStudyTool } from './tools/event-study'; -import { type FileFindingToolOptions, createFileFindingTool } from './tools/file-finding'; -import { type QueryDataToolOptions, createQueryDataTool } from './tools/query-data'; -import { type ReadKnowledgeToolOptions, createReadKnowledgeTool } from './tools/read-knowledge'; -import { type SearchSymbolsToolOptions, createSearchSymbolsTool } from './tools/search-symbols'; - -/** - * Fixed, documented registration order of the six MCP tools exposed by - * {@link createResearchCopilotMcpServer}. - */ -export const RESEARCH_COPILOT_TOOL_NAMES = Object.freeze([ - 'search_symbols', - 'query_data', - 'analyze_signal', - 'event_study', - 'file_finding', - 'read_knowledge', -] as const); - -/** - * Composed server options for {@link createResearchCopilotMcpServer}. - * - * Shares the common Vault-fenced `MarketDataStore`, `vaultContext`, - * `TrialLedgerExecutor`, and `principalId` across the tools that consume them - * while passing each tool's remaining injected ports unchanged. - */ -export interface ResearchCopilotMcpServerOptions - extends Pick, - Pick, - Pick { - readonly searchSymbols: Omit; - readonly eventStudy: Pick; - readonly fileFinding: FileFindingToolOptions; - readonly readKnowledge: ReadKnowledgeToolOptions; -} - -/** - * Composes all six research MCP tools (`search_symbols`, `query_data`, - * `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`) into a - * single transport-agnostic {@link McpServer}. - * - * Keeps the shared `store`, `vaultContext`, `ledger`, and `principalId` - * authoritative across tools and fails closed if any tool is duplicated, - * missing, unexpected, or out of order. - */ -export function createResearchCopilotMcpServer( - options: ResearchCopilotMcpServerOptions -): McpServer { - if (typeof options !== 'object' || options === null) { - throw new Error('Invalid `options`: expected a ResearchCopilotMcpServerOptions object.'); - } - if (typeof options.searchSymbols !== 'object' || options.searchSymbols === null) { - throw new Error('Invalid `searchSymbols`: expected a SearchSymbolsToolOptions object.'); - } - if (typeof options.eventStudy !== 'object' || options.eventStudy === null) { - throw new Error('Invalid `eventStudy`: expected an EventStudyToolOptions object.'); - } - - const tools = [ - createSearchSymbolsTool({ - ...options.searchSymbols, - vaultContext: options.vaultContext, - }), - createQueryDataTool({ - store: options.store, - vaultContext: options.vaultContext, - }), - createAnalyzeSignalTool({ - store: options.store, - ledger: options.ledger, - vaultContext: options.vaultContext, - principalId: options.principalId, - }), - createEventStudyTool({ - store: options.store, - ledger: options.ledger, - vaultContext: options.vaultContext, - principalId: options.principalId, - resolveExchangeCalendars: options.eventStudy.resolveExchangeCalendars, - }), - createFileFindingTool(options.fileFinding), - createReadKnowledgeTool(options.readKnowledge), - ]; - - const server = createMcpServer({ - name: options.name, - version: options.version, - tools, - }); - - const registered = server.listTools(); - if (registered.length !== RESEARCH_COPILOT_TOOL_NAMES.length) { - throw new Error( - `Research copilot MCP server expected ${RESEARCH_COPILOT_TOOL_NAMES.length} tools, got ${registered.length}.` - ); - } - for (let i = 0; i < RESEARCH_COPILOT_TOOL_NAMES.length; i += 1) { - const expectedName = RESEARCH_COPILOT_TOOL_NAMES[i]; - const actualName = registered[i]?.name; - if (actualName !== expectedName) { - throw new Error( - `Research copilot MCP server tool mismatch at index ${i}: expected "${expectedName}", got "${String(actualName)}".` - ); - } - } - - return server; -} diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts deleted file mode 100644 index 3ab56692..00000000 --- a/libs/research/src/mcp/index.ts +++ /dev/null @@ -1,10 +0,0 @@ -export * from './copilot-server'; -export * from './protocol'; -export * from './server'; -export * from './stdio'; -export * from './tools/analyze-signal'; -export * from './tools/event-study'; -export * from './tools/file-finding'; -export * from './tools/query-data'; -export * from './tools/read-knowledge'; -export * from './tools/search-symbols'; diff --git a/libs/research/src/mcp/protocol.ts b/libs/research/src/mcp/protocol.ts deleted file mode 100644 index fe7efcd6..00000000 --- a/libs/research/src/mcp/protocol.ts +++ /dev/null @@ -1,274 +0,0 @@ -import { z } from 'zod'; - -/** Supported Model Context Protocol revision. */ -export const MCP_PROTOCOL_VERSION = '2025-03-26'; - -/** Standard JSON-RPC 2.0 error codes. */ -export const JSON_RPC_ERROR_CODES = { - PARSE_ERROR: -32700, - INVALID_REQUEST: -32600, - METHOD_NOT_FOUND: -32601, - INVALID_PARAMS: -32602, - INTERNAL_ERROR: -32603, -} as const; - -export type JsonRpcErrorCode = (typeof JSON_RPC_ERROR_CODES)[keyof typeof JSON_RPC_ERROR_CODES]; - -/** Valid JSON-RPC 2.0 request identifier (string or finite number). */ -export const jsonRpcIdSchema = z.union([z.string(), z.number().finite()]); -export type JsonRpcId = z.infer; - -/** Strict JSON-RPC 2.0 request envelope (must carry a valid `id`). */ -export const jsonRpcRequestSchema = z - .object({ - jsonrpc: z.literal('2.0'), - id: jsonRpcIdSchema, - method: z.string().min(1), - params: z.unknown().optional(), - }) - .strict(); - -export type JsonRpcRequest = z.infer; - -/** Strict JSON-RPC 2.0 notification envelope (must NOT carry an `id`). */ -export const jsonRpcNotificationSchema = z - .object({ - jsonrpc: z.literal('2.0'), - method: z.string().min(1), - params: z.unknown().optional(), - }) - .strict(); - -export type JsonRpcNotification = z.infer; - -export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification; - -export interface JsonRpcSuccessResponse { - readonly jsonrpc: '2.0'; - readonly id: JsonRpcId; - readonly result: unknown; -} - -export interface JsonRpcErrorObject { - readonly code: number; - readonly message: string; - readonly data?: unknown; -} - -export interface JsonRpcErrorResponse { - readonly jsonrpc: '2.0'; - readonly id: JsonRpcId | null; - readonly error: JsonRpcErrorObject; -} - -export type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse; - -/** MCP text content block returned inside `tools/call` results. */ -export interface McpTextContent { - readonly type: 'text'; - readonly text: string; -} - -/** MCP `tools/call` result envelope. */ -export interface McpToolCallResult { - readonly content: readonly McpTextContent[]; - readonly isError?: boolean; -} - -/** Minimal JSON Schema Draft 7/2020-12 property definition for MCP tool inputs. */ -export interface JsonSchemaProperty { - readonly type?: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object' | 'null'; - readonly description?: string; - readonly enum?: readonly (string | number | boolean | null)[]; - readonly const?: string | number | boolean | null; - readonly minimum?: number; - readonly maximum?: number; - readonly exclusiveMinimum?: number; - readonly exclusiveMaximum?: number; - readonly minLength?: number; - readonly maxLength?: number; - readonly minItems?: number; - readonly maxItems?: number; - readonly items?: JsonSchemaProperty; - readonly properties?: Readonly>; - readonly required?: readonly string[]; - readonly additionalProperties?: boolean; - readonly anyOf?: readonly JsonSchemaProperty[]; - readonly default?: unknown; -} - -/** Strict top-level JSON Schema object emitted by `tools/list`. */ -export interface JsonSchemaObject { - readonly type: 'object'; - readonly properties: Readonly>; - readonly required?: readonly string[]; - readonly additionalProperties: false; - readonly description?: string; -} - -/** Tool metadata returned in `tools/list`. */ -export interface McpToolDescriptor { - readonly name: string; - readonly description: string; - readonly inputSchema: JsonSchemaObject; -} - -/** Valid MCP progress token (`string | finite number`). */ -export const mcpProgressTokenSchema = z.union([z.string(), z.number().finite()]); -export type McpProgressToken = z.infer; - -/** Standard optional MCP `_meta` request/notification metadata bag. */ -export const mcpRequestMetaSchema = z - .object({ - progressToken: mcpProgressTokenSchema.optional(), - }) - .passthrough(); -export type McpRequestMeta = z.infer; - -const jsonObjectSchema = z.custom>( - (value): value is Record => - typeof value === 'object' && value !== null && !Array.isArray(value), - { message: 'Expected a JSON object.' } -); - -/** Strict MCP `initialize` params schema. */ -export const mcpInitializeParamsSchema = z - .object({ - 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, - }; -} diff --git a/libs/research/src/mcp/server.ts b/libs/research/src/mcp/server.ts deleted file mode 100644 index dec43185..00000000 --- a/libs/research/src/mcp/server.ts +++ /dev/null @@ -1,536 +0,0 @@ -import { z } from 'zod'; -import { - JSON_RPC_ERROR_CODES, - type JsonSchemaObject, - type JsonSchemaProperty, - MCP_PROTOCOL_VERSION, - type McpToolCallResult, - type McpToolDescriptor, - jsonRpcError, - jsonRpcSuccess, - mcpInitializeParamsSchema, - mcpPingParamsSchema, - mcpToolsCallParamsSchema, - mcpToolsListParamsSchema, - parseJsonRpcMessage, -} from './protocol'; - -/** Configuration for defining a strongly typed MCP tool. */ -export interface McpToolDefinition { - readonly name: string; - readonly description: string; - readonly inputSchema: z.ZodType; - readonly jsonSchema?: JsonSchemaObject; - readonly handler: (input: TInput) => Promise | McpToolCallResult; -} - -/** Type-erased tool entry registered on an {@link McpServer}. */ -export interface McpToolEntry { - readonly name: string; - readonly description: string; - readonly inputSchema: JsonSchemaObject; - readonly execute: (rawArguments: Record) => Promise; -} - -/** Options for {@link createMcpServer}. */ -export interface McpServerOptions { - readonly name: string; - readonly version: string; - readonly tools?: readonly McpToolEntry[]; -} - -/** Transport-agnostic MCP JSON-RPC 2.0 server interface. */ -export interface McpServer { - readonly name: string; - readonly version: string; - listTools(): readonly McpToolDescriptor[]; - handleMessage(raw: string): Promise; -} - -function isOptionalSchema(schema: z.ZodTypeAny): boolean { - if (schema instanceof z.ZodOptional || schema instanceof z.ZodDefault) { - return true; - } - if (schema instanceof z.ZodEffects) { - return isOptionalSchema(schema._def.schema); - } - return false; -} - -function withDescription( - prop: JsonSchemaProperty, - description: string | undefined -): JsonSchemaProperty { - if (description !== undefined && prop.description === undefined) { - return { ...prop, description }; - } - return prop; -} - -function convertZodType(schema: z.ZodTypeAny): JsonSchemaProperty { - const outerDescription = schema.description; - - if (schema instanceof z.ZodEffects) { - return withDescription(convertZodType(schema._def.schema), outerDescription); - } - - if (schema instanceof z.ZodOptional) { - return withDescription(convertZodType(schema.unwrap()), outerDescription); - } - - if (schema instanceof z.ZodDefault) { - const inner = convertZodType(schema._def.innerType); - const defaultValue: unknown = schema._def.defaultValue(); - return withDescription({ ...inner, default: defaultValue }, outerDescription); - } - - if (schema instanceof z.ZodNullable) { - const inner = convertZodType(schema.unwrap()); - return withDescription({ anyOf: [inner, { type: 'null' }] }, outerDescription); - } - - if (schema instanceof z.ZodString) { - let minLength: number | undefined; - let maxLength: number | undefined; - for (const check of schema._def.checks) { - if (check.kind === 'min') { - minLength = check.value; - } else if (check.kind === 'max') { - maxLength = check.value; - } else if (check.kind === 'length') { - minLength = check.value; - maxLength = check.value; - } - } - const result: { - type: 'string'; - description?: string; - minLength?: number; - maxLength?: number; - } = { type: 'string' }; - if (outerDescription !== undefined) { - result.description = outerDescription; - } - if (minLength !== undefined) { - result.minLength = minLength; - } - if (maxLength !== undefined) { - result.maxLength = maxLength; - } - return result; - } - - if (schema instanceof z.ZodNumber) { - let isInt = false; - let minimum: number | undefined; - let maximum: number | undefined; - let exclusiveMinimum: number | undefined; - let exclusiveMaximum: number | undefined; - for (const check of schema._def.checks) { - if (check.kind === 'int') { - isInt = true; - } else if (check.kind === 'min') { - if (check.inclusive) { - minimum = check.value; - } else { - exclusiveMinimum = check.value; - } - } else if (check.kind === 'max') { - if (check.inclusive) { - maximum = check.value; - } else { - exclusiveMaximum = check.value; - } - } - } - const result: { - type: 'integer' | 'number'; - description?: string; - minimum?: number; - maximum?: number; - exclusiveMinimum?: number; - exclusiveMaximum?: number; - } = { type: isInt ? 'integer' : 'number' }; - if (outerDescription !== undefined) { - result.description = outerDescription; - } - if (minimum !== undefined) { - result.minimum = minimum; - } - if (maximum !== undefined) { - result.maximum = maximum; - } - if (exclusiveMinimum !== undefined) { - result.exclusiveMinimum = exclusiveMinimum; - } - if (exclusiveMaximum !== undefined) { - result.exclusiveMaximum = exclusiveMaximum; - } - return result; - } - - if (schema instanceof z.ZodBoolean) { - return outerDescription !== undefined - ? { type: 'boolean', description: outerDescription } - : { type: 'boolean' }; - } - - if (schema instanceof z.ZodEnum) { - const values = [...schema._def.values] as readonly string[]; - return outerDescription !== undefined - ? { type: 'string', enum: values, description: outerDescription } - : { type: 'string', enum: values }; - } - - if (schema instanceof z.ZodLiteral) { - const literalValue: unknown = schema._def.value; - if ( - typeof literalValue === 'string' || - typeof literalValue === 'number' || - typeof literalValue === 'boolean' || - literalValue === null - ) { - const literalType: JsonSchemaProperty['type'] = - literalValue === null - ? 'null' - : typeof literalValue === 'string' - ? 'string' - : typeof literalValue === 'number' - ? 'number' - : 'boolean'; - return outerDescription !== undefined - ? { type: literalType, const: literalValue, description: outerDescription } - : { type: literalType, const: literalValue }; - } - throw new Error('Unsupported ZodLiteral value type in MCP tool input schema.'); - } - - if (schema instanceof z.ZodArray) { - const items = convertZodType(schema._def.type); - const result: { - type: 'array'; - items: JsonSchemaProperty; - description?: string; - minItems?: number; - maxItems?: number; - } = { type: 'array', items }; - if (outerDescription !== undefined) { - result.description = outerDescription; - } - if (schema._def.minLength !== null) { - result.minItems = schema._def.minLength.value; - } - if (schema._def.maxLength !== null) { - result.maxItems = schema._def.maxLength.value; - } - if (schema._def.exactLength !== null) { - result.minItems = schema._def.exactLength.value; - result.maxItems = schema._def.exactLength.value; - } - return result; - } - - if (schema instanceof z.ZodUnion) { - const options = (schema._def.options as readonly z.ZodTypeAny[]).map(option => - convertZodType(option) - ); - return outerDescription !== undefined - ? { anyOf: options, description: outerDescription } - : { anyOf: options }; - } - - if (schema instanceof z.ZodObject) { - return convertZodObject(schema, outerDescription); - } - - const typeName = - typeof (schema._def as { typeName?: unknown }).typeName === 'string' - ? (schema._def as { typeName: string }).typeName - : 'unknown'; - throw new Error(`Unsupported Zod schema type "${typeName}" in MCP tool input schema.`); -} - -function convertZodObject( - schema: z.ZodObject, - outerDescription: string | undefined -): JsonSchemaObject { - const shape = schema.shape; - const properties: Record = {}; - const required: string[] = []; - - for (const [key, fieldSchema] of Object.entries(shape)) { - properties[key] = convertZodType(fieldSchema); - if (!isOptionalSchema(fieldSchema)) { - required.push(key); - } - } - - const description = outerDescription ?? schema.description; - const result: { - type: 'object'; - properties: Record; - required?: string[]; - additionalProperties: false; - description?: string; - } = { - type: 'object', - properties, - additionalProperties: false, - }; - - if (required.length > 0) { - result.required = required; - } - if (description !== undefined) { - result.description = description; - } - return result; -} - -/** - * Converts a Zod v3 object schema (including `.refine()` / `.superRefine()` - * `ZodEffects` wrappers) into a strict {@link JsonSchemaObject}. - * - * Fails fast on unsupported Zod schema types so misconfigured tools are caught - * at registration time rather than at `tools/list` time. - */ -export function zodObjectToJsonSchema(schema: z.ZodTypeAny): JsonSchemaObject { - let current: z.ZodTypeAny = schema; - let description = schema.description; - - while (current instanceof z.ZodEffects) { - current = current._def.schema; - if (description === undefined && current.description !== undefined) { - description = current.description; - } - } - - if (!(current instanceof z.ZodObject)) { - throw new Error('MCP tool inputSchema must be a ZodObject (optionally wrapped in ZodEffects).'); - } - - return convertZodObject(current, description); -} - -function formatZodIssues(error: z.ZodError): string { - const parts = error.issues.map(issue => { - const path = issue.path.length > 0 ? `${issue.path.join('.')}: ` : ''; - return `${path}${issue.message}`; - }); - return parts.join('; '); -} - -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(definition: McpToolDefinition): McpToolEntry { - if (typeof definition.name !== 'string' || definition.name.trim().length === 0) { - throw new Error('MCP tool name must be a non-empty string.'); - } - if (typeof definition.description !== 'string' || definition.description.trim().length === 0) { - throw new Error(`MCP tool "${definition.name}" description must be a non-empty string.`); - } - - const resolvedSchema: JsonSchemaObject = - definition.jsonSchema ?? zodObjectToJsonSchema(definition.inputSchema); - - return { - name: definition.name, - description: definition.description, - inputSchema: resolvedSchema, - async execute(rawArguments: Record): Promise { - const parsed = definition.inputSchema.safeParse(rawArguments); - if (!parsed.success) { - return { - content: [ - { - type: 'text', - text: `Invalid arguments for tool "${definition.name}": ${formatZodIssues(parsed.error)}`, - }, - ], - isError: true, - }; - } - - try { - return await definition.handler(parsed.data); - } catch (err: unknown) { - return { - content: [ - { - type: 'text', - text: sanitizeToolError(err), - }, - ], - isError: true, - }; - } - }, - }; -} - -/** - * Creates a transport-agnostic MCP JSON-RPC 2.0 server with a validated tool - * registry. - */ -export function createMcpServer(options: McpServerOptions): McpServer { - if (typeof options.name !== 'string' || options.name.trim().length === 0) { - throw new Error('MCP server name must be a non-empty string.'); - } - if (typeof options.version !== 'string' || options.version.trim().length === 0) { - throw new Error('MCP server version must be a non-empty string.'); - } - - const toolMap = new Map(); - const toolDescriptors: McpToolDescriptor[] = []; - - for (const tool of options.tools ?? []) { - if (toolMap.has(tool.name)) { - throw new Error(`Duplicate MCP tool name: "${tool.name}".`); - } - toolMap.set(tool.name, tool); - toolDescriptors.push({ - name: tool.name, - description: tool.description, - inputSchema: tool.inputSchema, - }); - } - - const frozenDescriptors: readonly McpToolDescriptor[] = Object.freeze([...toolDescriptors]); - - return { - name: options.name, - version: options.version, - - listTools(): readonly McpToolDescriptor[] { - return frozenDescriptors; - }, - - async handleMessage(raw: string): Promise { - const parsed = parseJsonRpcMessage(raw); - if (!parsed.ok) { - return JSON.stringify(jsonRpcError(null, parsed.errorCode, parsed.message)); - } - - if (parsed.kind === 'notification') { - return null; - } - - const { id, method, params } = parsed.message; - - switch (method) { - case 'initialize': { - if (params !== undefined) { - const initParams = mcpInitializeParamsSchema.safeParse(params); - if (!initParams.success) { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.INVALID_PARAMS, - `Invalid params for initialize: ${formatZodIssues(initParams.error)}` - ) - ); - } - } - return JSON.stringify( - jsonRpcSuccess(id, { - protocolVersion: MCP_PROTOCOL_VERSION, - capabilities: { - tools: {}, - }, - serverInfo: { - name: options.name, - version: options.version, - }, - }) - ); - } - - case 'ping': { - if (params !== undefined) { - const pingParams = mcpPingParamsSchema.safeParse(params); - if (!pingParams.success) { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.INVALID_PARAMS, - `Invalid params for ping: ${formatZodIssues(pingParams.error)}` - ) - ); - } - } - return JSON.stringify(jsonRpcSuccess(id, {})); - } - - case 'tools/list': { - if (params !== undefined) { - const listParams = mcpToolsListParamsSchema.safeParse(params); - if (!listParams.success) { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.INVALID_PARAMS, - `Invalid params for tools/list: ${formatZodIssues(listParams.error)}` - ) - ); - } - } - return JSON.stringify( - jsonRpcSuccess(id, { - tools: frozenDescriptors, - }) - ); - } - - case 'tools/call': { - const callParams = mcpToolsCallParamsSchema.safeParse(params); - if (!callParams.success) { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.INVALID_PARAMS, - `Invalid params for tools/call: ${formatZodIssues(callParams.error)}` - ) - ); - } - - const tool = toolMap.get(callParams.data.name); - if (tool === undefined) { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.INVALID_PARAMS, - `Unknown tool: "${callParams.data.name}".` - ) - ); - } - - const result = await tool.execute(callParams.data.arguments ?? {}); - return JSON.stringify(jsonRpcSuccess(id, result)); - } - - default: { - return JSON.stringify( - jsonRpcError( - id, - JSON_RPC_ERROR_CODES.METHOD_NOT_FOUND, - `Method not found: "${method}".` - ) - ); - } - } - }, - }; -} diff --git a/libs/research/src/mcp/stdio.ts b/libs/research/src/mcp/stdio.ts deleted file mode 100644 index 580c3b6e..00000000 --- a/libs/research/src/mcp/stdio.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { JSON_RPC_ERROR_CODES, jsonRpcError } from './protocol'; -import type { McpServer } from './server'; - -/** Default maximum allowed line frame size in UTF-8 bytes (4 MiB). */ -export const DEFAULT_STDIO_MAX_LINE_BYTES = 4 * 1024 * 1024; - -/** Readable byte/string stream accepted by {@link runStdioServer}. */ -export type StdioInput = AsyncIterable; - -/** Minimal writable stream interface accepted by {@link runStdioServer}. */ -export interface StdioOutput { - write(chunk: string): boolean; - once?(event: 'drain', listener: () => void): unknown; -} - -/** Options for {@link runStdioServer}. */ -export interface StdioServerOptions { - readonly input?: StdioInput; - readonly output?: StdioOutput; - readonly maxLineBytes?: number; -} - -async function writeLine(output: StdioOutput, line: string): Promise { - const ok = output.write(`${line}\n`); - if (!ok && typeof output.once === 'function') { - await new Promise(resolve => { - output.once?.('drain', () => { - resolve(); - }); - }); - } -} - -/** - * Runs a newline-delimited JSON-RPC 2.0 stdio transport loop for an - * {@link McpServer}. - * - * - Decodes binary chunks with streaming UTF-8 (`TextDecoder`) so multi-byte - * characters split across chunk boundaries are never corrupted. - * - Dispatches lines strictly sequentially in arrival order. - * - Writes only compact newline-terminated JSON-RPC responses to `output` - * (skipping `null` notification results and blank lines). - * - Guards against oversized unterminated frames via `maxLineBytes`. - */ -export async function runStdioServer( - server: McpServer, - options?: StdioServerOptions -): Promise { - const input: StdioInput = options?.input ?? process.stdin; - const output: StdioOutput = options?.output ?? process.stdout; - const maxLineBytes = options?.maxLineBytes ?? DEFAULT_STDIO_MAX_LINE_BYTES; - - if (!Number.isSafeInteger(maxLineBytes) || maxLineBytes < 1) { - throw new Error(`Invalid maxLineBytes (${String(maxLineBytes)}): expected a positive integer.`); - } - - const decoder = new TextDecoder('utf-8'); - const encoder = new TextEncoder(); - let buffer = ''; - let droppingOversizedLine = false; - - const processLine = async (rawLine: string): Promise => { - const trimmed = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine; - if (trimmed.trim().length === 0) { - return; - } - const response = await server.handleMessage(trimmed); - if (response !== null) { - await writeLine(output, response); - } - }; - - const emitOversizedError = async (): Promise => { - const errorPayload = JSON.stringify( - jsonRpcError( - null, - JSON_RPC_ERROR_CODES.PARSE_ERROR, - `Parse error: message exceeds maximum frame size of ${maxLineBytes} bytes.` - ) - ); - await writeLine(output, errorPayload); - }; - - const drainBuffer = async (): Promise => { - while (true) { - const newlineIdx = buffer.indexOf('\n'); - if (newlineIdx === -1) { - if (!droppingOversizedLine && encoder.encode(buffer).byteLength > maxLineBytes) { - droppingOversizedLine = true; - buffer = ''; - await emitOversizedError(); - } - return; - } - - const rawLine = buffer.slice(0, newlineIdx); - buffer = buffer.slice(newlineIdx + 1); - - if (droppingOversizedLine) { - droppingOversizedLine = false; - continue; - } - - if (encoder.encode(rawLine).byteLength > maxLineBytes) { - await emitOversizedError(); - continue; - } - - await processLine(rawLine); - } - }; - - for await (const chunk of input) { - const text = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true }); - if (text.length === 0) { - continue; - } - - if (droppingOversizedLine) { - const newlineIdx = text.indexOf('\n'); - if (newlineIdx === -1) { - continue; - } - droppingOversizedLine = false; - buffer = text.slice(newlineIdx + 1); - } else { - buffer += text; - } - - await drainBuffer(); - } - - const tail = decoder.decode(); - if (tail.length > 0 && !droppingOversizedLine) { - buffer += tail; - } - - await drainBuffer(); - - if (!droppingOversizedLine && buffer.length > 0) { - if (encoder.encode(buffer).byteLength > maxLineBytes) { - await emitOversizedError(); - } else { - await processLine(buffer); - } - } -} diff --git a/libs/research/src/mcp/tools/analyze-signal.ts b/libs/research/src/mcp/tools/analyze-signal.ts deleted file mode 100644 index 0103f10a..00000000 --- a/libs/research/src/mcp/tools/analyze-signal.ts +++ /dev/null @@ -1,1201 +0,0 @@ -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 { - FUNDAMENTALS_PIT_VALUE_FIELDS, - type FundamentalsPitValueField, - UNIVERSE_REFS, -} from '../../market-data-store-duckdb'; -import { - SHORTS_SIGNAL_FIELDS, - type SignalObservation, - 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 { JsonSchemaObject, JsonSchemaProperty, McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool, zodObjectToJsonSchema } from '../server'; -import { - EXCLUSIVE_LISTING_SELECTOR_MESSAGE, - MCP_MAX_LISTING_IDS, - createListingIdsFieldSchema, - createUniverseFieldSchema, - fenceVaultQueryBounds, - formatMappedStoreError, - formatUtcIsoWithMicros, - 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; - -/** Hard maximum number of UTC month-end fundamentals snapshots queried in a single study. */ -export const ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS = 120; - -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 = 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 ("shorts").'), - field: z - .enum(SHORTS_SIGNAL_FIELDS) - .describe('Short-interest field to evaluate (shares_short, net_change, or pct_float).'), - }) - .strict() - .describe('Short-interest signal specification.'); - -const fundamentalsSignalSpecSchema = z - .object({ - source: z.literal('fundamentals').describe('Signal data source ("fundamentals").'), - field: z - .enum(FUNDAMENTALS_PIT_VALUE_FIELDS) - .describe( - 'Point-in-time fundamentals value field to evaluate (revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, ttm_revenue, ttm_net_income, or ttm_operating_cash_flow).' - ), - allowEstimatedLag: z - .boolean() - .default(false) - .describe( - 'Whether to include fundamentals snapshots with estimated publication lag (default false).' - ), - }) - .strict() - .describe('Point-in-time fundamentals signal specification.'); - -const signalSpecSchema = z - .discriminatedUnion('source', [shortsSignalSpecSchema, fundamentalsSignalSpecSchema]) - .describe('Discriminated signal source and field specification ("shorts" or "fundamentals").'); - -const analyzeSignalSharedFieldsSchema = 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.' - ), - 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(); - -/** - * 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 = analyzeSignalSharedFieldsSchema - .extend({ - signal: signalSpecSchema, - }) - .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.universeMarket === 'FX') { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['universeMarket'], - message: - data.signal.source === 'shorts' - ? 'Short-interest signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).' - : 'Fundamentals signal studies require an equity universeMarket (US_EQ, CA_EQ, or US_CA_EQ).', - }); - } - }); - -export type AnalyzeSignalInput = z.infer; - -function buildAnalyzeSignalJsonSchema(): JsonSchemaObject { - const sharedSchema = zodObjectToJsonSchema(analyzeSignalSharedFieldsSchema); - const shortsBranch = zodObjectToJsonSchema(shortsSignalSpecSchema); - const fundamentalsBranch = zodObjectToJsonSchema(fundamentalsSignalSpecSchema); - const allowEstimatedLagProp = fundamentalsBranch.properties.allowEstimatedLag ?? { - type: 'boolean' as const, - default: false, - }; - const signalProperty: JsonSchemaProperty = { - type: 'object', - description: signalSpecSchema.description, - properties: { - source: { - type: 'string', - enum: ['shorts', 'fundamentals'], - description: 'Signal data source ("shorts" or "fundamentals").', - }, - field: { - type: 'string', - enum: [...SHORTS_SIGNAL_FIELDS, ...FUNDAMENTALS_PIT_VALUE_FIELDS], - description: 'Signal field name valid for the chosen source.', - }, - allowEstimatedLag: allowEstimatedLagProp, - }, - required: ['source', 'field'], - additionalProperties: false, - anyOf: [shortsBranch, fundamentalsBranch], - }; - - return { - type: 'object', - properties: { - ...sharedSchema.properties, - signal: signalProperty, - }, - required: [...(sharedSchema.required ?? []), 'signal'], - additionalProperties: false, - }; -} - -const ANALYZE_SIGNAL_JSON_SCHEMA: JsonSchemaObject = buildAnalyzeSignalJsonSchema(); - -/** Server-side injected configuration for {@link createAnalyzeSignalTool}. */ -export interface AnalyzeSignalToolOptions { - readonly store: MarketDataStore; - readonly ledger: TrialLedgerExecutor; - readonly vaultContext: Pick; - readonly principalId: string; -} - -/** Single dated observation in the bounded series preview. */ -export interface AnalyzeSignalSeriesPoint { - readonly date: string; - readonly value: number; -} - -/** Bounded preview of the selected ledger series (latest 100 observations). */ -export interface AnalyzeSignalSeriesPreview { - readonly series: SignalLedgerSeries; - readonly totalCount: number; - readonly truncated: boolean; - readonly points: readonly AnalyzeSignalSeriesPoint[]; -} - -/** Projected quantile-spread summary without raw per-bucket typed arrays. */ -export interface AnalyzeSignalQuantilesSummary { - readonly quantiles: number; - readonly validDates: number; - readonly skippedDates: number; - readonly bucketMeanReturns: readonly (number | null)[]; - readonly spreadSummary: IcSummary; -} - -/** Projected top/bottom quantile membership turnover summary. */ -export interface AnalyzeSignalTurnoverSummary { - readonly count: number; - readonly meanTopTurnover: number | null; - readonly meanBottomTurnover: number | null; -} - -/** Bounded summary projection of {@link SignalPanelAnalysis}. */ -export interface AnalyzeSignalAnalysisSummary { - readonly pearsonIc: IcSummary; - readonly rankIc: IcSummary; - readonly quantiles: AnalyzeSignalQuantilesSummary; - readonly turnover: AnalyzeSignalTurnoverSummary; - readonly recency: RecencySplitResult; - readonly diagnostics: CalcSignalPanelDiagnostics; - readonly ledgerSeries: AnalyzeSignalSeriesPreview; -} - -interface AnalyzeSignalResultBase { - readonly scope: 'vault_fenced'; - readonly vaultCutoffTs: number; - readonly vaultCutoffDate: string; - readonly signal: AnalyzeSignalInput['signal']; - 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> = { - invalid_input: 'Invalid signal panel input.', - invalid_horizon: 'Invalid forward-return horizon.', - invalid_option: 'Invalid signal panel option.', - invalid_date: 'Invalid signal panel date.', - invalid_bar: 'Market bar data failed panel validation.', - invalid_signal: 'Signal table data failed panel validation.', - duplicate_bar: 'Conflicting duplicate daily bars detected.', -}; - -const SIGNAL_STUDY_ERROR_MESSAGES: Readonly> = { - invalid_request: 'Invalid signal study request.', - empty_panel: 'Signal panel is empty.', - invalid_date: 'Invalid signal study date.', - unsorted_dates: 'Signal panel dates are not strictly ascending.', - duplicate_date: 'Duplicate date detected in signal panel.', - invalid_panel: 'Signal panel failed validation.', - invalid_option: 'Invalid signal study option.', - dsr_read_failed: 'Trial was recorded, but cluster deflated Sharpe evaluation failed.', -}; - -const TRIAL_LEDGER_ERROR_MESSAGES: Readonly>> = { - VAULT_FENCE_VIOLATION: 'Sample window violates the Vault holdout cutoff.', - INVALID_PRINCIPAL: 'Invalid trial ledger principal.', - INVALID_UUID: 'Invalid trial ledger UUID.', - INVALID_SAMPLE_WINDOW: 'Invalid trial ledger sample window.', - INVALID_DATE: 'Invalid trial ledger date.', - SERIES_TOO_SHORT: 'Observation series is too short for trial ledger recording.', - ZERO_VARIANCE_SERIES: 'Observation series has zero variance.', - TRIAL_NOT_FOUND: 'Recorded trial could not be found in trial ledger.', -}; - -function sortAndDedupeListingIds(ids: readonly number[]): number[] { - return [...new Set(ids)].sort((a, b) => a - b); -} - -function projectAnalysisSummary( - analysis: SignalPanelAnalysis, - selectedSeries: SignalLedgerSeries -): AnalyzeSignalAnalysisSummary { - const rawDates = selectedSeries === 'rank_ic' ? analysis.dates : analysis.quantiles.dates; - const rawValues = - selectedSeries === 'rank_ic' ? analysis.rankIcSeries : analysis.quantiles.spreadSeries; - const totalCount = Math.min(rawDates.length, rawValues.length); - const truncated = totalCount > ANALYZE_SIGNAL_MAX_SERIES_POINTS; - const startIdx = truncated ? totalCount - ANALYZE_SIGNAL_MAX_SERIES_POINTS : 0; - const points: AnalyzeSignalSeriesPoint[] = []; - - for (let i = startIdx; i < totalCount; i += 1) { - points.push({ - date: rawDates[i] as string, - value: rawValues[i] as number, - }); - } - - return { - pearsonIc: analysis.pearsonIc, - rankIc: analysis.rankIc, - quantiles: { - quantiles: analysis.quantiles.quantiles, - validDates: analysis.quantiles.validDates, - skippedDates: analysis.quantiles.skippedDates, - bucketMeanReturns: [...analysis.quantiles.bucketMeanReturns], - spreadSummary: analysis.quantiles.spreadSummary, - }, - turnover: { - count: analysis.turnover.count, - meanTopTurnover: analysis.turnover.meanTopTurnover, - meanBottomTurnover: analysis.turnover.meanBottomTurnover, - }, - recency: analysis.recency, - diagnostics: analysis.diagnostics, - ledgerSeries: { - series: selectedSeries, - totalCount, - truncated, - points, - }, - }; -} - -function filterEligibleBars( - bars: readonly BarRecord[], - listingIdSet: ReadonlySet, - fromMs: number, - toMs: number, - asOfMs: number, - vaultCutoffTs: number, - vaultCutoffDate: string -): BarRecord[] { - const eligible: BarRecord[] = []; - for (let i = 0; i < bars.length; i += 1) { - const row = bars[i]; - if (typeof row !== 'object' || row === null) { - eligible.push(row as unknown as BarRecord); - continue; - } - if (typeof row.ts === 'number' && Number.isFinite(row.ts)) { - if ( - row.ts < fromMs || - row.ts > toMs || - row.ts > 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, - 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 deriveMonthlySnapshotDates(bars: readonly BarRecord[]): string[] { - const latestByMonth = new Map(); - for (let i = 0; i < bars.length; i += 1) { - const bar = bars[i]; - if ( - typeof bar !== 'object' || - bar === null || - typeof bar.ts !== 'number' || - !Number.isFinite(bar.ts) - ) { - continue; - } - const sessionDate = utcDateOf(bar.ts); - const monthKey = sessionDate.slice(0, 7); - const prev = latestByMonth.get(monthKey); - if (prev === undefined || sessionDate > prev) { - latestByMonth.set(monthKey, sessionDate); - } - } - return [...latestByMonth.values()].sort(); -} - -function resolveSnapshotAsOf( - snapshotDate: string, - fencedAsOfMs: number, - canonicalAsOf: string -): { readonly asOf: string; readonly asOfMs: number } { - const snapshotDayEndMs = Date.parse(`${snapshotDate}T23:59:59.999Z`); - if (fencedAsOfMs <= snapshotDayEndMs) { - return { - asOf: canonicalAsOf, - asOfMs: fencedAsOfMs, - }; - } - return { - asOf: formatUtcIsoWithMicros(snapshotDayEndMs, 999), - asOfMs: snapshotDayEndMs, - }; -} - -function buildBarTimestampsByListing(bars: readonly BarRecord[]): Map { - const byListing = new Map(); - for (let i = 0; i < bars.length; i += 1) { - const bar = bars[i]; - if ( - typeof bar !== 'object' || - bar === null || - typeof bar.listingId !== 'number' || - !Number.isSafeInteger(bar.listingId) || - typeof bar.ts !== 'number' || - !Number.isFinite(bar.ts) - ) { - continue; - } - let list = byListing.get(bar.listingId); - if (list === undefined) { - list = []; - byListing.set(bar.listingId, list); - } - list.push(bar.ts); - } - for (const [lid, list] of byListing) { - list.sort((a, b) => a - b); - let write = 0; - for (let i = 0; i < list.length; i += 1) { - const ts = list[i] as number; - if (write === 0 || list[write - 1] !== ts) { - list[write] = ts; - write += 1; - } - } - list.length = write; - byListing.set(lid, list); - } - return byListing; -} - -function findLatestBarBefore( - sortedTs: readonly number[] | undefined, - upperExclusiveMs: number, - lowerExclusiveMs: number -): number | null { - if (sortedTs === undefined || sortedTs.length === 0) { - return null; - } - let lo = 0; - let hi = sortedTs.length; - while (lo < hi) { - const mid = (lo + hi) >>> 1; - if ((sortedTs[mid] as number) < upperExclusiveMs) { - lo = mid + 1; - } else { - hi = mid; - } - } - const idx = lo - 1; - if (idx < 0) { - return null; - } - const candidate = sortedTs[idx] as number; - return candidate > lowerExclusiveMs ? candidate : null; -} - -function appendEligibleFundamentalsObservations(params: { - readonly table: Table; - readonly field: FundamentalsPitValueField; - readonly listingIdSet: ReadonlySet; - readonly snapshotAsOfMs: number; - readonly fencedAsOfMs: number; - readonly vaultCutoffTs: number; - readonly seenKeys: Set; - readonly out: SignalObservation[]; -}): Map { - const { - table, - field, - listingIdSet, - snapshotAsOfMs, - fencedAsOfMs, - vaultCutoffTs, - seenKeys, - out, - } = params; - - if ( - typeof table !== 'object' || - table === null || - !Array.isArray(table.columns) || - !Array.isArray(table.rows) - ) { - throw new SignalPanelError( - 'invalid_input', - 'Expected a fundamentals Table object with array columns and rows.' - ); - } - - const latestKnownAtByListing = new Map(); - - for (let i = 0; i < table.rows.length; i += 1) { - const row = table.rows[i]; - if (typeof row !== 'object' || row === null) { - continue; - } - - const listingId = row.listing_id; - if ( - typeof listingId !== 'number' || - !Number.isSafeInteger(listingId) || - !listingIdSet.has(listingId) - ) { - continue; - } - - const knownAt = row.effective_known_at; - if ( - typeof knownAt !== 'number' || - !Number.isFinite(knownAt) || - !Number.isSafeInteger(knownAt) - ) { - continue; - } - if (knownAt > snapshotAsOfMs || knownAt > fencedAsOfMs || knownAt >= vaultCutoffTs) { - continue; - } - - const rawValue = row[field]; - if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) { - continue; - } - - const normalizedListingId = listingId === 0 ? 0 : listingId; - const normalizedKnownAt = knownAt === 0 ? 0 : knownAt; - const prevLatest = latestKnownAtByListing.get(normalizedListingId); - if (prevLatest === undefined || normalizedKnownAt > prevLatest) { - latestKnownAtByListing.set(normalizedListingId, normalizedKnownAt); - } - - const normalizedValue = rawValue === 0 ? 0 : rawValue; - const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`; - if (seenKeys.has(dedupeKey)) { - continue; - } - seenKeys.add(dedupeKey); - out.push({ - listingId: normalizedListingId, - knownAt: normalizedKnownAt, - value: normalizedValue, - }); - } - - return latestKnownAtByListing; -} - -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, - ...(input.signal.source === 'fundamentals' - ? { allowEstimatedLag: input.signal.allowEstimatedLag } - : {}), - 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.fundamentalsAsOf !== 'function' || - typeof options.store.universe !== 'function' - ) { - throw new MarketDataStoreValidationError( - 'Invalid `store`: expected a MarketDataStore implementing `bars`, `shortsAsOf`, `fundamentalsAsOf`, 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 or point-in-time fundamentals signal study and record eligible trials to trial_ledger.', - inputSchema: analyzeSignalInputSchema, - jsonSchema: ANALYZE_SIGNAL_JSON_SCHEMA, - async handler(input: AnalyzeSignalInput): Promise { - try { - const fenced = fenceVaultQueryBounds( - { - from: input.from, - to: input.to, - asOf: input.asOf, - }, - vaultCutoffTs - ); - - let listingIds: number[]; - let universeSnapshotDate: string | null = null; - - if (input.universe !== undefined) { - universeSnapshotDate = resolvePreStartUniverseDate( - fenced.fromMs, - fenced.asOfMs, - fenced.asOfSubMs - ); - const resolved = await store.universe({ - ref: input.universe, - date: universeSnapshotDate, - }); - listingIds = sortAndDedupeListingIds(resolved); - } else { - listingIds = sortAndDedupeListingIds(input.listingIds ?? []); - } - - const signalEcho: AnalyzeSignalInput['signal'] = - input.signal.source === 'shorts' - ? { - source: 'shorts', - field: input.signal.field, - } - : { - source: 'fundamentals', - field: input.signal.field, - allowEstimatedLag: input.signal.allowEstimatedLag, - }; - - const basePayloadFields = { - scope: 'vault_fenced' as const, - vaultCutoffTs, - vaultCutoffDate: fenced.vaultCutoffDate, - signal: signalEcho, - 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 listingIdSet = new Set(listingIds); - const eligibleBars = filterEligibleBars( - rawBars, - listingIdSet, - fenced.fromMs, - fenced.toMs, - fenced.asOfMs, - vaultCutoffTs, - fenced.vaultCutoffDate - ); - - let signals: SignalObservation[]; - if (input.signal.source === 'shorts') { - const rawShortsTable = await store.shortsAsOf({ - listingIds, - from: fenced.canonicalFrom, - to: fenced.canonicalTo, - asOf: fenced.canonicalAsOf, - }); - const eligibleShortsTable = filterEligibleShortsTable( - rawShortsTable, - listingIdSet, - utcDateOf(fenced.fromMs), - utcDateOf(fenced.toMs), - fenced.asOfMs, - vaultCutoffTs, - fenced.vaultCutoffDate - ); - signals = shortsTableToSignalRows(eligibleShortsTable, input.signal.field); - } else { - const { field: fundamentalsField, allowEstimatedLag } = input.signal; - const snapshotDates = deriveMonthlySnapshotDates(eligibleBars); - if (snapshotDates.length > ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS) { - return { - content: [ - { - type: 'text', - text: `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.`, - }, - ], - isError: true, - }; - } - - signals = []; - const seenKeys = new Set(); - const barTimestampsByListing = buildBarTimestampsByListing(eligibleBars); - let windowFloorMs = Number.NEGATIVE_INFINITY; - - for (const snapshotDate of snapshotDates) { - const snapshot = resolveSnapshotAsOf( - snapshotDate, - fenced.asOfMs, - fenced.canonicalAsOf - ); - const rawTable = await store.fundamentalsAsOf({ - listingIds, - fields: [fundamentalsField], - asOf: snapshot.asOf, - allowEstimatedLag, - }); - const latestKnownByListing = appendEligibleFundamentalsObservations({ - table: rawTable, - field: fundamentalsField, - listingIdSet, - snapshotAsOfMs: snapshot.asOfMs, - fencedAsOfMs: fenced.asOfMs, - vaultCutoffTs, - seenKeys, - out: signals, - }); - - // Backfill vintages superseded earlier within this month (or prior - // to the first eligible bar for the initial month) by stepping to - // the latest uncovered eligible bar strictly before each returned - // vintage. Under either lag setting, a requested listing with no - // valid observation (omitted by DuckDB or carrying a null/non-finite - // field) is treated as an unresolved interval so earlier eligible - // closes within the month are probed. Listings sharing a target bar - // timestamp are batched. - const pendingByBarTs = new Map(); - const enqueueBackfill = ( - queriedListingIds: readonly number[], - knownByListing: ReadonlyMap, - upperBoundExclusiveMs: number - ): void => { - for (const lid of queriedListingIds) { - const knownAt = knownByListing.get(lid); - const upperExclusive = - knownAt !== undefined - ? Math.min(knownAt, upperBoundExclusiveMs) - : upperBoundExclusiveMs; - const prevBarTs = findLatestBarBefore( - barTimestampsByListing.get(lid), - upperExclusive, - windowFloorMs - ); - if (prevBarTs !== null) { - let bucket = pendingByBarTs.get(prevBarTs); - if (bucket === undefined) { - bucket = []; - pendingByBarTs.set(prevBarTs, bucket); - } - bucket.push(lid); - } - } - }; - - enqueueBackfill(listingIds, latestKnownByListing, snapshot.asOfMs); - - while (pendingByBarTs.size > 0) { - // Pop the highest bar timestamp first so earlier buckets merge - // newly discovered listings landing on the same session. - let nextBarTs = Number.NEGATIVE_INFINITY; - for (const ts of pendingByBarTs.keys()) { - if (ts > nextBarTs) { - nextBarTs = ts; - } - } - const batchListingIds = sortAndDedupeListingIds(pendingByBarTs.get(nextBarTs) ?? []); - pendingByBarTs.delete(nextBarTs); - if (batchListingIds.length === 0) { - continue; - } - - const batchAsOfMs = Math.min(nextBarTs, fenced.asOfMs); - const batchAsOf = - batchAsOfMs === fenced.asOfMs - ? fenced.canonicalAsOf - : formatUtcIsoWithMicros(batchAsOfMs, 0); - const batchListingIdSet = new Set(batchListingIds); - - const backfillTable = await store.fundamentalsAsOf({ - listingIds: batchListingIds, - fields: [fundamentalsField], - asOf: batchAsOf, - allowEstimatedLag, - }); - const backfillKnownByListing = appendEligibleFundamentalsObservations({ - table: backfillTable, - field: fundamentalsField, - listingIdSet: batchListingIdSet, - snapshotAsOfMs: batchAsOfMs, - fencedAsOfMs: fenced.asOfMs, - vaultCutoffTs, - seenKeys, - out: signals, - }); - - enqueueBackfill(batchListingIds, backfillKnownByListing, nextBarTs); - } - - windowFloorMs = snapshot.asOfMs; - } - } - - 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); - } - }, - }); -} diff --git a/libs/research/src/mcp/tools/event-study.ts b/libs/research/src/mcp/tools/event-study.ts deleted file mode 100644 index 68e5266e..00000000 --- a/libs/research/src/mcp/tools/event-study.ts +++ /dev/null @@ -1,1032 +0,0 @@ -import type { - EventStudyDiagnostics, - EventStudyRecencyResult, - EventStudyResult, - NeweyWestResult, -} from '@stock-bot/calculations'; -import { z } from 'zod'; -import { - type EventPanelDiagnostics, - EventPanelError, - type EventPanelErrorCode, - type EventStudyBenchmarkMode, - type EventStudyExchangeCalendars, - buildEventStudyInput, - eventsTableToEventRows, -} from '../../event-panel'; -import { - type BarRecord, - type EventKind, - type MarketDataStore, - MarketDataStoreValidationError, - type Table, - type TableRow, - type VaultFenceContext, -} from '../../market-data-store'; -import { EVENT_KINDS } from '../../market-data-store-duckdb'; -import { collectBars } from '../../signal-panel'; -import { - type RunEventStudyInsufficientDataReason, - SignalStudyError, - type SignalStudyErrorCode, - type SignalStudyExpression, - type StudyTrialSummary, - runEventStudy, -} from '../../signal-study'; -import { - type ClusterDeflatedSharpeResult, - HORIZON_BUCKETS, - type HorizonBucket, - TrialLedgerError, - type TrialLedgerErrorCode, - type TrialLedgerExecutor, - UNIVERSE_MARKETS, - type UniverseMarket, -} from '../../trial-ledger'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; -import { - EXCLUSIVE_LISTING_SELECTOR_MESSAGE, - MAX_ECMASCRIPT_EPOCH_MS, - MCP_MAX_LISTING_IDS, - MS_PER_DAY, - createListingIdsFieldSchema, - createUniverseFieldSchema, - fenceVaultQueryBounds, - formatMappedStoreError, - hasExclusiveListingSelector, - isValidUtcBoundString, - resolvePreStartUniverseDate, - utcDateOf, - validateVaultCutoffTs, -} from './vault-fenced-input'; - -/** Hard maximum number of explicit `listingIds` accepted by `event_study`. */ -export const EVENT_STUDY_MAX_LISTING_IDS = MCP_MAX_LISTING_IDS; - -/** Hard maximum pre-event window length in trading sessions. */ -export const EVENT_STUDY_MAX_PRE_DAYS = 60; - -/** Hard maximum post-event window length in trading sessions. */ -export const EVENT_STUDY_MAX_POST_DAYS = 60; - -/** Hard maximum number of event subtype entries accepted in `event.subtypes`. */ -export const EVENT_STUDY_MAX_SUBTYPES = 100; - -/** Hard maximum character length of each event subtype string in `event.subtypes`. */ -export const EVENT_STUDY_MAX_SUBTYPE_LENGTH = 128; - -const LEDGER_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -const AGENT_PRINCIPAL_RE = - /^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; -const UTC_BOUND_ERROR_MESSAGE = - 'Expected YYYY-MM-DD calendar date or UTC ISO-8601 timestamp with timezone offset.'; -const EVENT_KIND_SET: ReadonlySet = new Set(EVENT_KINDS); - -function canonicalDailyHorizonBucket(postDays: number): HorizonBucket { - return postDays <= 10 ? 'swing_1_10d' : 'position_10d_plus'; -} - -function isValidEpochMs(value: unknown): value is number { - return ( - typeof value === 'number' && - Number.isFinite(value) && - Number.isSafeInteger(value) && - Math.abs(value) < MAX_ECMASCRIPT_EPOCH_MS - ); -} - -const utcBoundStringSchema = z.string().min(1).refine(isValidUtcBoundString, UTC_BOUND_ERROR_MESSAGE); - -const eventFilterSpecSchema = z - .object({ - kinds: z - .array(z.enum(EVENT_KINDS)) - .min(1) - .describe( - 'Non-empty list of event kinds to include (filing, earnings, ceo_post, or corporate_action).' - ), - subtypes: z - .array(z.string().min(1).max(EVENT_STUDY_MAX_SUBTYPE_LENGTH)) - .min(1) - .max(EVENT_STUDY_MAX_SUBTYPES) - .optional() - .describe( - `Optional non-empty exact-match allow-list of event subtypes (max ${EVENT_STUDY_MAX_SUBTYPES} entries, ${EVENT_STUDY_MAX_SUBTYPE_LENGTH} chars each).` - ), - }) - .strict() - .describe('Event kind and optional subtype filter specification.'); - -/** - * Strict Zod input schema for the `event_study` MCP tool. - * - * Intentionally omits `scope`, `vault_evaluation_only`, `principalId`, and - * `vaultCutoffDate`; `.strict()` rejects any caller attempt to supply them - * or any other unknown top-level or nested key. - */ -export const eventStudyInputSchema = z - .object({ - listingIds: createListingIdsFieldSchema( - 'Explicit INT32 listing IDs to study (mutually exclusive with universe).' - ), - universe: createUniverseFieldSchema( - 'Survivorship-free universe identifier such as US_EQ, CA_EQ, or US_CA_EQ (mutually exclusive with listingIds).' - ), - from: utcBoundStringSchema.describe( - 'Inclusive study start date (YYYY-MM-DD) or UTC ISO-8601 timestamp.' - ), - to: utcBoundStringSchema.describe( - 'Inclusive study end date (YYYY-MM-DD) or UTC ISO-8601 timestamp; clamped below Vault cutoff.' - ), - asOf: utcBoundStringSchema - .optional() - .describe( - 'Optional point-in-time knowledge cutoff (YYYY-MM-DD or UTC ISO-8601); clamped below Vault cutoff.' - ), - event: eventFilterSpecSchema, - preDays: z - .number() - .int() - .min(0) - .max(EVENT_STUDY_MAX_PRE_DAYS) - .describe( - `Pre-event window in trading sessions (0–${EVENT_STUDY_MAX_PRE_DAYS}).` - ), - postDays: z - .number() - .int() - .min(0) - .max(EVENT_STUDY_MAX_POST_DAYS) - .describe( - `Post-event window in trading sessions (0–${EVENT_STUDY_MAX_POST_DAYS}).` - ), - benchmark: z - .enum(['equal_weight', 'none']) - .default('equal_weight') - .describe( - 'Benchmark return mode: equal_weight (cross-sectional mean of eligible listing returns) or none (default equal_weight).' - ), - adjustment: z - .enum(['raw', 'split', 'total']) - .default('raw') - .describe('Bar price adjustment mode (default raw).'), - universeMarket: z - .enum(UNIVERSE_MARKETS) - .describe('Relatedness-cluster market bucket recorded in trial_ledger.'), - horizonBucket: z - .enum(HORIZON_BUCKETS) - .describe('Relatedness-cluster horizon bucket recorded in trial_ledger.'), - campaignId: z - .string() - .regex(LEDGER_UUID_RE, 'Expected a UUID string.') - .optional() - .describe('Optional research campaign UUID recorded in trial_ledger.'), - hypothesisId: z - .string() - .regex(LEDGER_UUID_RE, 'Expected a UUID string.') - .optional() - .describe('Optional research hypothesis UUID recorded in trial_ledger.'), - }) - .strict() - .superRefine((data, ctx) => { - if (!hasExclusiveListingSelector(data)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: EXCLUSIVE_LISTING_SELECTOR_MESSAGE, - }); - } - - const expectedBucket = canonicalDailyHorizonBucket(data.postDays); - if (data.horizonBucket !== expectedBucket) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['horizonBucket'], - message: `Daily postDays=${data.postDays} requires horizonBucket "${expectedBucket}".`, - }); - } - - if (data.universe !== undefined && data.universeMarket !== data.universe) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['universeMarket'], - message: `Named universe "${data.universe}" requires universeMarket "${data.universe}".`, - }); - } - }); - -export type EventStudyToolInput = z.infer; - -/** Query passed to the server-injected exchange-calendar resolver. */ -export interface EventStudyExchangeCalendarQuery { - readonly listingIds: readonly number[]; - readonly fromDate: string; - readonly toDate: string; -} - -/** Server-injected exchange-calendar resolver returning actual session close calendars. */ -export type EventStudyExchangeCalendarResolver = ( - query: EventStudyExchangeCalendarQuery -) => Promise | EventStudyExchangeCalendars; - -/** Server-side injected configuration for {@link createEventStudyTool}. */ -export interface EventStudyToolOptions { - readonly store: MarketDataStore; - readonly ledger: TrialLedgerExecutor; - readonly vaultContext: Pick; - readonly principalId: string; - readonly resolveExchangeCalendars: EventStudyExchangeCalendarResolver; -} - -/** Projected CAR/AAR summary for one relative offset in `[-preDays, +postDays]`. */ -export interface EventStudyOffsetSummary { - readonly offset: number; - readonly n: number; - readonly aar: number; - readonly caar: number; - readonly caarFromZero: number | null; -} - -/** Bounded date-clustered CAR summary without raw per-date typed arrays. */ -export interface EventStudyClusteredSummary { - readonly nDates: number; - readonly carMean: number; - readonly neweyWest: NeweyWestResult; -} - -/** Bounded summary projection of {@link EventStudyResult}. */ -export interface EventStudySummary { - readonly preDays: number; - readonly postDays: number; - readonly hasBenchmark: boolean; - readonly offsets: readonly EventStudyOffsetSummary[]; - readonly clustered: EventStudyClusteredSummary | null; - readonly recency: EventStudyRecencyResult | null; - readonly diagnostics: EventStudyDiagnostics; -} - -interface EventStudyResultBase { - readonly scope: 'vault_fenced'; - readonly vaultCutoffTs: number; - readonly vaultCutoffDate: string; - readonly event: { - readonly kinds: readonly EventKind[]; - readonly subtypes: readonly string[] | null; - }; - readonly preDays: number; - readonly postDays: number; - readonly benchmark: EventStudyBenchmarkMode; - readonly adjustment: 'raw' | 'split' | 'total'; - readonly universeMarket: UniverseMarket; - readonly horizonBucket: HorizonBucket; - readonly fromMs: number; - readonly toMs: number; - readonly asOfMs: number; - readonly effectiveFrom: string; - readonly effectiveTo: string; - readonly effectiveAsOf: string; - readonly clampedTo: boolean; - readonly clampedAsOf: boolean; - readonly listingCount: number; - readonly eventCount: number; - readonly vaultExcludedEvents: number; - readonly panelDiagnostics: EventPanelDiagnostics; - readonly study: EventStudySummary; -} - -/** Structured JSON payload serialized into the `event_study` MCP text result. */ -export type EventStudyResultPayload = - | (EventStudyResultBase & { - readonly status: 'ok'; - readonly trial: StudyTrialSummary; - readonly deflatedSharpe: ClusterDeflatedSharpeResult; - }) - | (EventStudyResultBase & { - readonly status: 'insufficient_data'; - readonly reason: RunEventStudyInsufficientDataReason; - }); - -class ExchangeCalendarResolverError extends Error { - override readonly name = 'ExchangeCalendarResolverError'; - override readonly cause?: unknown; - - constructor(cause: unknown) { - super('Exchange calendar resolution failed.', { cause }); - this.cause = cause; - Object.setPrototypeOf(this, new.target.prototype); - } -} - -const ZERO_EVENT_PANEL_DIAGNOSTICS: EventPanelDiagnostics = { - vaultExcludedDates: 0, - vaultExcludedEvents: 0, - droppedUnknownListing: 0, - droppedAfterLastSession: 0, - droppedMissingCalendarSession: 0, - duplicateEvents: 0, - duplicateBars: 0, - nonPositiveCloseReturns: 0, -}; - -const ZERO_EVENT_STUDY_DIAGNOSTICS: EventStudyDiagnostics = { - eventsIn: 0, - eventsUsed: 0, - droppedUnknownEntity: 0, - droppedWindowOutOfRange: 0, - droppedMissingReturns: 0, - duplicateEventsCollapsed: 0, -}; - -const EVENT_PANEL_ERROR_MESSAGES: Readonly> = { - invalid_input: 'Invalid event panel input.', - invalid_date: 'Invalid event panel date.', - invalid_bar: 'Market bar data failed event panel validation.', - invalid_event: 'Event table data failed event panel validation.', - invalid_option: 'Invalid event panel option.', - duplicate_bar: 'Conflicting duplicate daily bars detected.', -}; - -const SIGNAL_STUDY_ERROR_MESSAGES: Readonly> = { - invalid_request: 'Invalid event study request.', - empty_panel: 'Event study session grid is empty.', - invalid_date: 'Invalid event study date.', - unsorted_dates: 'Event study session dates are not strictly ascending.', - duplicate_date: 'Duplicate date detected in event study session grid.', - invalid_panel: 'Event study panel failed validation.', - invalid_option: 'Invalid event study option.', - dsr_read_failed: 'Trial was recorded, but cluster deflated Sharpe evaluation failed.', -}; - -const TRIAL_LEDGER_ERROR_MESSAGES: Readonly>> = { - VAULT_FENCE_VIOLATION: 'Sample window violates the Vault holdout cutoff.', - INVALID_PRINCIPAL: 'Invalid trial ledger principal.', - INVALID_UUID: 'Invalid trial ledger UUID.', - INVALID_SAMPLE_WINDOW: 'Invalid trial ledger sample window.', - INVALID_DATE: 'Invalid trial ledger date.', - SERIES_TOO_SHORT: 'Observation series is too short for trial ledger recording.', - ZERO_VARIANCE_SERIES: 'Observation series has zero variance.', - TRIAL_NOT_FOUND: 'Recorded trial could not be found in trial ledger.', -}; - -function sortAndDedupeListingIds(ids: readonly number[]): number[] { - return [...new Set(ids)].sort((a, b) => a - b); -} - -function sortAndDedupeStrings(items: readonly T[]): T[] { - return [...new Set(items)].sort() as T[]; -} - -function makeEmptyStudySummary( - preDays: number, - postDays: number, - hasBenchmark: boolean -): EventStudySummary { - return { - preDays, - postDays, - hasBenchmark, - offsets: [], - clustered: null, - recency: null, - diagnostics: ZERO_EVENT_STUDY_DIAGNOSTICS, - }; -} - -function projectStudySummary(study: EventStudyResult): EventStudySummary { - if (study.status === 'insufficient_data') { - return { - preDays: study.preDays, - postDays: study.postDays, - hasBenchmark: study.hasBenchmark, - offsets: [], - clustered: null, - recency: null, - diagnostics: study.diagnostics, - }; - } - - return { - preDays: study.preDays, - postDays: study.postDays, - hasBenchmark: study.hasBenchmark, - offsets: study.offsets.map(o => ({ - offset: o.offset, - n: o.n, - aar: o.aar, - caar: o.caar, - caarFromZero: o.caarFromZero, - })), - clustered: { - nDates: study.clustered.nDates, - carMean: study.clustered.carMean, - neweyWest: study.clustered.neweyWest, - }, - recency: study.recency, - diagnostics: study.diagnostics, - }; -} - -function filterEligibleBars( - bars: readonly BarRecord[], - listingIdSet: ReadonlySet, - fromMs: number, - fromSubMs: number, - toMs: number, - asOfMs: number, - vaultCutoffTs: number, - vaultCutoffDate: string -): { readonly bars: BarRecord[]; readonly prePanelVaultExcludedDates: number } { - const eligible: BarRecord[] = []; - const vaultExcludedDates = new Set(); - const minTsMs = fromSubMs > 0 ? fromMs + 1 : fromMs; - - for (let i = 0; i < bars.length; i += 1) { - const row = bars[i]; - if (typeof row !== 'object' || row === null) { - eligible.push(row as unknown as BarRecord); - continue; - } - if (typeof row.listingId === 'number' && !listingIdSet.has(row.listingId)) { - continue; - } - - const tsValid = isValidEpochMs(row.ts); - const tsDate = tsValid ? utcDateOf(row.ts) : null; - const tsInVault = tsValid && (row.ts >= vaultCutoffTs || (tsDate as string) >= vaultCutoffDate); - if (tsInVault) { - vaultExcludedDates.add(tsDate as string); - continue; - } - - if (tsValid) { - if (row.ts < minTsMs || row.ts > toMs || row.ts > asOfMs) { - continue; - } - } - - if (isValidEpochMs(row.knownAt)) { - if ( - row.knownAt > asOfMs || - row.knownAt >= vaultCutoffTs || - utcDateOf(row.knownAt) >= vaultCutoffDate - ) { - continue; - } - } - - eligible.push(row); - } - - return { - bars: eligible, - prePanelVaultExcludedDates: vaultExcludedDates.size, - }; -} - -function filterEligibleEventsTable(params: { - readonly table: Table; - readonly listingIdSet: ReadonlySet; - readonly kindSet: ReadonlySet; - readonly subtypeSet: ReadonlySet | null; - readonly fromMs: number; - readonly fromSubMs: number; - readonly toMs: number; - readonly asOfMs: number; - readonly vaultCutoffTs: number; - readonly vaultCutoffDate: string; -}): { readonly table: Table; readonly prePanelVaultExcludedEvents: number } { - const { - table, - listingIdSet, - kindSet, - subtypeSet, - fromMs, - fromSubMs, - toMs, - asOfMs, - vaultCutoffTs, - vaultCutoffDate, - } = params; - - if ( - typeof table !== 'object' || - table === null || - !Array.isArray(table.columns) || - !Array.isArray(table.rows) - ) { - return { table, prePanelVaultExcludedEvents: 0 }; - } - - const eligibleRows: TableRow[] = []; - let prePanelVaultExcludedEvents = 0; - // TableRow timestamps carry integer epoch-ms precision. When the effective start - // has non-zero microseconds (fromSubMs > 0), any row stamped at `fromMs` is either - // strictly earlier (e.g. `.123Z < .123456Z`) or ambiguous at the boundary ms, so - // require `ts >= fromMs + 1` conservatively. - const minTsMs = fromSubMs > 0 ? fromMs + 1 : fromMs; - - for (let i = 0; i < table.rows.length; i += 1) { - const row = table.rows[i]; - if (typeof row !== 'object' || row === null || Array.isArray(row)) { - eligibleRows.push(row as TableRow); - continue; - } - - const listingId = row.listing_id; - if (typeof listingId === 'number' && !listingIdSet.has(listingId)) { - continue; - } - - // Drop valid but unrequested kinds/subtypes without counting them as Vault exclusions. - // Malformed kind/subtype values fall through so eventsTableToEventRows rejects them. - const kind = row.kind; - if (typeof kind === 'string' && EVENT_KIND_SET.has(kind) && !kindSet.has(kind)) { - continue; - } - if (subtypeSet !== null) { - const subtype = row.subtype; - if (subtype === null || (typeof subtype === 'string' && !subtypeSet.has(subtype))) { - continue; - } - } - - const knownAt = row.known_at; - const knownAtInVault = - isValidEpochMs(knownAt) && - (knownAt >= vaultCutoffTs || utcDateOf(knownAt) >= vaultCutoffDate); - - const ts = row.ts; - const tsInVault = - isValidEpochMs(ts) && - (ts >= vaultCutoffTs || utcDateOf(ts) >= vaultCutoffDate); - - if (knownAtInVault || tsInVault) { - prePanelVaultExcludedEvents += 1; - continue; - } - - if (isValidEpochMs(knownAt) && knownAt > asOfMs) { - continue; - } - - if (isValidEpochMs(ts)) { - if (ts < minTsMs || ts > toMs) { - continue; - } - } else { - throw new EventPanelError( - 'invalid_event', - `Invalid ts in events table row[${i}]: ${String(ts)}.` - ); - } - - eligibleRows.push(row); - } - - return { - table: { - columns: table.columns, - rows: eligibleRows, - }, - prePanelVaultExcludedEvents, - }; -} - -function buildCanonicalEventStudyExpression(params: { - readonly input: EventStudyToolInput; - readonly canonicalKinds: readonly EventKind[]; - readonly canonicalSubtypes: readonly string[] | undefined; - readonly listingIds: readonly number[]; - readonly universeSnapshotDate: string | null; - readonly effectiveFrom: string; - readonly effectiveTo: string; - readonly effectiveAsOf: string; -}): SignalStudyExpression { - const { - input, - canonicalKinds, - canonicalSubtypes, - listingIds, - universeSnapshotDate, - effectiveFrom, - effectiveTo, - effectiveAsOf, - } = params; - - return { - expression: `mcp:event_study:v1:${canonicalKinds.join(',')}`, - params: { - version: 1, - kinds: canonicalKinds, - subtypes: canonicalSubtypes ?? null, - preDays: input.preDays, - postDays: input.postDays, - benchmark: input.benchmark, - adjustment: input.adjustment, - effectiveFrom, - effectiveTo, - effectiveAsOf, - }, - universe: - input.universe !== undefined - ? { - kind: 'universe', - ref: input.universe, - snapshotDate: universeSnapshotDate, - listingIds, - } - : { - kind: 'listingIds', - listingIds, - }, - horizon: `${input.postDays}d`, - }; -} - -function formatMappedEventStudyError(err: unknown): McpToolCallResult { - const storeMapped = formatMappedStoreError(err); - if (storeMapped !== null) { - return storeMapped; - } - - if (err instanceof ExchangeCalendarResolverError) { - return { - content: [{ type: 'text', text: 'Error: Exchange calendar resolution failed.' }], - isError: true, - }; - } - - if (err instanceof EventPanelError) { - const detail = Object.prototype.hasOwnProperty.call(EVENT_PANEL_ERROR_MESSAGES, err.code) - ? EVENT_PANEL_ERROR_MESSAGES[err.code] - : 'Event panel construction failed.'; - return { - content: [{ type: 'text', text: `EventPanelError: ${detail}` }], - isError: true, - }; - } - - if (err instanceof SignalStudyError) { - const detail = Object.prototype.hasOwnProperty.call(SIGNAL_STUDY_ERROR_MESSAGES, err.code) - ? SIGNAL_STUDY_ERROR_MESSAGES[err.code] - : 'Event study execution failed.'; - return { - content: [{ type: 'text', text: `SignalStudyError: ${detail}` }], - isError: true, - }; - } - - if (err instanceof TrialLedgerError) { - const detail = - Object.prototype.hasOwnProperty.call(TRIAL_LEDGER_ERROR_MESSAGES, err.code) && - TRIAL_LEDGER_ERROR_MESSAGES[err.code] !== undefined - ? TRIAL_LEDGER_ERROR_MESSAGES[err.code] - : 'Trial ledger operation failed.'; - return { - content: [{ type: 'text', text: `TrialLedgerError: ${detail}` }], - isError: true, - }; - } - - return { - content: [{ type: 'text', text: 'Error: Tool execution failed.' }], - isError: true, - }; -} - -function validateFactoryOptions(options: EventStudyToolOptions): number { - if (typeof options !== 'object' || options === null) { - throw new MarketDataStoreValidationError( - 'Invalid `options`: expected an EventStudyToolOptions object.', - 'options' - ); - } - - if ( - typeof options.store !== 'object' || - options.store === null || - typeof options.store.bars !== 'function' || - typeof options.store.events !== 'function' || - typeof options.store.universe !== 'function' - ) { - throw new MarketDataStoreValidationError( - 'Invalid `store`: expected a MarketDataStore implementing `bars`, `events`, and `universe`.', - 'store' - ); - } - - if ( - typeof options.ledger !== 'object' || - options.ledger === null || - typeof options.ledger.query !== 'function' - ) { - throw new SignalStudyError( - 'invalid_request', - 'Invalid `ledger`: expected a TrialLedgerExecutor implementing `query`.' - ); - } - - if (typeof options.resolveExchangeCalendars !== 'function') { - throw new EventPanelError( - 'invalid_option', - 'Invalid `resolveExchangeCalendars`: expected a function.' - ); - } - - if ( - typeof options.principalId !== 'string' || - (options.principalId !== 'operator' && !AGENT_PRINCIPAL_RE.test(options.principalId)) - ) { - throw new TrialLedgerError( - 'INVALID_PRINCIPAL', - `Invalid \`principalId\`: "${String(options.principalId)}".` - ); - } - - return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs); -} - -/** - * Creates the Vault-fenced `event_study` MCP tool backed by an injected - * {@link MarketDataStore}, {@link TrialLedgerExecutor}, and exchange-calendar - * resolver. - * - * Enforces `scope: 'vault_fenced'`, fences bounds before any dependency call, - * resolves named universes strictly prior to the study start date, filters - * bars and events defensively against the effective window and Vault cutoff, - * anchors events using actual exchange close calendars, runs `runEventStudy` - * under the injected research principal, and returns a bounded summary payload. - */ -export function createEventStudyTool(options: EventStudyToolOptions): McpToolEntry { - const vaultCutoffTs = validateFactoryOptions(options); - const { store, ledger, principalId, resolveExchangeCalendars } = options; - - return defineMcpTool({ - name: 'event_study', - description: - 'Run a Vault-fenced event study over daily bars and point-in-time events and record eligible trials to trial_ledger.', - inputSchema: eventStudyInputSchema, - async handler(input: EventStudyToolInput): Promise { - try { - const fenced = fenceVaultQueryBounds( - { - from: input.from, - to: input.to, - asOf: input.asOf, - }, - vaultCutoffTs - ); - - const canonicalKinds = sortAndDedupeStrings(input.event.kinds); - const canonicalSubtypes = - input.event.subtypes !== undefined - ? sortAndDedupeStrings(input.event.subtypes) - : undefined; - - let listingIds: number[]; - let universeSnapshotDate: string | null = null; - - if (input.universe !== undefined) { - universeSnapshotDate = resolvePreStartUniverseDate( - fenced.fromMs, - fenced.asOfMs, - fenced.asOfSubMs - ); - const resolved = await store.universe({ - ref: input.universe, - date: universeSnapshotDate, - }); - listingIds = sortAndDedupeListingIds(resolved); - } else { - listingIds = sortAndDedupeListingIds(input.listingIds ?? []); - } - - const hasBenchmark = input.benchmark === 'equal_weight'; - const basePayloadFields = { - scope: 'vault_fenced' as const, - vaultCutoffTs, - vaultCutoffDate: fenced.vaultCutoffDate, - event: { - kinds: canonicalKinds, - subtypes: canonicalSubtypes ?? null, - }, - preDays: input.preDays, - postDays: input.postDays, - benchmark: input.benchmark, - adjustment: input.adjustment, - universeMarket: input.universeMarket, - horizonBucket: input.horizonBucket, - fromMs: fenced.fromMs, - toMs: fenced.toMs, - asOfMs: fenced.asOfMs, - effectiveFrom: fenced.canonicalFrom, - effectiveTo: fenced.canonicalTo, - effectiveAsOf: fenced.canonicalAsOf, - clampedTo: fenced.clampedTo, - clampedAsOf: fenced.clampedAsOf, - listingCount: listingIds.length, - }; - - if (listingIds.length === 0) { - const payload: EventStudyResultPayload = { - ...basePayloadFields, - status: 'insufficient_data', - reason: 'below_min_events', - eventCount: 0, - vaultExcludedEvents: 0, - panelDiagnostics: ZERO_EVENT_PANEL_DIAGNOSTICS, - study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), - }; - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } - - const rawBars = await collectBars( - store.bars({ - listingIds, - timeframe: '1d', - from: fenced.canonicalFrom, - to: fenced.canonicalTo, - adjustment: input.adjustment, - asOf: fenced.canonicalAsOf, - scope: 'vault_fenced', - }) - ); - - const rawEventsTable = await store.events({ - kinds: canonicalKinds, - listingIds, - from: fenced.canonicalFrom, - to: fenced.canonicalTo, - asOf: fenced.canonicalAsOf, - }); - - const listingIdSet = new Set(listingIds); - const kindSet = new Set(canonicalKinds); - const subtypeSet = canonicalSubtypes !== undefined ? new Set(canonicalSubtypes) : null; - - const { bars: eligibleBars, prePanelVaultExcludedDates } = filterEligibleBars( - rawBars, - listingIdSet, - fenced.fromMs, - fenced.fromSubMs, - fenced.toMs, - fenced.asOfMs, - vaultCutoffTs, - fenced.vaultCutoffDate - ); - - const { table: eligibleEventsTable, prePanelVaultExcludedEvents } = - filterEligibleEventsTable({ - table: rawEventsTable, - listingIdSet, - kindSet, - subtypeSet, - fromMs: fenced.fromMs, - fromSubMs: fenced.fromSubMs, - toMs: fenced.toMs, - asOfMs: fenced.asOfMs, - vaultCutoffTs, - vaultCutoffDate: fenced.vaultCutoffDate, - }); - - const events = eventsTableToEventRows(eligibleEventsTable, { - kinds: canonicalKinds, - ...(canonicalSubtypes !== undefined ? { subtypes: canonicalSubtypes } : {}), - }); - - const fromDate = utcDateOf(fenced.fromMs); - const toDate = utcDateOf(fenced.toMs); - const asOfDate = utcDateOf(fenced.asOfMs); - const vaultCutoffDayStartMs = Math.floor(vaultCutoffTs / MS_PER_DAY) * MS_PER_DAY; - const lastPreVaultDate = utcDateOf(vaultCutoffDayStartMs - MS_PER_DAY); - const calendarToDate = [toDate, asOfDate, lastPreVaultDate].reduce((a, b) => - a < b ? a : b - ); - - if (fromDate > calendarToDate) { - const panelDiagnostics: EventPanelDiagnostics = { - ...ZERO_EVENT_PANEL_DIAGNOSTICS, - vaultExcludedDates: prePanelVaultExcludedDates, - vaultExcludedEvents: prePanelVaultExcludedEvents, - droppedUnknownListing: events.length, - }; - const payload: EventStudyResultPayload = { - ...basePayloadFields, - status: 'insufficient_data', - reason: 'below_min_events', - eventCount: 0, - vaultExcludedEvents: prePanelVaultExcludedEvents, - panelDiagnostics, - study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), - }; - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } - - let exchangeCalendars: EventStudyExchangeCalendars; - try { - exchangeCalendars = await resolveExchangeCalendars({ - listingIds, - fromDate, - toDate: calendarToDate, - }); - } catch (err: unknown) { - if (err instanceof EventPanelError) { - throw err; - } - throw new ExchangeCalendarResolverError(err); - } - - const built = buildEventStudyInput({ - bars: eligibleBars, - events, - vaultCutoffDate: fenced.vaultCutoffDate, - benchmark: input.benchmark, - exchangeCalendars, - }); - - const combinedPanelDiagnostics: EventPanelDiagnostics = { - ...built.diagnostics, - vaultExcludedDates: prePanelVaultExcludedDates + built.diagnostics.vaultExcludedDates, - vaultExcludedEvents: prePanelVaultExcludedEvents + built.diagnostics.vaultExcludedEvents, - }; - - if (built.input.sessionDates.length === 0) { - const payload: EventStudyResultPayload = { - ...basePayloadFields, - status: 'insufficient_data', - reason: 'below_min_events', - eventCount: 0, - vaultExcludedEvents: combinedPanelDiagnostics.vaultExcludedEvents, - panelDiagnostics: combinedPanelDiagnostics, - study: makeEmptyStudySummary(input.preDays, input.postDays, hasBenchmark), - }; - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } - - const expression = buildCanonicalEventStudyExpression({ - input, - canonicalKinds, - canonicalSubtypes, - listingIds, - universeSnapshotDate, - effectiveFrom: fenced.canonicalFrom, - effectiveTo: fenced.canonicalTo, - effectiveAsOf: fenced.canonicalAsOf, - }); - - const studyResult = await runEventStudy(ledger, { - principalId, - ...(input.campaignId !== undefined ? { campaignId: input.campaignId } : {}), - ...(input.hypothesisId !== undefined ? { hypothesisId: input.hypothesisId } : {}), - universeMarket: input.universeMarket, - horizonBucket: input.horizonBucket, - expression, - input: built.input, - vaultCutoffDate: fenced.vaultCutoffDate, - options: { - preDays: input.preDays, - postDays: input.postDays, - }, - }); - - const totalVaultExcludedEvents = - combinedPanelDiagnostics.vaultExcludedEvents + studyResult.vaultExcludedEvents; - const studySummary = projectStudySummary(studyResult.study); - - const payload: EventStudyResultPayload = - studyResult.status === 'ok' - ? { - ...basePayloadFields, - status: 'ok', - eventCount: built.input.events.length, - vaultExcludedEvents: totalVaultExcludedEvents, - panelDiagnostics: combinedPanelDiagnostics, - study: studySummary, - trial: studyResult.trial, - deflatedSharpe: studyResult.deflatedSharpe, - } - : { - ...basePayloadFields, - status: 'insufficient_data', - reason: studyResult.reason, - eventCount: built.input.events.length, - vaultExcludedEvents: totalVaultExcludedEvents, - panelDiagnostics: combinedPanelDiagnostics, - study: studySummary, - }; - - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - } catch (err: unknown) { - return formatMappedEventStudyError(err); - } - }, - }); -} diff --git a/libs/research/src/mcp/tools/file-finding.ts b/libs/research/src/mcp/tools/file-finding.ts deleted file mode 100644 index 97fb8d3f..00000000 --- a/libs/research/src/mcp/tools/file-finding.ts +++ /dev/null @@ -1,416 +0,0 @@ -import { z } from 'zod'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; -import { type FindingRecord, READ_KNOWLEDGE_MAX_TEXT_LENGTH } from './read-knowledge'; -import { MAX_ECMASCRIPT_EPOCH_MS } from './vault-fenced-input'; - -/** Supported filing kinds for `file_finding` (per D12 in `design/PLATFORM-PLAN.md`). */ -export const FILE_FINDING_KINDS = ['finding', 'dead_end'] as const; - -export type FileFindingKind = (typeof FILE_FINDING_KINDS)[number]; - -/** Initial server-assigned review status for every newly filed finding or dead end. */ -export const FILE_FINDING_INITIAL_STATUS = 'pending_review' as const; - -export type FileFindingInitialStatus = typeof FILE_FINDING_INITIAL_STATUS; - -/** Hard maximum character length of a trimmed `file_finding` title. */ -export const FILE_FINDING_MAX_TITLE_LENGTH = 256; - -/** Hard maximum character length of a trimmed `file_finding` summary. */ -export const FILE_FINDING_MAX_SUMMARY_LENGTH = READ_KNOWLEDGE_MAX_TEXT_LENGTH; - -/** Hard maximum character length of a trimmed trial or evidence reference string. */ -export const FILE_FINDING_MAX_REF_LENGTH = 256; - -/** Hard maximum number of raw `trialRefs` accepted before deduplication. */ -export const FILE_FINDING_MAX_TRIAL_REFS = 32; - -/** Hard maximum number of raw `evidenceRefs` accepted before deduplication. */ -export const FILE_FINDING_MAX_EVIDENCE_REFS = 32; - -/** Hard maximum character length of a trimmed `idempotencyKey`. */ -export const FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH = 128; - -/** Fixed validation message used when unknown keys are supplied (never echoes caller keys). */ -export const FILE_FINDING_ERROR_UNKNOWN_KEYS = 'Unrecognized field(s) are not allowed.'; - -/** Fixed tool error message when one or more trial refs are unknown or Vault-only. */ -export const FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF = - 'One or more referenced trials are unavailable in the research-visible trial ledger.'; - -/** Fixed tool error message when an idempotency key is reused with a different payload. */ -export const FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT = - 'Idempotency key conflict: the provided idempotency key was already used with a different finding payload.'; - -/** Fixed tool error message when trial lookup, metadata generation, or append fails. */ -export const FILE_FINDING_ERROR_FILING_FAILED = - 'Failed to file finding due to a storage or lookup error.'; - -/** - * Append-only finding or dead-end record passed to {@link FindingWritePort.appendFinding}. - * - * Extends {@link FindingRecord} with `kind` and fixes `status` to `'pending_review'` - * so filed records are directly readable via `read_knowledge` while director approval - * happens out-of-band. - */ -export interface FiledFindingRecord extends FindingRecord { - readonly kind: FileFindingKind; - readonly status: FileFindingInitialStatus; -} - -/** Normalized caller-supplied fields compared for idempotency equality. */ -export type FiledFindingComparablePayload = Pick< - FiledFindingRecord, - 'kind' | 'title' | 'summary' | 'trialRefs' | 'evidenceRefs' ->; - -/** - * Discriminated outcome returned by {@link FindingWritePort.appendFinding}. - * - * - `'created'`: A new record was appended. - * - `'replayed'`: An existing record with the same `idempotencyKey` and - * identical normalized payload (`kind`, `title`, `summary`, `trialRefs`, - * `evidenceRefs`) was found; zero rows were appended and the stored `id` - * and `createdAt` are returned. - * - `'conflict'`: An existing record with the same `idempotencyKey` has a - * different normalized payload; zero rows were appended. - */ -export type AppendFindingResult = - | { - readonly status: 'created'; - readonly id: string; - readonly createdAt: string; - } - | { - readonly status: 'replayed'; - readonly id: string; - readonly createdAt: string; - } - | { - readonly status: 'conflict'; - }; - -/** - * Append-only write port injected into {@link createFileFindingTool}. - * - * Port contract: - * - Append-only by construction: exposes only {@link appendFinding} (no update - * or delete methods). - * - When `idempotencyKey` is supplied, the port must atomically compare and - * append within its configured key namespace: - * - Compare normalized `kind`, `title`, `summary`, `trialRefs`, and - * `evidenceRefs` (excluding server-generated `id`, `createdAt`, and `status`). - * - On an identical payload match, return `{ status: 'replayed', id, createdAt }` - * with the originally stored `id` and `createdAt` without appending a new row. - * - On a payload mismatch, return `{ status: 'conflict' }` and append zero rows. - * - When `idempotencyKey` is omitted (`undefined`), each call is independent and - * appends a new row, returning `{ status: 'created', id, createdAt }`. - */ -export interface FindingWritePort { - appendFinding( - record: FiledFindingRecord, - idempotencyKey?: string - ): Promise; -} - -/** - * Read-only trial visibility lookup port injected into {@link createFileFindingTool}. - * - * Bound at composition to the caller's research-visible `trial_ledger` and active - * Vault boundary. Accepts opaque string refs (for example, decimal `trialId` strings - * from `trial_ledger` receipts without numeric coercion) and returns `true` only when - * the trial exists and is research-visible. Unknown and Vault-only refs both return - * `false`. - */ -export interface TrialRefLookupPort { - hasResearchVisibleTrial(trialRef: string): Promise | boolean; -} - -/** Server-side injected configuration for {@link createFileFindingTool}. */ -export interface FileFindingToolOptions { - readonly port: FindingWritePort; - readonly trialLookup: TrialRefLookupPort; - readonly newId: () => string; - readonly now: () => Date | number; -} - -/** Structured JSON receipt serialized into the `file_finding` MCP text result. */ -export interface FileFindingResultPayload { - readonly id: string; - readonly createdAt: string; - readonly created: boolean; -} - -function compareStrings(a: string, b: string): number { - if (a < b) { - return -1; - } - if (a > b) { - return 1; - } - return 0; -} - -function normalizeRefSet(refs: readonly string[]): readonly string[] { - const unique = Array.from(new Set(refs)); - unique.sort(compareStrings); - return unique; -} - -function areStringArraysEqual(a: readonly string[], b: readonly string[]): boolean { - if (a.length !== b.length) { - return false; - } - for (let i = 0; i < a.length; i += 1) { - if (a[i] !== b[i]) { - return false; - } - } - return true; -} - -/** - * Compares two normalized filing payloads for idempotency equality across - * `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` (excluding - * server-generated `id`, `createdAt`, and `status`). - */ -export function areFiledFindingPayloadsEqual( - a: FiledFindingComparablePayload, - b: FiledFindingComparablePayload -): boolean { - return ( - a.kind === b.kind && - a.title === b.title && - a.summary === b.summary && - areStringArraysEqual(a.trialRefs, b.trialRefs) && - areStringArraysEqual(a.evidenceRefs, b.evidenceRefs) - ); -} - -const refStringSchema = z.string().trim().min(1).max(FILE_FINDING_MAX_REF_LENGTH); - -/** - * Strict Zod input schema for the `file_finding` MCP tool. - * - * Intentionally omits server-controlled fields (`id`, `status`, `createdAt`) and - * Vault/holdout fields (`scope`, `vault_evaluation_only`, `vaultCutoffTs`). - * `.strict(FILE_FINDING_ERROR_UNKNOWN_KEYS)` rejects any unknown keys with a fixed - * message so caller-supplied key names are never echoed. - * - * `title` and `summary` must describe research-visible evidence only; `evidenceRefs` - * are opaque snapshot identifiers that the tool stores without dereferencing. - */ -export const fileFindingInputSchema = z - .object({ - kind: z - .enum(FILE_FINDING_KINDS, { - errorMap: () => ({ message: "Expected 'finding' or 'dead_end'." }), - }) - .describe("Filing classification: 'finding' or 'dead_end'."), - title: z - .string() - .trim() - .min(1) - .max(FILE_FINDING_MAX_TITLE_LENGTH) - .describe( - `Short title describing research-visible evidence (trimmed, 1–${FILE_FINDING_MAX_TITLE_LENGTH} characters).` - ), - summary: z - .string() - .trim() - .min(1) - .max(FILE_FINDING_MAX_SUMMARY_LENGTH) - .describe( - `Concise summary of research-visible evidence only; never include Vault holdout observations (trimmed, 1–${FILE_FINDING_MAX_SUMMARY_LENGTH} characters).` - ), - trialRefs: z - .array(refStringSchema) - .min(1) - .max(FILE_FINDING_MAX_TRIAL_REFS) - .transform(normalizeRefSet) - .describe( - `Opaque research-visible trial_ledger references (1–${FILE_FINDING_MAX_TRIAL_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; deduplicated case-sensitively and sorted).` - ), - evidenceRefs: z - .array(refStringSchema) - .max(FILE_FINDING_MAX_EVIDENCE_REFS) - .default([]) - .transform(normalizeRefSet) - .describe( - `Optional opaque snapshot or artifact identifiers never dereferenced by the tool (0–${FILE_FINDING_MAX_EVIDENCE_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; defaults to empty list, deduplicated case-sensitively and sorted).` - ), - idempotencyKey: z - .string() - .trim() - .min(1) - .max(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH) - .optional() - .describe( - `Optional retry idempotency key (trimmed, 1–${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH} characters).` - ), - }) - .strict(FILE_FINDING_ERROR_UNKNOWN_KEYS); - -export type FileFindingInput = z.infer; - -function toolError(message: string): McpToolCallResult { - return { - content: [{ type: 'text', text: message }], - isError: true, - }; -} - -function validateNonEmptyString(value: unknown): string | null { - if (typeof value !== 'string' || value.trim().length === 0) { - return null; - } - return value; -} - -function formatUtcIsoTimestamp(raw: Date | number): string | null { - const epochMs = raw instanceof Date ? raw.getTime() : raw; - if ( - typeof epochMs !== 'number' || - !Number.isFinite(epochMs) || - Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS - ) { - return null; - } - return new Date(epochMs).toISOString(); -} - -function validateFactoryOptions(options: FileFindingToolOptions): FileFindingToolOptions { - if (typeof options !== 'object' || options === null) { - throw new Error('Invalid `options`: expected a FileFindingToolOptions object.'); - } - - if ( - typeof options.port !== 'object' || - options.port === null || - typeof options.port.appendFinding !== 'function' - ) { - throw new Error( - 'Invalid `port`: expected a FindingWritePort implementing `appendFinding`.' - ); - } - - if ( - typeof options.trialLookup !== 'object' || - options.trialLookup === null || - typeof options.trialLookup.hasResearchVisibleTrial !== 'function' - ) { - throw new Error( - 'Invalid `trialLookup`: expected a TrialRefLookupPort implementing `hasResearchVisibleTrial`.' - ); - } - - if (typeof options.newId !== 'function') { - throw new Error('Invalid `newId`: expected a function returning a non-empty finding ID.'); - } - - if (typeof options.now !== 'function') { - throw new Error('Invalid `now`: expected a clock function returning a Date or epoch ms.'); - } - - return options; -} - -/** - * Creates the append-only `file_finding` MCP tool backed by an injected - * {@link FindingWritePort} and read-only {@link TrialRefLookupPort}. - * - * Verifies every unique `trialRef` against the research-visible trial ledger - * before generating server-controlled metadata (`id`, `createdAt`, - * `status: 'pending_review'`) or calling `appendFinding`. Returns only the - * explicitly projected `{ id, createdAt, created }` receipt on success and fixed - * sanitized `isError` messages on failure. - */ -export function createFileFindingTool(options: FileFindingToolOptions): McpToolEntry { - const validated = validateFactoryOptions(options); - const { port, trialLookup, newId, now } = validated; - - return defineMcpTool({ - name: 'file_finding', - description: - 'File an append-only empirical finding or dead end linked to research-visible trial ledger references for director review.', - inputSchema: fileFindingInputSchema, - async handler(input: FileFindingInput): Promise { - // Verify every unique research-visible trial ref before generating metadata or writing. - for (let i = 0; i < input.trialRefs.length; i += 1) { - const trialRef = input.trialRefs[i] as string; - let visible: unknown; - try { - visible = await trialLookup.hasResearchVisibleTrial(trialRef); - } catch { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - if (typeof visible !== 'boolean') { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - if (!visible) { - return toolError(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - } - } - - let id: string | null; - let createdAt: string | null; - try { - id = validateNonEmptyString(newId()); - createdAt = formatUtcIsoTimestamp(now()); - } catch { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - if (id === null || createdAt === null) { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - const record: FiledFindingRecord = { - id, - kind: input.kind, - title: input.title, - status: FILE_FINDING_INITIAL_STATUS, - createdAt, - summary: input.summary, - trialRefs: [...input.trialRefs], - evidenceRefs: [...input.evidenceRefs], - }; - - let outcome: AppendFindingResult; - try { - outcome = await port.appendFinding(record, input.idempotencyKey); - } catch { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - if (typeof outcome !== 'object' || outcome === null) { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - if (outcome.status === 'conflict') { - return toolError(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); - } - - if (outcome.status !== 'created' && outcome.status !== 'replayed') { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - const receiptId = validateNonEmptyString(outcome.id); - const receiptCreatedAt = validateNonEmptyString(outcome.createdAt); - if (receiptId === null || receiptCreatedAt === null) { - return toolError(FILE_FINDING_ERROR_FILING_FAILED); - } - - const payload: FileFindingResultPayload = { - id: receiptId, - createdAt: receiptCreatedAt, - created: outcome.status === 'created', - }; - - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - }, - }); -} diff --git a/libs/research/src/mcp/tools/query-data.ts b/libs/research/src/mcp/tools/query-data.ts deleted file mode 100644 index b65fff46..00000000 --- a/libs/research/src/mcp/tools/query-data.ts +++ /dev/null @@ -1,249 +0,0 @@ -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; - -/** Configuration for {@link createQueryDataTool}. */ -export interface QueryDataToolOptions { - readonly store: MarketDataStore; - readonly vaultContext: Pick; -} - -/** Structured JSON payload serialized into the `query_data` MCP text result. */ -export interface QueryDataResultPayload { - readonly scope: 'vault_fenced'; - readonly vaultCutoffTs: number; - readonly timeframe: '1m' | '5m' | '1h' | '1d'; - readonly adjustment: 'raw' | 'split' | 'total'; - readonly fromMs: number; - readonly toMs: number; - readonly asOfMs: number; - readonly clampedTo: boolean; - readonly clampedAsOf: boolean; - readonly limit: number; - readonly rowCount: number; - readonly truncated: boolean; - readonly rows: readonly BarRecord[]; -} - -function 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 { - 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; - } - }, - }); -} diff --git a/libs/research/src/mcp/tools/read-knowledge.ts b/libs/research/src/mcp/tools/read-knowledge.ts deleted file mode 100644 index 929b398f..00000000 --- a/libs/research/src/mcp/tools/read-knowledge.ts +++ /dev/null @@ -1,588 +0,0 @@ -import { z } from 'zod'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; - -/** Concrete knowledge sources returned in `read_knowledge` rows and source counts. */ -export const READ_KNOWLEDGE_RECORD_SOURCES = ['library', 'findings', 'provider_caveats'] as const; - -export type ReadKnowledgeRecordSource = (typeof READ_KNOWLEDGE_RECORD_SOURCES)[number]; - -/** Supported `source` selector values for `read_knowledge`. */ -export const READ_KNOWLEDGE_SOURCES = [...READ_KNOWLEDGE_RECORD_SOURCES, 'all'] as const; - -export type ReadKnowledgeSource = (typeof READ_KNOWLEDGE_SOURCES)[number]; - -/** Default maximum number of matching records returned by `read_knowledge`. */ -export const READ_KNOWLEDGE_DEFAULT_LIMIT = 20; - -/** Hard maximum number of matching records returned by `read_knowledge`. */ -export const READ_KNOWLEDGE_MAX_LIMIT = 100; - -/** Hard maximum character length of a trimmed `read_knowledge` query string. */ -export const READ_KNOWLEDGE_MAX_QUERY_LENGTH = 64; - -/** Hard maximum character length per projected text field (`body`, `summary`, `caveat`). */ -export const READ_KNOWLEDGE_MAX_TEXT_LENGTH = 4096; - -/** Methodology or literature card record returned by {@link KnowledgePort.listLibraryCards}. */ -export interface LibraryCardRecord { - readonly id: string; - readonly title: string; - readonly tags: readonly string[]; - readonly summary: string; - readonly body: string; -} - -/** Empirical Stock Bot finding record returned by {@link KnowledgePort.listFindings}. */ -export interface FindingRecord { - readonly id: string; - readonly title: string; - readonly status: string; - readonly createdAt: string; - readonly summary: string; - readonly trialRefs: readonly string[]; - readonly evidenceRefs: readonly string[]; -} - -/** Provider dataset caveat record returned by {@link KnowledgePort.listProviderCaveats}. */ -export interface ProviderCaveatRecord { - readonly id: string; - readonly provider: string; - readonly dataset: string; - readonly caveat: string; - readonly createdAt: string; -} - -/** Applicable parsed selectors passed to {@link KnowledgePort.listLibraryCards}. */ -export interface LibraryCardQuery { - readonly id?: string; - readonly query?: string; - readonly tags?: readonly string[]; -} - -/** Applicable parsed selectors passed to {@link KnowledgePort.listFindings}. */ -export interface FindingQuery { - readonly id?: string; - readonly query?: string; -} - -/** Applicable parsed selectors passed to {@link KnowledgePort.listProviderCaveats}. */ -export interface ProviderCaveatQuery { - readonly id?: string; - readonly query?: string; - readonly provider?: string; -} - -/** - * Read-only knowledge lookup port injected into {@link createReadKnowledgeTool}. - * - * Port contract: - * - Read-only by construction: exposes only lookup methods and never mutates backing stores. - * - Callers and concrete adapters must supply research-visible records and references only; - * holdout observations and vault-only evidence must be excluded from the research corpus. - * - Return all eligible candidates (with IDs unique within each source) without pre-slicing - * so the tool controls deterministic global ranking and the global `limit`. - */ -export interface KnowledgePort { - listLibraryCards(q: LibraryCardQuery): Promise; - listFindings(q: FindingQuery): Promise; - listProviderCaveats(q: ProviderCaveatQuery): Promise; -} - -/** - * Strict Zod input schema for the `read_knowledge` MCP tool. - * - * Intentionally omits `scope`, `vault_evaluation_only`, and `vaultCutoffTs`; - * `.strict()` rejects any unknown keys. - */ -export const readKnowledgeInputSchema = z - .object({ - source: z - .enum(READ_KNOWLEDGE_SOURCES) - .default('all') - .describe( - 'Knowledge source to query: library, findings, provider_caveats, or all (default all).' - ), - query: z - .string() - .trim() - .min(1) - .max(READ_KNOWLEDGE_MAX_QUERY_LENGTH) - .optional() - .describe( - `Optional case-insensitive substring query (trimmed, 1–${READ_KNOWLEDGE_MAX_QUERY_LENGTH} characters). Ignored when id is supplied.` - ), - id: z - .string() - .trim() - .min(1) - .optional() - .describe( - 'Optional exact case-sensitive card or record ID selector. Takes precedence over query when supplied.' - ), - tags: z - .array(z.string().trim().min(1)) - .min(1) - .optional() - .describe( - 'Optional tag filter applied only to library cards (case-insensitive all-tag match; findings and provider_caveats are unaffected when source is all).' - ), - provider: z - .string() - .trim() - .min(1) - .optional() - .describe( - 'Optional provider filter applied only to provider_caveats (case-insensitive exact match; library and findings are unaffected when source is all).' - ), - limit: z - .number() - .int() - .min(1) - .max(READ_KNOWLEDGE_MAX_LIMIT) - .default(READ_KNOWLEDGE_DEFAULT_LIMIT) - .describe( - `Maximum number of ranked records to return (default ${READ_KNOWLEDGE_DEFAULT_LIMIT}, max ${READ_KNOWLEDGE_MAX_LIMIT}).` - ), - }) - .strict(); - -export type ReadKnowledgeInput = z.infer; - -/** Server-side injected configuration for {@link createReadKnowledgeTool}. */ -export interface ReadKnowledgeToolOptions { - readonly port: KnowledgePort; -} - -/** Source-labeled library card row emitted by `read_knowledge`. */ -export interface ReadKnowledgeLibraryRow { - readonly source: 'library'; - readonly id: string; - readonly title: string; - readonly tags: readonly string[]; - readonly summary: string; - readonly body: string; - readonly truncated: boolean; -} - -/** Source-labeled empirical finding row emitted by `read_knowledge`. */ -export interface ReadKnowledgeFindingRow { - readonly source: 'findings'; - readonly id: string; - readonly title: string; - readonly status: string; - readonly createdAt: string; - readonly summary: string; - readonly trialRefs: readonly string[]; - readonly evidenceRefs: readonly string[]; - readonly truncated: boolean; -} - -/** Source-labeled provider caveat row emitted by `read_knowledge`. */ -export interface ReadKnowledgeProviderCaveatRow { - readonly source: 'provider_caveats'; - readonly id: string; - readonly provider: string; - readonly dataset: string; - readonly caveat: string; - readonly createdAt: string; - readonly truncated: boolean; -} - -/** Discriminated union of rows emitted by `read_knowledge`. */ -export type ReadKnowledgeRow = - | ReadKnowledgeLibraryRow - | ReadKnowledgeFindingRow - | ReadKnowledgeProviderCaveatRow; - -/** Per-source counts of returned rows after applying the global `limit`. */ -export interface ReadKnowledgeSourceCounts { - readonly library: number; - readonly findings: number; - readonly provider_caveats: number; -} - -/** Structured JSON payload serialized into the `read_knowledge` MCP text result. */ -export interface ReadKnowledgeResultPayload { - readonly rowCount: number; - readonly sources: ReadKnowledgeSourceCounts; - readonly rows: readonly ReadKnowledgeRow[]; -} - -const SOURCE_ORDER: Readonly> = { - library: 0, - findings: 1, - provider_caveats: 2, -}; - -function compareStrings(a: string, b: string): number { - if (a < b) { - return -1; - } - if (a > b) { - return 1; - } - return 0; -} - -function validateRequiredString(value: unknown, field: string): string { - if (typeof value !== 'string') { - throw new Error(`Invalid port string for "${field}".`); - } - return value; -} - -function validateStringArray(value: unknown, field: string): readonly string[] { - if (!Array.isArray(value)) { - throw new Error(`Invalid port string array for "${field}".`); - } - const result: string[] = []; - for (let i = 0; i < value.length; i += 1) { - const entry: unknown = value[i]; - if (typeof entry !== 'string') { - throw new Error(`Invalid port string array entry for "${field}".`); - } - result.push(entry); - } - return result; -} - -function truncateText(value: string): { readonly text: string; readonly truncated: boolean } { - if (value.length <= READ_KNOWLEDGE_MAX_TEXT_LENGTH) { - return { text: value, truncated: false }; - } - return { - text: value.slice(0, READ_KNOWLEDGE_MAX_TEXT_LENGTH), - truncated: true, - }; -} - -function validateLibraryCard(raw: LibraryCardRecord): LibraryCardRecord { - if (typeof raw !== 'object' || raw === null) { - throw new Error('Invalid library card record returned by port.'); - } - return { - id: validateRequiredString(raw.id, 'id'), - title: validateRequiredString(raw.title, 'title'), - tags: validateStringArray(raw.tags, 'tags'), - summary: validateRequiredString(raw.summary, 'summary'), - body: validateRequiredString(raw.body, 'body'), - }; -} - -function validateFinding(raw: FindingRecord): FindingRecord { - if (typeof raw !== 'object' || raw === null) { - throw new Error('Invalid finding record returned by port.'); - } - return { - id: validateRequiredString(raw.id, 'id'), - title: validateRequiredString(raw.title, 'title'), - status: validateRequiredString(raw.status, 'status'), - createdAt: validateRequiredString(raw.createdAt, 'createdAt'), - summary: validateRequiredString(raw.summary, 'summary'), - trialRefs: validateStringArray(raw.trialRefs, 'trialRefs'), - evidenceRefs: validateStringArray(raw.evidenceRefs, 'evidenceRefs'), - }; -} - -function validateProviderCaveat(raw: ProviderCaveatRecord): ProviderCaveatRecord { - if (typeof raw !== 'object' || raw === null) { - throw new Error('Invalid provider caveat record returned by port.'); - } - return { - id: validateRequiredString(raw.id, 'id'), - provider: validateRequiredString(raw.provider, 'provider'), - dataset: validateRequiredString(raw.dataset, 'dataset'), - caveat: validateRequiredString(raw.caveat, 'caveat'), - createdAt: validateRequiredString(raw.createdAt, 'createdAt'), - }; -} - -function matchesAllTags( - cardTags: readonly string[], - requiredLowerTags: readonly string[] -): boolean { - const cardLowerTags = new Set(cardTags.map(tag => tag.toLowerCase())); - for (let i = 0; i < requiredLowerTags.length; i += 1) { - if (!cardLowerTags.has(requiredLowerTags[i] as string)) { - return false; - } - } - return true; -} - -function rankLibraryCard( - card: LibraryCardRecord, - exactId: string | undefined, - normalizedQuery: string | null, - requiredLowerTags: readonly string[] | null -): number | null { - if (requiredLowerTags !== null && !matchesAllTags(card.tags, requiredLowerTags)) { - return null; - } - if (exactId !== undefined) { - return card.id === exactId ? 0 : null; - } - if (normalizedQuery === null) { - return 2; - } - const titleMatches = card.title.toLowerCase().includes(normalizedQuery); - const tagMatches = card.tags.some(tag => tag.toLowerCase().includes(normalizedQuery)); - const summaryMatches = card.summary.toLowerCase().includes(normalizedQuery); - if (!titleMatches && !tagMatches && !summaryMatches) { - return null; - } - return titleMatches ? 1 : 2; -} - -function rankFinding( - finding: FindingRecord, - exactId: string | undefined, - normalizedQuery: string | null -): number | null { - if (exactId !== undefined) { - return finding.id === exactId ? 0 : null; - } - if (normalizedQuery === null) { - return 2; - } - const titleMatches = finding.title.toLowerCase().includes(normalizedQuery); - const summaryMatches = finding.summary.toLowerCase().includes(normalizedQuery); - if (!titleMatches && !summaryMatches) { - return null; - } - return titleMatches ? 1 : 2; -} - -function rankProviderCaveat( - caveat: ProviderCaveatRecord, - exactId: string | undefined, - normalizedQuery: string | null, - normalizedProvider: string | null -): number | null { - if (normalizedProvider !== null && caveat.provider.toLowerCase() !== normalizedProvider) { - return null; - } - if (exactId !== undefined) { - return caveat.id === exactId ? 0 : null; - } - if (normalizedQuery === null) { - return 2; - } - const datasetMatches = caveat.dataset.toLowerCase().includes(normalizedQuery); - const providerMatches = caveat.provider.toLowerCase().includes(normalizedQuery); - const caveatMatches = caveat.caveat.toLowerCase().includes(normalizedQuery); - if (!datasetMatches && !providerMatches && !caveatMatches) { - return null; - } - return datasetMatches ? 1 : 2; -} - -function projectLibraryCard(card: LibraryCardRecord): ReadKnowledgeLibraryRow { - const summary = truncateText(card.summary); - const body = truncateText(card.body); - return { - source: 'library', - id: card.id, - title: card.title, - tags: [...card.tags], - summary: summary.text, - body: body.text, - truncated: summary.truncated || body.truncated, - }; -} - -function projectFinding(finding: FindingRecord): ReadKnowledgeFindingRow { - const summary = truncateText(finding.summary); - return { - source: 'findings', - id: finding.id, - title: finding.title, - status: finding.status, - createdAt: finding.createdAt, - summary: summary.text, - trialRefs: [...finding.trialRefs], - evidenceRefs: [...finding.evidenceRefs], - truncated: summary.truncated, - }; -} - -function projectProviderCaveat(caveat: ProviderCaveatRecord): ReadKnowledgeProviderCaveatRow { - const caveatText = truncateText(caveat.caveat); - return { - source: 'provider_caveats', - id: caveat.id, - provider: caveat.provider, - dataset: caveat.dataset, - caveat: caveatText.text, - createdAt: caveat.createdAt, - truncated: caveatText.truncated, - }; -} - -function validateFactoryOptions(options: ReadKnowledgeToolOptions): KnowledgePort { - if (typeof options !== 'object' || options === null) { - throw new Error('Invalid `options`: expected a ReadKnowledgeToolOptions object.'); - } - - const { port } = options; - if ( - typeof port !== 'object' || - port === null || - typeof port.listLibraryCards !== 'function' || - typeof port.listFindings !== 'function' || - typeof port.listProviderCaveats !== 'function' - ) { - throw new Error( - 'Invalid `port`: expected a KnowledgePort implementing `listLibraryCards`, `listFindings`, and `listProviderCaveats`.' - ); - } - - return port; -} - -interface RankedCandidate { - readonly rank: number; - readonly row: ReadKnowledgeRow; -} - -/** - * Creates the read-only `read_knowledge` MCP tool backed by an injected - * {@link KnowledgePort}. - * - * Queries only the selected source(s), applies exact-ID or case-insensitive - * text matching and source-specific filters (`tags` for library cards, - * `provider` for provider caveats), ranks deterministically (exact ID > title - * match > ascending ID, breaking cross-source ties in `library`, `findings`, - * `provider_caveats` order), applies `limit` after ranking, and caps long text - * fields independently with `truncated: true`. - */ -export function createReadKnowledgeTool(options: ReadKnowledgeToolOptions): McpToolEntry { - const port = validateFactoryOptions(options); - - return defineMcpTool({ - name: 'read_knowledge', - description: - 'Read-only lookup across methodology library cards, empirical findings, and provider dataset caveats.', - inputSchema: readKnowledgeInputSchema, - async handler(input: ReadKnowledgeInput): Promise { - const wantLibrary = input.source === 'all' || input.source === 'library'; - const wantFindings = input.source === 'all' || input.source === 'findings'; - const wantCaveats = input.source === 'all' || input.source === 'provider_caveats'; - - const baseQuery: FindingQuery = - input.id !== undefined - ? { id: input.id } - : input.query !== undefined - ? { query: input.query } - : {}; - - const libraryQuery: LibraryCardQuery = { - ...baseQuery, - ...(input.tags !== undefined ? { tags: input.tags } : {}), - }; - const findingQuery: FindingQuery = baseQuery; - const caveatQuery: ProviderCaveatQuery = { - ...baseQuery, - ...(input.provider !== undefined ? { provider: input.provider } : {}), - }; - - const [rawLibrary, rawFindings, rawCaveats] = await Promise.all([ - (async () => (wantLibrary ? port.listLibraryCards(libraryQuery) : null))(), - (async () => (wantFindings ? port.listFindings(findingQuery) : null))(), - (async () => (wantCaveats ? port.listProviderCaveats(caveatQuery) : null))(), - ]); - - const normalizedQuery = - input.id === undefined && input.query !== undefined ? input.query.toLowerCase() : null; - const requiredLowerTags = - input.tags !== undefined ? input.tags.map(tag => tag.toLowerCase()) : null; - const normalizedProvider = - input.provider !== undefined ? input.provider.toLowerCase() : null; - - const eligible: RankedCandidate[] = []; - - if (rawLibrary !== null) { - if (!Array.isArray(rawLibrary)) { - throw new Error('Invalid library cards response returned by port.'); - } - for (let i = 0; i < rawLibrary.length; i += 1) { - const card = validateLibraryCard(rawLibrary[i] as LibraryCardRecord); - const rank = rankLibraryCard(card, input.id, normalizedQuery, requiredLowerTags); - if (rank !== null) { - eligible.push({ rank, row: projectLibraryCard(card) }); - } - } - } - - if (rawFindings !== null) { - if (!Array.isArray(rawFindings)) { - throw new Error('Invalid findings response returned by port.'); - } - for (let i = 0; i < rawFindings.length; i += 1) { - const finding = validateFinding(rawFindings[i] as FindingRecord); - const rank = rankFinding(finding, input.id, normalizedQuery); - if (rank !== null) { - eligible.push({ rank, row: projectFinding(finding) }); - } - } - } - - if (rawCaveats !== null) { - if (!Array.isArray(rawCaveats)) { - throw new Error('Invalid provider caveats response returned by port.'); - } - for (let i = 0; i < rawCaveats.length; i += 1) { - const caveat = validateProviderCaveat(rawCaveats[i] as ProviderCaveatRecord); - const rank = rankProviderCaveat(caveat, input.id, normalizedQuery, normalizedProvider); - if (rank !== null) { - eligible.push({ rank, row: projectProviderCaveat(caveat) }); - } - } - } - - eligible.sort((a, b) => { - if (a.rank !== b.rank) { - return a.rank - b.rank; - } - const idCmp = compareStrings(a.row.id, b.row.id); - if (idCmp !== 0) { - return idCmp; - } - return SOURCE_ORDER[a.row.source] - SOURCE_ORDER[b.row.source]; - }); - - const limitCount = Math.min(eligible.length, input.limit); - const rows: ReadKnowledgeRow[] = []; - let libraryCount = 0; - let findingsCount = 0; - let providerCaveatsCount = 0; - - for (let i = 0; i < limitCount; i += 1) { - const row = (eligible[i] as RankedCandidate).row; - rows.push(row); - if (row.source === 'library') { - libraryCount += 1; - } else if (row.source === 'findings') { - findingsCount += 1; - } else { - providerCaveatsCount += 1; - } - } - - const payload: ReadKnowledgeResultPayload = { - rowCount: rows.length, - sources: { - library: libraryCount, - findings: findingsCount, - provider_caveats: providerCaveatsCount, - }, - rows, - }; - - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - }, - }); -} diff --git a/libs/research/src/mcp/tools/search-symbols.ts b/libs/research/src/mcp/tools/search-symbols.ts deleted file mode 100644 index a5bd5882..00000000 --- a/libs/research/src/mcp/tools/search-symbols.ts +++ /dev/null @@ -1,359 +0,0 @@ -import { z } from 'zod'; -import { MarketDataStoreValidationError, type VaultFenceContext } from '../../market-data-store'; -import type { McpToolCallResult } from '../protocol'; -import { type McpToolEntry, defineMcpTool } from '../server'; -import { utcDateOf, validateVaultCutoffTs } from './vault-fenced-input'; - -/** Default maximum number of matching listings returned by `search_symbols`. */ -export const SEARCH_SYMBOLS_DEFAULT_LIMIT = 20; - -/** Hard maximum number of matching listings returned by `search_symbols`. */ -export const SEARCH_SYMBOLS_MAX_LIMIT = 100; - -/** Hard maximum character length of a trimmed `search_symbols` query string. */ -export const SEARCH_SYMBOLS_MAX_QUERY_LENGTH = 64; - -/** Supported exchange country filters for `search_symbols`. */ -export const SEARCH_SYMBOLS_COUNTRIES = ['US', 'CA'] as const; - -export type SymbolSearchCountry = (typeof SEARCH_SYMBOLS_COUNTRIES)[number]; - -const CALENDAR_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/; -const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; - -/** - * Security-master projection returned by {@link SymbolSearchPort} and emitted - * (after Vault fencing) by the `search_symbols` MCP tool. - * - * Field provenance (M1 security master DDL / `design/DATA-CONTRACTS.md`): - * - `listingId`: `listing.listing_id` (`INT32`) - * - `instrumentId`: `listing.instrument_id` / `instrument.instrument_id` (`INT32`) - * - `ticker`: `listing_symbol_history.ticker` valid as of the Vault cutoff - * - `classSuffix`: nullable `listing.class_suffix` - * - `name`: `instrument.canonical_name` - * - `mic`: `listing.mic` - * - `currency`: `listing.currency` - * - `isin`: nullable `instrument.primary_isin` - * - `firstBarDate`: nullable `YYYY-MM-DD` observed bar span start (`listing.listed_from`) - * - `lastBarDate`: nullable `YYYY-MM-DD` observed bar span end (`listing.listed_to`) - * - `delistedAt`: nullable `YYYY-MM-DD` confirmed delisting date (distinct from `lastBarDate`) - */ -export interface SymbolSearchRow { - readonly listingId: number; - readonly instrumentId: number; - readonly ticker: string; - readonly classSuffix: string | null; - readonly name: string; - readonly mic: string; - readonly currency: string; - readonly isin: string | null; - readonly firstBarDate: string | null; - readonly lastBarDate: string | null; - readonly delistedAt: string | null; -} - -/** - * Query passed to {@link SymbolSearchPort.searchSymbols}. - * - * Port contract: - * - Return all matching candidates for tool-side ranking and Vault fencing; - * treat `limit` as a hint only (never truncate ahead of exact-ticker matches). - * - Resolve symbol identities and matches as of `vaultCutoffTs` so future - * renames or delistings do not leak into research queries. - * - Include listings whose `firstBarDate` is unknown (`null`). - * - The tool always passes `includeDelisted: true` to the port so current - * delisting status cannot drop a candidate before Vault cutoff masking. - */ -export interface SymbolSearchQuery { - readonly query: string; - readonly limit: number; - readonly country?: SymbolSearchCountry; - readonly includeDelisted: boolean; - readonly vaultCutoffTs: number; -} - -/** Read-only security-master symbol lookup port injected into `createSearchSymbolsTool`. */ -export interface SymbolSearchPort { - searchSymbols(q: SymbolSearchQuery): Promise; -} - -/** - * Strict Zod input schema for the `search_symbols` MCP tool. - * - * Intentionally omits `scope`, `vault_evaluation_only`, and `vaultCutoffTs`; - * `.strict()` rejects any unknown keys. - */ -export const searchSymbolsInputSchema = z - .object({ - query: z - .string() - .trim() - .min(1) - .max(SEARCH_SYMBOLS_MAX_QUERY_LENGTH) - .describe( - `Ticker symbol or company name search query (trimmed, 1–${SEARCH_SYMBOLS_MAX_QUERY_LENGTH} characters).` - ), - limit: z - .number() - .int() - .min(1) - .max(SEARCH_SYMBOLS_MAX_LIMIT) - .default(SEARCH_SYMBOLS_DEFAULT_LIMIT) - .describe( - `Maximum number of matching listings to return (default ${SEARCH_SYMBOLS_DEFAULT_LIMIT}, max ${SEARCH_SYMBOLS_MAX_LIMIT}).` - ), - country: z - .enum(SEARCH_SYMBOLS_COUNTRIES) - .optional() - .describe('Optional exchange country filter (US or CA).'), - includeDelisted: z - .boolean() - .default(true) - .describe('Include delisted listings as of the Vault cutoff (default true).'), - }) - .strict(); - -export type SearchSymbolsInput = z.infer; - -/** Server-side injected configuration for {@link createSearchSymbolsTool}. */ -export interface SearchSymbolsToolOptions { - readonly port: SymbolSearchPort; - readonly vaultContext: Pick; -} - -/** Structured JSON payload serialized into the `search_symbols` MCP text result. */ -export interface SearchSymbolsResultPayload { - readonly scope: 'vault_fenced'; - readonly vaultCutoffTs: number; - readonly rowCount: number; - readonly truncated: boolean; - readonly rows: readonly SymbolSearchRow[]; -} - -function isLeapYear(year: number): boolean { - return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; -} - -function daysInUtcMonth(year: number, monthIndex: number): number { - if (monthIndex === 1 && isLeapYear(year)) { - return 29; - } - return DAYS_IN_MONTH[monthIndex] ?? 0; -} - -function isValidCalendarDate(value: unknown): value is string { - if (typeof value !== 'string') { - return false; - } - const match = CALENDAR_DATE_RE.exec(value); - if (match === null) { - return false; - } - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - if (month < 1 || month > 12) { - return false; - } - return day >= 1 && day <= daysInUtcMonth(year, month - 1); -} - -function validateNullableDate(value: unknown, field: string): string | null { - if (value === null) { - return null; - } - if (!isValidCalendarDate(value)) { - throw new Error(`Invalid port date for "${field}".`); - } - return value; -} - -function validateNullableString(value: unknown, field: string): string | null { - if (value === null) { - return null; - } - if (typeof value !== 'string') { - throw new Error(`Invalid port string for "${field}".`); - } - return value; -} - -function validateRequiredString(value: unknown, field: string): string { - if (typeof value !== 'string') { - throw new Error(`Invalid port string for "${field}".`); - } - return value; -} - -function validateSafeInteger(value: unknown, field: string): number { - if (typeof value !== 'number' || !Number.isSafeInteger(value)) { - throw new Error(`Invalid port integer for "${field}".`); - } - return value; -} - -function fenceAndProjectRow( - raw: SymbolSearchRow, - vaultCutoffDate: string, - includeDelisted: boolean -): SymbolSearchRow | null { - if (typeof raw !== 'object' || raw === null) { - throw new Error('Invalid symbol search row returned by port.'); - } - - const listingId = validateSafeInteger(raw.listingId, 'listingId'); - const instrumentId = validateSafeInteger(raw.instrumentId, 'instrumentId'); - const ticker = validateRequiredString(raw.ticker, 'ticker'); - const classSuffix = validateNullableString(raw.classSuffix, 'classSuffix'); - const name = validateRequiredString(raw.name, 'name'); - const mic = validateRequiredString(raw.mic, 'mic'); - const currency = validateRequiredString(raw.currency, 'currency'); - const isin = validateNullableString(raw.isin, 'isin'); - const firstBarDate = validateNullableDate(raw.firstBarDate, 'firstBarDate'); - const rawLastBarDate = validateNullableDate(raw.lastBarDate, 'lastBarDate'); - const rawDelistedAt = validateNullableDate(raw.delistedAt, 'delistedAt'); - - if (firstBarDate !== null && firstBarDate > vaultCutoffDate) { - return null; - } - - const lastBarDate = - rawLastBarDate !== null && rawLastBarDate > vaultCutoffDate ? vaultCutoffDate : rawLastBarDate; - - const delistedAt = - rawDelistedAt !== null && rawDelistedAt > vaultCutoffDate ? null : rawDelistedAt; - - if (!includeDelisted && delistedAt !== null) { - return null; - } - - return { - listingId, - instrumentId, - ticker, - classSuffix, - name, - mic, - currency, - isin, - firstBarDate, - lastBarDate, - delistedAt, - }; -} - -function matchRank(row: SymbolSearchRow, normalizedQuery: string): number | null { - const normalizedTicker = row.ticker.toLowerCase(); - if (normalizedTicker === normalizedQuery) { - return 0; - } - if (normalizedTicker.startsWith(normalizedQuery)) { - return 1; - } - if (row.name.toLowerCase().includes(normalizedQuery)) { - return 2; - } - return null; -} - -function validateFactoryOptions(options: SearchSymbolsToolOptions): number { - if (typeof options !== 'object' || options === null) { - throw new MarketDataStoreValidationError( - 'Invalid `options`: expected a SearchSymbolsToolOptions object.', - 'options' - ); - } - - if ( - typeof options.port !== 'object' || - options.port === null || - typeof options.port.searchSymbols !== 'function' - ) { - throw new MarketDataStoreValidationError( - 'Invalid `port`: expected a SymbolSearchPort implementing `searchSymbols`.', - 'port' - ); - } - - return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs); -} - -/** - * Creates the Vault-fenced `search_symbols` MCP tool backed by an injected - * read-only {@link SymbolSearchPort}. - * - * Enforces `scope: 'vault_fenced'`, requests candidates with - * `includeDelisted: true` so current delisting status cannot hide listings that - * were active as of the Vault cutoff, drops post-cutoff listings, clamps - * `lastBarDate` and masks future `delistedAt` against the cutoff UTC calendar - * date, ranks deterministically (exact ticker > ticker prefix > company name, - * breaking ties by ascending `listingId`), and caps results at `limit`. - */ -export function createSearchSymbolsTool(options: SearchSymbolsToolOptions): McpToolEntry { - const vaultCutoffTs = validateFactoryOptions(options); - const vaultCutoffDate = utcDateOf(vaultCutoffTs); - const { port } = options; - - return defineMcpTool({ - name: 'search_symbols', - description: - 'Search Vault-fenced security-master listings by ticker symbol or company name and return numeric listing IDs.', - inputSchema: searchSymbolsInputSchema, - async handler(input: SearchSymbolsInput): Promise { - const candidates = await port.searchSymbols({ - query: input.query, - limit: input.limit, - ...(input.country !== undefined ? { country: input.country } : {}), - includeDelisted: true, - vaultCutoffTs, - }); - - if (!Array.isArray(candidates)) { - throw new Error('Invalid symbol search response returned by port.'); - } - - const normalizedQuery = input.query.toLowerCase(); - const eligible: { readonly row: SymbolSearchRow; readonly rank: number }[] = []; - - for (let i = 0; i < candidates.length; i += 1) { - const fenced = fenceAndProjectRow( - candidates[i] as SymbolSearchRow, - vaultCutoffDate, - input.includeDelisted - ); - if (fenced !== null) { - const rank = matchRank(fenced, normalizedQuery); - if (rank !== null) { - eligible.push({ row: fenced, rank }); - } - } - } - - eligible.sort((a, b) => { - if (a.rank !== b.rank) { - return a.rank - b.rank; - } - return a.row.listingId - b.row.listingId; - }); - - const truncated = eligible.length > input.limit; - const limitCount = truncated ? input.limit : eligible.length; - const rows: SymbolSearchRow[] = []; - for (let i = 0; i < limitCount; i += 1) { - rows.push((eligible[i] as { readonly row: SymbolSearchRow }).row); - } - - const payload: SearchSymbolsResultPayload = { - scope: 'vault_fenced', - vaultCutoffTs, - rowCount: rows.length, - truncated, - rows, - }; - - return { - content: [{ type: 'text', text: JSON.stringify(payload) }], - }; - }, - }); -} diff --git a/libs/research/src/mcp/tools/vault-fenced-input.ts b/libs/research/src/mcp/tools/vault-fenced-input.ts deleted file mode 100644 index 3eaa97c7..00000000 --- a/libs/research/src/mcp/tools/vault-fenced-input.ts +++ /dev/null @@ -1,341 +0,0 @@ -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 = new Set([ - 'from', - 'to', - 'asOf', - 'date', - 'ref', - 'listingIds', - 'timeframe', - 'adjustment', - 'scope', - 'limit', -]); - -const SAFE_STORE_METHODS: ReadonlySet = new Set([ - 'bars', - 'crossSection', - 'fundamentalsAsOf', - 'events', - 'shortsAsOf', - 'macroAsOf', - 'fx', - 'universe', -]); - -const ADJ_SNAPSHOT_ERROR_MESSAGES: Readonly> = { - missing_snapshot: - 'Adjusted bars require a verified point-in-time fenced adj_factors snapshot.', - missing_metadata: 'Required adj_factors snapshot metadata is missing.', - invalid_metadata: 'adj_factors snapshot metadata is invalid.', - unsupported_version: 'adj_factors snapshot metadata version is unsupported.', - retrospective_rejected: - 'Retrospective adj_factors snapshots are rejected for point-in-time queries.', - incompatible_fence: - 'adj_factors snapshot fence does not match the query asOf or Vault cutoff.', - path_mismatch: 'adj_factors snapshot metadata does not match the configured artifact.', - unpinned_mutable_path: - 'Adjusted bars require a pinned or immutable adj_factors snapshot artifact.', -}; - -/** - * Maps known `MarketDataStore` / Vault domain errors to fixed, sanitized - * `isError: true` MCP tool results without leaking SQL, file paths, or URIs. - */ -export function formatMappedStoreError(err: unknown): McpToolCallResult | null { - if (err instanceof VaultHoldoutFenceError) { - return { - content: [ - { - type: 'text', - text: 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.', - }, - ], - isError: true, - }; - } - - if (err instanceof VaultScopeNotAuthorizedError) { - return { - content: [ - { - type: 'text', - text: "VaultScopeNotAuthorizedError: Data scope 'vault_evaluation_only' is not permitted through MCP.", - }, - ], - isError: true, - }; - } - - if (err instanceof MarketDataStoreValidationError) { - const text = - err.field !== undefined && SAFE_VALIDATION_FIELDS.has(err.field) - ? `MarketDataStoreValidationError: Invalid query parameter "${err.field}".` - : 'MarketDataStoreValidationError: Query parameters failed store validation.'; - return { - content: [{ type: 'text', text }], - isError: true, - }; - } - - if (err instanceof MarketDataStoreNotImplementedError) { - const text = SAFE_STORE_METHODS.has(err.method) - ? `MarketDataStoreNotImplementedError: Store operation "${err.method}" is not supported for this query.` - : 'MarketDataStoreNotImplementedError: Requested store operation is not supported.'; - return { - content: [{ type: 'text', text }], - isError: true, - }; - } - - if (err instanceof AdjFactorsSnapshotError) { - const detail = Object.prototype.hasOwnProperty.call(ADJ_SNAPSHOT_ERROR_MESSAGES, err.code) - ? ADJ_SNAPSHOT_ERROR_MESSAGES[err.code] - : 'Adjusted bars snapshot verification failed.'; - return { - content: [{ type: 'text', text: `AdjFactorsSnapshotError: ${detail}` }], - isError: true, - }; - } - - return null; -} diff --git a/libs/research/src/sha256.ts b/libs/research/src/sha256.ts deleted file mode 100644 index d4c6febc..00000000 --- a/libs/research/src/sha256.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Browser-safe, dependency-free FIPS 180-4 SHA-256 hex digest helper. - * - * Internal module shared by `trial-ledger.ts` and `feature-library.ts`. - */ - -// FIPS 180-4 SHA-256 round constants. -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, -]); - -const UTF8_ENCODER = new TextEncoder(); - -export function sha256HexUtf8(text: string): string { - const bytes = UTF8_ENCODER.encode(text); - const byteLen = bytes.length; - const paddedLen = (((byteLen + 9 + 63) >> 6) << 6) >>> 0; - const buffer = new Uint8Array(paddedLen); - buffer.set(bytes); - buffer[byteLen] = 0x80; - - const view = new DataView(buffer.buffer); - const bitLenHigh = Math.floor((byteLen * 8) / 0x1_0000_0000); - const bitLenLow = (byteLen * 8) >>> 0; - view.setUint32(paddedLen - 8, bitLenHigh, false); - view.setUint32(paddedLen - 4, bitLenLow, false); - - let h0 = 0x6a09e667; - let h1 = 0xbb67ae85; - let h2 = 0x3c6ef372; - let h3 = 0xa54ff53a; - let h4 = 0x510e527f; - let h5 = 0x9b05688c; - let h6 = 0x1f83d9ab; - let h7 = 0x5be0cd19; - - const w = new Uint32Array(64); - - for (let offset = 0; offset < paddedLen; offset += 64) { - for (let i = 0; i < 16; i += 1) { - w[i] = view.getUint32(offset + i * 4, false); - } - for (let i = 16; i < 64; i += 1) { - const w15 = w[i - 15] as number; - const w2 = w[i - 2] as number; - const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3); - const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10); - w[i] = (((w[i - 16] as number) + s0 + (w[i - 7] as number) + s1) | 0) >>> 0; - } - - let a = h0; - let b = h1; - let c = h2; - let d = h3; - let e = h4; - let f = h5; - let g = h6; - let h = h7; - - for (let i = 0; i < 64; i += 1) { - const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); - const ch = (e & f) ^ (~e & g); - const temp1 = (h + s1 + ch + (SHA256_K[i] as number) + (w[i] as number)) | 0; - const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); - const maj = (a & b) ^ (a & c) ^ (b & c); - const temp2 = (s0 + maj) | 0; - - h = g; - g = f; - f = e; - e = (d + temp1) | 0; - d = c; - c = b; - b = a; - a = (temp1 + temp2) | 0; - } - - h0 = (h0 + a) >>> 0; - h1 = (h1 + b) >>> 0; - h2 = (h2 + c) >>> 0; - h3 = (h3 + d) >>> 0; - h4 = (h4 + e) >>> 0; - h5 = (h5 + f) >>> 0; - h6 = (h6 + g) >>> 0; - h7 = (h7 + h) >>> 0; - } - - return ( - h0.toString(16).padStart(8, '0') + - h1.toString(16).padStart(8, '0') + - h2.toString(16).padStart(8, '0') + - h3.toString(16).padStart(8, '0') + - h4.toString(16).padStart(8, '0') + - h5.toString(16).padStart(8, '0') + - h6.toString(16).padStart(8, '0') + - h7.toString(16).padStart(8, '0') - ); -} diff --git a/libs/research/src/trial-ledger.ts b/libs/research/src/trial-ledger.ts index fedddfbc..bc89a636 100644 --- a/libs/research/src/trial-ledger.ts +++ b/libs/research/src/trial-ledger.ts @@ -18,7 +18,6 @@ import { VaultHoldoutFenceError, applyVaultFence, } from './market-data-store'; -import { sha256HexUtf8 } from './sha256'; export const TRIAL_STAGES = ['signal_ic', 'event_study', 'screen', 'engine_backtest'] as const; export type TrialStage = (typeof TRIAL_STAGES)[number]; @@ -223,6 +222,106 @@ const SELECT_TRIAL_COLUMNS = ` kurtosis, daily_series`; +// FIPS 180-4 SHA-256 round constants. +const SHA256_K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]); + +const UTF8_ENCODER = new TextEncoder(); + +function sha256HexUtf8(text: string): string { + const bytes = UTF8_ENCODER.encode(text); + const byteLen = bytes.length; + const paddedLen = (((byteLen + 9 + 63) >> 6) << 6) >>> 0; + const buffer = new Uint8Array(paddedLen); + buffer.set(bytes); + buffer[byteLen] = 0x80; + + const view = new DataView(buffer.buffer); + const bitLenHigh = Math.floor((byteLen * 8) / 0x1_0000_0000); + const bitLenLow = (byteLen * 8) >>> 0; + view.setUint32(paddedLen - 8, bitLenHigh, false); + view.setUint32(paddedLen - 4, bitLenLow, false); + + let h0 = 0x6a09e667; + let h1 = 0xbb67ae85; + let h2 = 0x3c6ef372; + let h3 = 0xa54ff53a; + let h4 = 0x510e527f; + let h5 = 0x9b05688c; + let h6 = 0x1f83d9ab; + let h7 = 0x5be0cd19; + + const w = new Uint32Array(64); + + for (let offset = 0; offset < paddedLen; offset += 64) { + for (let i = 0; i < 16; i += 1) { + w[i] = view.getUint32(offset + i * 4, false); + } + for (let i = 16; i < 64; i += 1) { + const w15 = w[i - 15] as number; + const w2 = w[i - 2] as number; + const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3); + const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10); + w[i] = (((w[i - 16] as number) + s0 + (w[i - 7] as number) + s1) | 0) >>> 0; + } + + let a = h0; + let b = h1; + let c = h2; + let d = h3; + let e = h4; + let f = h5; + let g = h6; + let h = h7; + + for (let i = 0; i < 64; i += 1) { + const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); + const ch = (e & f) ^ (~e & g); + const temp1 = (h + s1 + ch + (SHA256_K[i] as number) + (w[i] as number)) | 0; + const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); + const maj = (a & b) ^ (a & c) ^ (b & c); + const temp2 = (s0 + maj) | 0; + + h = g; + g = f; + f = e; + e = (d + temp1) | 0; + d = c; + c = b; + b = a; + a = (temp1 + temp2) | 0; + } + + h0 = (h0 + a) >>> 0; + h1 = (h1 + b) >>> 0; + h2 = (h2 + c) >>> 0; + h3 = (h3 + d) >>> 0; + h4 = (h4 + e) >>> 0; + h5 = (h5 + f) >>> 0; + h6 = (h6 + g) >>> 0; + h7 = (h7 + h) >>> 0; + } + + return ( + h0.toString(16).padStart(8, '0') + + h1.toString(16).padStart(8, '0') + + h2.toString(16).padStart(8, '0') + + h3.toString(16).padStart(8, '0') + + h4.toString(16).padStart(8, '0') + + h5.toString(16).padStart(8, '0') + + h6.toString(16).padStart(8, '0') + + h7.toString(16).padStart(8, '0') + ); +} + function compareAscii(a: string, b: string): number { return a < b ? -1 : a > b ? 1 : 0; } diff --git a/libs/research/test/feature-library.test.ts b/libs/research/test/feature-library.test.ts deleted file mode 100644 index 9315471d..00000000 --- a/libs/research/test/feature-library.test.ts +++ /dev/null @@ -1,1616 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - type DuckDbExecutor, - type DuckDbParam, - FEATURE_FAMILIES, - FEATURE_INPUT_DATASETS, - FEATURE_KINDS, - FEATURE_KNOWN_AT_RULES, - FEATURE_OUTPUT_COLUMNS, - type FeatureDefinition, - FeatureLibraryError, - type FeatureLibraryErrorCode, - RET_1D_V1, - type TableRow, - createFeatureRegistry, - featureDefinitionHash, - featureRef, - parseFeatureRef, - planFeatureBatch, - runFeatureBatch, - validateFeatureDefinition, -} from '@stock-bot/research'; -import { - FEATURE_FAMILIES as subpathFeatureFamilies, - FEATURE_INPUT_DATASETS as subpathFeatureInputDatasets, - FEATURE_KINDS as subpathFeatureKinds, - FEATURE_KNOWN_AT_RULES as subpathFeatureKnownAtRules, - FEATURE_OUTPUT_COLUMNS as subpathFeatureOutputColumns, - FeatureLibraryError as SubpathFeatureLibraryError, - RET_1D_V1 as subpathRet1dV1, - createFeatureRegistry as subpathCreateFeatureRegistry, - featureDefinitionHash as subpathFeatureDefinitionHash, - featureRef as subpathFeatureRef, - parseFeatureRef as subpathParseFeatureRef, - planFeatureBatch as subpathPlanFeatureBatch, - runFeatureBatch as subpathRunFeatureBatch, - validateFeatureDefinition as subpathValidateFeatureDefinition, -} from '@stock-bot/research/feature-library'; - -interface RecordedQuery { - readonly sql: string; - readonly params: readonly DuckDbParam[]; -} - -interface RecordingFakeExecutor { - readonly executor: DuckDbExecutor; - readonly calls: RecordedQuery[]; - readonly runCalls: string[]; -} - -function createRecordingFakeExecutor(opts?: { - onQuery?: (sql: string, params: readonly DuckDbParam[], callIndex: number) => Promise | void; -}): RecordingFakeExecutor { - const calls: RecordedQuery[] = []; - const runCalls: string[] = []; - - const executor: DuckDbExecutor = { - async run(sql: string): Promise { - runCalls.push(sql); - }, - async query(sql: string, params: readonly DuckDbParam[]): Promise { - const idx = calls.length; - calls.push({ sql, params: [...params] }); - if (opts?.onQuery !== undefined) { - await opts.onQuery(sql, params, idx); - } - return []; - }, - }; - - return { executor, calls, runCalls }; -} - -function expectFeatureErrorCode(fn: () => unknown, expectedCode: FeatureLibraryErrorCode): FeatureLibraryError { - try { - fn(); - } catch (error) { - expect(error).toBeInstanceOf(FeatureLibraryError); - const typed = error as FeatureLibraryError; - expect(typed.code).toBe(expectedCode); - return typed; - } - throw new Error(`Expected FeatureLibraryError(${expectedCode}) to be thrown, but succeeded.`); -} - -function makeSimpleDef(overrides: Partial = {}): FeatureDefinition { - return { - name: 'close_raw', - version: 1, - family: 'technical', - kind: 'duckdb_sql', - inputs: ['bars_1d'], - warmupBars: 0, - knownAtRule: 'bar_close', - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - ...overrides, - }; -} - -describe('feature-library barrel and subpath exports', () => { - it('exposes identical symbols from @stock-bot/research and @stock-bot/research/feature-library', () => { - expect(FEATURE_FAMILIES).toBe(subpathFeatureFamilies); - expect(FEATURE_INPUT_DATASETS).toBe(subpathFeatureInputDatasets); - expect(FEATURE_KINDS).toBe(subpathFeatureKinds); - expect(FEATURE_KNOWN_AT_RULES).toBe(subpathFeatureKnownAtRules); - expect(FEATURE_OUTPUT_COLUMNS).toBe(subpathFeatureOutputColumns); - expect(FeatureLibraryError).toBe(SubpathFeatureLibraryError); - expect(RET_1D_V1).toBe(subpathRet1dV1); - expect(createFeatureRegistry).toBe(subpathCreateFeatureRegistry); - expect(featureDefinitionHash).toBe(subpathFeatureDefinitionHash); - expect(featureRef).toBe(subpathFeatureRef); - expect(parseFeatureRef).toBe(subpathParseFeatureRef); - expect(planFeatureBatch).toBe(subpathPlanFeatureBatch); - expect(runFeatureBatch).toBe(subpathRunFeatureBatch); - expect(validateFeatureDefinition).toBe(subpathValidateFeatureDefinition); - }); -}); - -describe('featureRef and parseFeatureRef', () => { - it('round-trips canonical refs such as ret_1d@v1', () => { - const ref = featureRef(RET_1D_V1); - expect(ref).toBe('ret_1d@v1'); - expect(parseFeatureRef(ref)).toEqual({ name: 'ret_1d', version: 1 }); - expect(parseFeatureRef('rsi_14@v12')).toEqual({ name: 'rsi_14', version: 12 }); - }); - - it('rejects malformed, non-canonical, and unsafe refs', () => { - const invalidRefs = [ - '', - 'ret_1d', - 'ret_1d@1', - 'ret_1d@v0', - 'ret_1d@v01', - 'ret_1d@v-1', - 'ret_1d@v1.5', - 'RSI-14@v1', - '1abc@v1', - `${'a'.repeat(64)}@v1`, - 'ret_1d@v9007199254740992', - ]; - for (const bad of invalidRefs) { - expectFeatureErrorCode(() => parseFeatureRef(bad), 'INVALID_FEATURE_REF'); - } - expectFeatureErrorCode(() => parseFeatureRef(null as unknown as string), 'INVALID_FEATURE_REF'); - expectFeatureErrorCode(() => featureRef({ name: 'RSI-14', version: 1 }), 'INVALID_NAME'); - expectFeatureErrorCode(() => featureRef({ name: 'ret_1d', version: 0 }), 'INVALID_VERSION'); - expectFeatureErrorCode(() => featureRef({ name: 'ret_1d', version: 1.5 }), 'INVALID_VERSION'); - expectFeatureErrorCode( - () => featureRef({ name: 'ret_1d', version: Number.MAX_SAFE_INTEGER + 1 }), - 'INVALID_VERSION' - ); - }); -}); - -describe('validateFeatureDefinition', () => { - it('accepts RET_1D_V1, CTE + window expressions, subqueries, and multi-input joins', () => { - expect(() => validateFeatureDefinition(RET_1D_V1)).not.toThrow(); - - const joinedDef: FeatureDefinition = { - name: 'cad_scaled_close', - version: 1, - family: 'fx', - kind: 'duckdb_sql', - inputs: ['bars_1d', 'fx_1d'], - warmupBars: 0, - knownAtRule: 'max_input_known_at', - sql: ` - WITH base AS ( - SELECT b.listing_id, b.ts, b.session_date, b.close, b.known_at - FROM {{input:bars_1d}} AS b - ) - SELECT - base.listing_id, - base.ts, - GREATEST(base.known_at, f.known_at) AS known_at, - base.close / f.close AS value - FROM base - INNER JOIN ( - SELECT session_date, close, known_at - FROM {{input:fx_1d}} - WHERE pair = 'USDCAD' - ) AS f ON base.session_date = f.session_date - `, - }; - expect(() => validateFeatureDefinition(joinedDef)).not.toThrow(); - - // Two-input join using LEFT(...) and RIGHT(...) string functions in the ON predicate, - // followed immediately by a real LEFT JOIN to verify join-boundary detection. - const leftInJoinOnDef: FeatureDefinition = { - name: 'fx_base_ccy_close', - version: 1, - family: 'fx', - kind: 'duckdb_sql', - inputs: ['bars_1d', 'fx_1d'], - warmupBars: 0, - knownAtRule: 'max_input_known_at', - sql: ` - SELECT - b.listing_id, - b.ts, - GREATEST(b.known_at, f.known_at) AS known_at, - b.close / COALESCE(f2.close, f.close) AS value - FROM {{input:bars_1d}} AS b - INNER JOIN {{input:fx_1d}} AS f - ON b.session_date = f.session_date - AND b.currency = LEFT(f.pair, 3) - AND RIGHT(f.pair, 3) = 'USD' - LEFT JOIN {{input:fx_1d}} AS f2 - ON b.session_date = f2.session_date - AND f2.pair = 'USDCAD' - WHERE f.close > 0 - `, - }; - expect(() => validateFeatureDefinition(leftInJoinOnDef)).not.toThrow(); - - // Valid compound subquery with parenthesized branches referencing declared inputs, - // and scalar subquery inside parenthesized arithmetic. - const compoundExistsDef: FeatureDefinition = { - name: 'eligible_close', - version: 1, - family: 'event', - kind: 'duckdb_sql', - inputs: ['bars_1d', 'events'], - warmupBars: 0, - knownAtRule: 'max_input_known_at', - sql: ` - SELECT - b.listing_id, - b.ts, - b.known_at, - b.close AS value - FROM {{input:bars_1d}} AS b - WHERE EXISTS ( - (SELECT 1 FROM {{input:bars_1d}} AS b2 WHERE b2.listing_id = b.listing_id) - UNION ALL - (SELECT 1 FROM {{input:events}} AS e WHERE e.listing_id = b.listing_id) - ) - AND ((SELECT MAX(close) FROM {{input:bars_1d}}) + 1) > b.close - `, - }; - expect(() => validateFeatureDefinition(compoundExistsDef)).not.toThrow(); - }); - - it('rejects invalid names, versions, families, kinds, warmupBars, and knownAtRule', () => { - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: 'RSI-14' })), 'INVALID_NAME'); - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: '' })), 'INVALID_NAME'); - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ name: '1ret' })), 'INVALID_NAME'); - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ name: 'a'.repeat(64) })), - 'INVALID_NAME' - ); - - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: 0 })), 'INVALID_VERSION'); - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: -2 })), 'INVALID_VERSION'); - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ version: 1.5 })), 'INVALID_VERSION'); - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ version: Number.NaN })), - 'INVALID_VERSION' - ); - - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ family: 'macro' as FeatureDefinition['family'] })), - 'INVALID_FAMILY' - ); - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ kind: 'polars' as FeatureDefinition['kind'] })), - 'INVALID_KIND' - ); - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ warmupBars: -1 })), - 'INVALID_WARMUP_BARS' - ); - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ warmupBars: 0.5 })), - 'INVALID_WARMUP_BARS' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ knownAtRule: 'end_of_month' as FeatureDefinition['knownAtRule'] }) - ), - 'INVALID_KNOWN_AT_RULE' - ); - }); - - it('rejects empty SQL, semicolons/multi-statement SQL, comments, bind markers, and malformed placeholders', () => { - expectFeatureErrorCode(() => validateFeatureDefinition(makeSimpleDef({ sql: ' ' })), 'INVALID_SQL_STATEMENT'); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}; SELECT 1', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} -- comment', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: '/* block */ SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > ?', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > $1', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE close > :min_close', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{bad:bars_1d}}', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - }); - - it('rejects prohibited DDL/DML/admin SQL commands with PROHIBITED_SQL_OPERATION', () => { - const prohibitedSqls = [ - "COPY (SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}) TO '/tmp/out.parquet'", - "ATTACH '/tmp/evil.db' AS evil", - 'INSERT INTO t VALUES (1)', - 'CREATE TABLE t (x INT)', - 'PRAGMA database_list', - "SET memory_limit = '100GB'", - 'INSTALL httpfs', - 'LOAD httpfs', - 'DROP TABLE bars_1d', - 'DELETE FROM bars_1d', - 'UPDATE bars_1d SET close = 0', - ]; - for (const sql of prohibitedSqls) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ sql })), - 'PROHIBITED_SQL_OPERATION' - ); - } - }); - - it('rejects direct/mixed-case readers, quoted paths, catalog relations, table functions, and disallowed functions', () => { - const externalSqls = [ - "SELECT listing_id, ts, ts AS known_at, close AS value FROM read_parquet('/etc/x')", - "SELECT listing_id, ts, ts AS known_at, close AS value FROM ReAd_PaRqUeT('/etc/x.parquet')", - "SELECT listing_id, ts, ts AS known_at, close AS value FROM read_csv('/tmp/a.csv')", - "SELECT listing_id, ts, ts AS known_at, close AS value FROM glob('/mnt/*')", - "SELECT listing_id, ts, ts AS known_at, close AS value FROM '/etc/x.parquet'", - "SELECT listing_id, ts, ts AS known_at, '/etc/passwd' AS value FROM {{input:bars_1d}}", - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM information_schema.tables', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM pg_catalog.pg_tables', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM raw_table_not_a_cte', - "SELECT listing_id, ts, ts AS known_at, getenv('HOME') AS value FROM {{input:bars_1d}}", - 'SELECT listing_id, ts, ts AS known_at, custom_evil_fn(close) AS value FROM {{input:bars_1d}}', - ]; - for (const sql of externalSqls) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ sql })), - 'EXTERNAL_DATA_ACCESS' - ); - } - - // Reject DuckDB FROM-first and TABLE subqueries inside expressions so catalog tables cannot bypass allow-list checks. - const unsupportedSubqueries = [ - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS (FROM secret_table)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((FROM secret_table))', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE listing_id IN (FROM secret_table SELECT listing_id)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS (TABLE secret_table)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) UNION ALL FROM staging_eligibility)', - ]; - for (const sql of unsupportedSubqueries) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ sql })), - 'INVALID_SQL_STATEMENT' - ); - } - - // Reject compound subqueries with a parenthesized first branch when any later branch references an unauthorized relation. - const compoundBypassSubqueries = [ - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) UNION ALL SELECT 1 FROM staging_eligibility)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) UNION ALL (SELECT 1 FROM staging_eligibility))', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) INTERSECT SELECT 1 FROM staging_eligibility)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS ((SELECT 1 FROM {{input:bars_1d}}) EXCEPT SELECT 1 FROM staging_eligibility)', - 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}} WHERE EXISTS (((SELECT 1 FROM {{input:bars_1d}}) UNION ALL SELECT 1 FROM staging_eligibility))', - ]; - for (const sql of compoundBypassSubqueries) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ sql })), - 'EXTERNAL_DATA_ACCESS' - ); - } - }); - - it('rejects incorrect final projections with INVALID_SQL_PROJECTION', () => { - const badProjections = [ - 'SELECT * FROM {{input:bars_1d}}', - 'SELECT listing_id, ts, close AS value FROM {{input:bars_1d}}', - 'SELECT listing_id, ts, ts AS known_at, close AS value, volume AS extra FROM {{input:bars_1d}}', - 'SELECT ts, listing_id, ts AS known_at, close AS value FROM {{input:bars_1d}}', - 'SELECT listing_id, ts, ts AS known_at, close AS ret FROM {{input:bars_1d}}', - 'SELECT listing_id, ts, ts AS known_at, close + 1 FROM {{input:bars_1d}}', - ]; - for (const sql of badProjections) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ sql })), - 'INVALID_SQL_PROJECTION' - ); - } - }); - - it('rejects unsupported, undeclared, and unused input datasets with distinct codes', () => { - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - inputs: ['macro' as FeatureDefinition['inputs'][number]], - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:macro}}', - }) - ), - 'UNSUPPORTED_INPUT_DATASET' - ); - - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - inputs: ['bars_1d'], - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:events}} AS e ON b.listing_id = e.listing_id', - }) - ), - 'UNDECLARED_INPUT' - ); - - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - inputs: ['bars_1d', 'fx_1d'], - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - }) - ), - 'UNUSED_INPUT' - ); - }); -}); - -describe('featureDefinitionHash', () => { - it('is stable across inter-token whitespace, object key order, input order, and metadata', () => { - const defA: FeatureDefinition = { - name: 'fx_ratio', - version: 1, - family: 'fx', - kind: 'duckdb_sql', - inputs: ['fx_1d', 'bars_1d'], - warmupBars: 2, - knownAtRule: 'max_input_known_at', - description: 'First description', - sql: "SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date WHERE f.pair = 'USD CAD'", - }; - - const defB: FeatureDefinition = { - sql: [ - 'SELECT', - ' b.listing_id,', - ' b.ts,', - ' GREATEST(b.known_at, f.known_at) AS known_at,', - ' b.close / f.close AS value', - 'FROM {{input:bars_1d}} AS b', - 'INNER JOIN {{input:fx_1d}} AS f', - ' ON b.session_date = f.session_date', - "WHERE f.pair = 'USD CAD'", - ].join('\n\t'), - knownAtRule: 'max_input_known_at', - warmupBars: 2, - inputs: ['bars_1d', 'fx_1d'], - kind: 'duckdb_sql', - family: 'technical', - version: 1, - name: 'fx_ratio', - description: 'Different metadata description', - }; - - const hashA = featureDefinitionHash(defA); - const hashB = featureDefinitionHash(defB); - expect(hashA).toMatch(/^[0-9a-f]{64}$/); - expect(hashA).toBe(hashB); - }); - - it('changes when string literal whitespace, SQL semantics, inputs, warmupBars, or knownAtRule change', () => { - const base = makeSimpleDef({ - sql: "SELECT listing_id, ts, ts AS known_at, CASE WHEN currency = 'US D' THEN close ELSE 0.0 END AS value FROM {{input:bars_1d}}", - }); - const baseHash = featureDefinitionHash(base); - - // Whitespace inside string literal changes hash. - const changedLiteral = makeSimpleDef({ - sql: "SELECT listing_id, ts, ts AS known_at, CASE WHEN currency = 'US D' THEN close ELSE 0.0 END AS value FROM {{input:bars_1d}}", - }); - expect(featureDefinitionHash(changedLiteral)).not.toBe(baseHash); - - // Substantive SQL change. - const changedSql = makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, open AS value FROM {{input:bars_1d}}', - }); - expect(featureDefinitionHash(changedSql)).not.toBe(baseHash); - - // Valid input dataset change. - const changedInput = makeSimpleDef({ - inputs: ['events'], - sql: 'SELECT listing_id, ts, known_at, 1.0 AS value FROM {{input:events}}', - }); - expect(featureDefinitionHash(changedInput)).not.toBe(baseHash); - - // warmupBars change. - expect(featureDefinitionHash({ ...base, warmupBars: 5 })).not.toBe(baseHash); - - // knownAtRule change. - expect(featureDefinitionHash({ ...base, knownAtRule: 'source_known_at' })).not.toBe(baseHash); - }); -}); - -describe('createFeatureRegistry', () => { - it('supports idempotent re-registration, enforces FEATURE_VERSION_IMMUTABLE, allows version bumps, and isolates mutations', () => { - const registry = createFeatureRegistry(); - const mutableInputs: FeatureDefinition['inputs'][number][] = ['bars_1d']; - const initial: FeatureDefinition = { - ...RET_1D_V1, - inputs: mutableInputs, - }; - - const first = registry.registerSignal(initial); - expect(first.ref).toBe('ret_1d@v1'); - expect(first.definitionHash).toBe(featureDefinitionHash(RET_1D_V1)); - - // Mutate caller input after registration; stored definition must be unaffected. - mutableInputs.push('fx_1d'); - expect(registry.get('ret_1d@v1')?.inputs).toEqual(['bars_1d']); - - // Idempotent re-registration with whitespace-only SQL difference. - const sameSemantic: FeatureDefinition = { - ...RET_1D_V1, - sql: RET_1D_V1.sql.replace(/\n/g, ' '), - description: 'Updated description ignored for hash', - }; - const second = registry.registerSignal(sameSemantic); - expect(second.definitionHash).toBe(first.definitionHash); - expect(registry.list()).toEqual(['ret_1d@v1']); - - // Semantic changes at v1 must throw FEATURE_VERSION_IMMUTABLE. - const changedSql: FeatureDefinition = { - ...RET_1D_V1, - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - }; - const errSql = expectFeatureErrorCode( - () => registry.registerSignal(changedSql), - 'FEATURE_VERSION_IMMUTABLE' - ); - expect(errSql.ref).toBe('ret_1d@v1'); - - const changedInputs: FeatureDefinition = { - ...RET_1D_V1, - inputs: ['bars_1d', 'fx_1d'], - sql: 'SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date', - }; - expectFeatureErrorCode( - () => registry.registerSignal(changedInputs), - 'FEATURE_VERSION_IMMUTABLE' - ); - - expectFeatureErrorCode( - () => registry.registerSignal({ ...RET_1D_V1, warmupBars: 2 }), - 'FEATURE_VERSION_IMMUTABLE' - ); - - expectFeatureErrorCode( - () => registry.registerSignal({ ...RET_1D_V1, knownAtRule: 'source_known_at' }), - 'FEATURE_VERSION_IMMUTABLE' - ); - - // Same change under version 2 succeeds and both refs are listed. - const v2 = registry.registerSignal({ ...changedSql, version: 2 }); - expect(v2.ref).toBe('ret_1d@v2'); - expect(registry.list()).toEqual(['ret_1d@v1', 'ret_1d@v2']); - expect(registry.get('ret_1d@v2')?.version).toBe(2); - expect(registry.get('missing@v1')).toBeUndefined(); - - // Mutating returned list array does not affect registry. - const listed = registry.list() as string[]; - listed.push('evil@v99'); - expect(registry.list()).toEqual(['ret_1d@v1', 'ret_1d@v2']); - }); -}); - -describe('planFeatureBatch', () => { - it('plans 3 yearly Parquet COPY statements for RET_1D_V1 across 2020–2022', () => { - const writes = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2022, - vaultCutoffDate: '2025-06-01', - }); - - expect(writes).toHaveLength(3); - expect(writes.map(w => w.year)).toEqual([2020, 2021, 2022]); - expect(writes.map(w => w.outputPath)).toEqual([ - '/c/features/ret_1d/v1/year=2020/part.parquet', - '/c/features/ret_1d/v1/year=2021/part.parquet', - '/c/features/ret_1d/v1/year=2022/part.parquet', - ]); - - for (const write of writes) { - expect(write.sql).toStartWith( - 'COPY (SELECT listing_id, ts, known_at, value ' + - 'FROM (SELECT CAST(listing_id AS INTEGER) AS listing_id, CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, CAST(value AS DOUBLE) AS value FROM (' - ); - expect(write.sql).toContain( - "read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?" - ); - expect(write.sql).toContain( - ') AS __feature_source) AS __feature_typed WHERE year(ts) = ? AND ts <= ? AND known_at <= ? ORDER BY listing_id, ts)' - ); - expect(write.sql).toEndWith( - `TO '${write.outputPath}' (FORMAT PARQUET, COMPRESSION ZSTD)` - ); - const expectedTsEnd = `${write.year}-12-31T23:59:59.999999Z`; - const expectedKnownAtCeiling = '2025-05-31T23:59:59.999999Z'; - expect(write.params).toEqual([ - expectedTsEnd, - expectedKnownAtCeiling, - write.year, - expectedTsEnd, - expectedKnownAtCeiling, - ]); - - // Verify scan predicate is embedded inside the FROM subquery of the lagged CTE - // (evaluated before LAG), timestamp casts precede the outer year/Vault filter, - // and outer year(ts) filter follows the authored query. - const castTsIdx = write.sql.indexOf('CAST(ts AS TIMESTAMPTZ) AS ts'); - const castKnownAtIdx = write.sql.indexOf('CAST(known_at AS TIMESTAMPTZ) AS known_at'); - const lagIdx = write.sql.indexOf('LAG ( close )'); - const scanIdx = write.sql.indexOf( - "FROM (SELECT * FROM read_parquet('/c/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?)" - ); - const outerYearIdx = write.sql.indexOf('WHERE year(ts) = ?'); - expect(castTsIdx).toBeGreaterThan(-1); - expect(castKnownAtIdx).toBeGreaterThan(castTsIdx); - expect(lagIdx).toBeGreaterThan(castKnownAtIdx); - expect(scanIdx).toBeGreaterThan(lagIdx); - expect(outerYearIdx).toBeGreaterThan(scanIdx); - } - - // Daily short-interest fixture projecting DATE report_date as ts still normalizes ts & known_at to TIMESTAMPTZ. - const shortsDateDef: FeatureDefinition = { - name: 'short_interest_raw', - version: 1, - family: 'event', - kind: 'duckdb_sql', - inputs: ['shorts'], - warmupBars: 0, - knownAtRule: 'source_known_at', - sql: 'SELECT listing_id, report_date AS ts, known_at, shares_short AS value FROM {{input:shorts}}', - }; - const [shortsWrite] = planFeatureBatch(shortsDateDef, { - curatedRoot: '/c', - fromYear: 2021, - toYear: 2021, - vaultCutoffDate: '2025-01-01', - }); - expect(shortsWrite?.sql).toContain( - 'SELECT CAST(listing_id AS INTEGER) AS listing_id, CAST(ts AS TIMESTAMPTZ) AS ts, CAST(known_at AS TIMESTAMPTZ) AS known_at, CAST(value AS DOUBLE) AS value FROM (' - ); - expect(shortsWrite?.sql).toContain( - ') AS __feature_source) AS __feature_typed WHERE year(ts) = ? AND ts <= ? AND known_at <= ?' - ); - }); - - it('expands all six allow-listed dataset path shapes and predicates, normalizes roots, and rejects unsafe roots', () => { - const allSixDef: FeatureDefinition = { - name: 'all_six_check', - version: 1, - family: 'fundamental', - kind: 'duckdb_sql', - inputs: ['bars_1d', 'adj_factors', 'events', 'shorts', 'fx_1d', 'fundamentals_pit'], - warmupBars: 0, - knownAtRule: 'max_input_known_at', - sql: ` - SELECT - b.listing_id, - b.ts, - GREATEST(b.known_at, a.known_at, e.known_at, s.known_at, f.known_at, p.effective_known_at) AS known_at, - b.close AS value - FROM {{input:bars_1d}} AS b - INNER JOIN {{input:adj_factors}} AS a ON b.listing_id = a.listing_id - INNER JOIN {{input:events}} AS e ON b.listing_id = e.listing_id - INNER JOIN {{input:shorts}} AS s ON b.listing_id = s.listing_id - INNER JOIN {{input:fx_1d}} AS f ON b.session_date = f.session_date - INNER JOIN {{input:fundamentals_pit}} AS p ON b.listing_id = p.listing_id - `, - }; - - const [write] = planFeatureBatch(allSixDef, { - curatedRoot: '/data///', - fromYear: 2021, - toYear: 2021, - vaultCutoffDate: '2024-01-01', - }); - expect(write).toBeDefined(); - expect(write?.outputPath).toBe('/data/features/all_six_check/v1/year=2021/part.parquet'); - expect(write?.sql).toContain( - "read_parquet('/data/bars_1d/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?" - ); - expect(write?.sql).toContain( - "read_parquet('/data/adj_factors/part.parquet') WHERE known_at <= ?" - ); - expect(write?.sql).toContain( - "read_parquet('/data/events/year=*/part.parquet', hive_partitioning = true) WHERE ts <= ? AND known_at <= ?" - ); - expect(write?.sql).toContain( - "read_parquet('/data/shorts/part.parquet') WHERE known_at <= ?" - ); - expect(write?.sql).toContain( - "read_parquet('/data/fx_1d/part.parquet') WHERE ts <= ? AND known_at <= ?" - ); - expect(write?.sql).toContain( - "read_parquet('/data/fundamentals_pit/year=*/part.parquet', hive_partitioning = true) WHERE effective_known_at <= ?" - ); - - const ts2021 = '2021-12-31T23:59:59.999999Z'; - const vaultCeiling = '2023-12-31T23:59:59.999999Z'; - expect(write?.params).toEqual([ - ts2021, - vaultCeiling, // bars_1d - vaultCeiling, // adj_factors - ts2021, - vaultCeiling, // events - vaultCeiling, // shorts - ts2021, - vaultCeiling, // fx_1d - vaultCeiling, // fundamentals_pit - 2021, - ts2021, - vaultCeiling, // outer filter - ]); - - // Root '/' normalization (no double leading slash). - const [rootWrite] = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/', - fromYear: 2020, - toYear: 2020, - vaultCutoffDate: '2025-01-01', - }); - expect(rootWrite?.outputPath).toBe('/features/ret_1d/v1/year=2020/part.parquet'); - expect(rootWrite?.sql).toContain("read_parquet('/bars_1d/year=*/part.parquet', hive_partitioning = true)"); - - // Unsafe curated roots rejected. - for (const badRoot of ['', 'relative/path', "/tmp/o'reilly", '/tmp/a;b', '/tmp/a*b', '/tmp/\n']) { - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: badRoot, - fromYear: 2020, - toYear: 2020, - vaultCutoffDate: '2025-01-01', - }), - 'INVALID_BATCH_OPTIONS' - ); - } - }); - - it('enforces Vault fence for midyear cutoff, January 1 cutoff, entirely post-cutoff ranges, and invalid options', () => { - // Midyear cutoff: 2022-06-15 -> plans 2020, 2021, 2022; clamps 2022 ts and all known_at to 2022-06-14T23:59:59.999999Z. - const midyear = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2024, - vaultCutoffDate: '2022-06-15', - }); - expect(midyear.map(w => w.year)).toEqual([2020, 2021, 2022]); - expect(midyear[2]?.params).toEqual([ - '2022-06-14T23:59:59.999999Z', - '2022-06-14T23:59:59.999999Z', - 2022, - '2022-06-14T23:59:59.999999Z', - '2022-06-14T23:59:59.999999Z', - ]); - - // January 1 cutoff: 2022-01-01 -> excludes 2022 completely. - const jan1 = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2023, - vaultCutoffDate: '2022-01-01', - }); - expect(jan1.map(w => w.year)).toEqual([2020, 2021]); - expect(jan1[1]?.params).toEqual([ - '2021-12-31T23:59:59.999999Z', - '2021-12-31T23:59:59.999999Z', - 2021, - '2021-12-31T23:59:59.999999Z', - '2021-12-31T23:59:59.999999Z', - ]); - - // Entirely held-out ranges throw VAULT_RANGE_VIOLATION. - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2023, - toYear: 2025, - vaultCutoffDate: '2022-06-15', - }), - 'VAULT_RANGE_VIOLATION' - ); - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2022, - toYear: 2022, - vaultCutoffDate: '2022-01-01', - }), - 'VAULT_RANGE_VIOLATION' - ); - - // Invalid calendar dates and year ranges throw INVALID_BATCH_OPTIONS. - for (const badDate of ['2025-02-29', '2025-13-01', '2025-04-31', '2025-06-01T00:00:00Z', 'not-a-date']) { - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2021, - vaultCutoffDate: badDate, - }), - 'INVALID_BATCH_OPTIONS' - ); - } - - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2022, - toYear: 2020, - vaultCutoffDate: '2025-01-01', - }), - 'INVALID_BATCH_OPTIONS' - ); - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 999, - toYear: 2020, - vaultCutoffDate: '2025-01-01', - }), - 'INVALID_BATCH_OPTIONS' - ); - expectFeatureErrorCode( - () => - planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2020.5, - toYear: 2021, - vaultCutoffDate: '2025-01-01', - }), - 'INVALID_BATCH_OPTIONS' - ); - }); -}); - -describe('runFeatureBatch', () => { - it('executes deterministically in sequential year order and returns a complete manifest', async () => { - const opts = { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2022, - vaultCutoffDate: '2025-06-01', - }; - - const orderLog: string[] = []; - const fakeA = createRecordingFakeExecutor({ - async onQuery(_sql, params) { - const year = params[2]; - orderLog.push(`start:${String(year)}`); - await Promise.resolve(); - orderLog.push(`end:${String(year)}`); - }, - }); - const fakeB = createRecordingFakeExecutor(); - - const manifestA = await runFeatureBatch(RET_1D_V1, opts, fakeA.executor); - const manifestB = await runFeatureBatch(RET_1D_V1, opts, fakeB.executor); - - expect(orderLog).toEqual([ - 'start:2020', - 'end:2020', - 'start:2021', - 'end:2021', - 'start:2022', - 'end:2022', - ]); - expect(fakeA.runCalls).toHaveLength(0); - expect(fakeA.calls).toEqual(fakeB.calls); - expect(manifestA).toEqual(manifestB); - expect(manifestA).toEqual({ - ref: 'ret_1d@v1', - definitionHash: featureDefinitionHash(RET_1D_V1), - knownAtRule: 'bar_close', - warmupBars: 1, - inputs: ['bars_1d'], - writes: [ - { year: 2020, outputPath: '/c/features/ret_1d/v1/year=2020/part.parquet' }, - { year: 2021, outputPath: '/c/features/ret_1d/v1/year=2021/part.parquet' }, - { year: 2022, outputPath: '/c/features/ret_1d/v1/year=2022/part.parquet' }, - ], - }); - }); - - it('stops on second-year executor error, preserves cause, and reports only first year as completed', async () => { - const rootCause = new Error('disk full on year 2021'); - const fake = createRecordingFakeExecutor({ - onQuery(_sql, _params, callIndex) { - if (callIndex === 1) { - throw rootCause; - } - }, - }); - - let caught: unknown; - try { - await runFeatureBatch( - RET_1D_V1, - { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2022, - vaultCutoffDate: '2025-06-01', - }, - fake.executor - ); - } catch (error) { - caught = error; - } - - expect(caught).toBeInstanceOf(FeatureLibraryError); - const typed = caught as FeatureLibraryError; - expect(typed.code).toBe('BATCH_WRITE_FAILED'); - expect(typed.cause).toBe(rootCause); - expect(typed.failedYear).toBe(2021); - expect(typed.completedYears).toEqual([2020]); - expect(typed.completedWrites).toEqual([ - { year: 2020, outputPath: '/c/features/ret_1d/v1/year=2020/part.parquet' }, - ]); - expect(fake.calls).toHaveLength(2); - }); - - it('issues zero executor calls when definition or batch options are invalid', async () => { - const fake = createRecordingFakeExecutor(); - let caught: unknown; - try { - await runFeatureBatch( - RET_1D_V1, - { - curatedRoot: '/c', - fromYear: 2025, - toYear: 2026, - vaultCutoffDate: '2025-01-01', - }, - fake.executor - ); - } catch (error) { - caught = error; - } - - expect(caught).toBeInstanceOf(FeatureLibraryError); - expect((caught as FeatureLibraryError).code).toBe('VAULT_RANGE_VIOLATION'); - expect(fake.calls).toHaveLength(0); - expect(fake.runCalls).toHaveLength(0); - }); - - it('snapshots definition metadata before awaiting writes so mid-run caller mutations cannot skew the manifest', async () => { - const mutableDef: { - name: string; - version: number; - family: FeatureDefinition['family']; - kind: FeatureDefinition['kind']; - inputs: FeatureDefinition['inputs'][number][]; - warmupBars: number; - knownAtRule: FeatureDefinition['knownAtRule']; - sql: string; - } = { - name: 'mutable_close', - version: 1, - family: 'technical', - kind: 'duckdb_sql', - inputs: ['bars_1d'], - warmupBars: 2, - knownAtRule: 'bar_close', - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - }; - const expectedHash = featureDefinitionHash(mutableDef); - - const fake = createRecordingFakeExecutor({ - onQuery() { - mutableDef.warmupBars = 999; - mutableDef.knownAtRule = 'source_known_at'; - mutableDef.inputs.push('fx_1d'); - }, - }); - - const manifest = await runFeatureBatch( - mutableDef, - { - curatedRoot: '/c', - fromYear: 2020, - toYear: 2021, - vaultCutoffDate: '2025-01-01', - }, - fake.executor - ); - - expect(manifest.definitionHash).toBe(expectedHash); - expect(manifest.warmupBars).toBe(2); - expect(manifest.knownAtRule).toBe('bar_close'); - expect(manifest.inputs).toEqual(['bars_1d']); - expect(manifest.writes).toHaveLength(2); - }); -}); - -describe('RET_1D_V1 economic reference check (planned SQL + hand-calculated fixture, no Parquet execution)', () => { - it('matches listing-partitioned LAG raw-close return semantics across prior-year warm-up and raw split discontinuity', () => { - // Verify SQL structure enforces listing-partitioned LAG, bar-close known_at, and positive prior close guard. - expect(RET_1D_V1.sql).toContain('LAG(close) OVER (PARTITION BY listing_id ORDER BY ts ASC) AS prev_close'); - expect(RET_1D_V1.sql).toContain('ts AS known_at'); - expect(RET_1D_V1.sql).toContain('(close / prev_close) - 1.0 AS value'); - expect(RET_1D_V1.sql).toContain('WHERE prev_close IS NOT NULL AND prev_close > 0 AND close > 0'); - - // Hand-calculated reference fixture (does not evaluate DuckDB Parquet): - // Listing 101: 2019-12-31 close 100 -> 2020-01-02 close 110 (+10%) -> 2020-01-03 2-for-1 raw split close 55 (-50% raw). - // Listing 202: 2020-01-02 close 50 (no prior close -> omitted) -> 2020-01-03 close 52 (+4%). - const bars = [ - { listing_id: 101, ts: '2019-12-31T21:00:00Z', close: 100 }, - { listing_id: 101, ts: '2020-01-02T21:00:00Z', close: 110 }, - { listing_id: 101, ts: '2020-01-03T21:00:00Z', close: 55 }, - { listing_id: 202, ts: '2020-01-02T21:00:00Z', close: 50 }, - { listing_id: 202, ts: '2020-01-03T21:00:00Z', close: 52 }, - ]; - - const lastCloseByListing = new Map(); - const targetYearRows: Array<{ listing_id: number; ts: string; known_at: string; value: number }> = []; - for (const bar of bars) { - const prevClose = lastCloseByListing.get(bar.listing_id); - lastCloseByListing.set(bar.listing_id, bar.close); - if (prevClose === undefined || prevClose <= 0 || bar.close <= 0) { - continue; - } - if (bar.ts.startsWith('2020-')) { - targetYearRows.push({ - listing_id: bar.listing_id, - ts: bar.ts, - known_at: bar.ts, - value: bar.close / prevClose - 1.0, - }); - } - } - - expect(targetYearRows).toHaveLength(3); - expect(targetYearRows[0]).toEqual({ - listing_id: 101, - ts: '2020-01-02T21:00:00Z', - known_at: '2020-01-02T21:00:00Z', - value: 0.10000000000000009, - }); - expect(targetYearRows[1]).toEqual({ - listing_id: 101, - ts: '2020-01-03T21:00:00Z', - known_at: '2020-01-03T21:00:00Z', - value: -0.5, - }); - expect(targetYearRows[2]?.listing_id).toBe(202); - expect(targetYearRows[2]?.value).toBeCloseTo(0.04, 12); - }); -}); - -describe('QA: relation-source allow-list and Vault boundary edge cases', () => { - const positionalBypassSqls = [ - // Explicit alias, then DuckDB POSITIONAL JOIN to an undeclared catalog table. - 'SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b POSITIONAL JOIN staging_tbl AS s', - // Bare alias form. - 'SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} b POSITIONAL JOIN staging_tbl s', - // Inside a CTE body. - 'WITH x AS (SELECT b.listing_id, b.ts, s.v FROM {{input:bars_1d}} AS b POSITIONAL JOIN staging_tbl AS s) SELECT listing_id, ts, ts AS known_at, v AS value FROM x', - ]; - - it('rejects POSITIONAL JOIN to an undeclared relation after an aliased input (registry and runner never execute it)', async () => { - for (const sql of positionalBypassSqls) { - const def = makeSimpleDef({ name: 'positional_leak', sql }); - let thrown: unknown; - try { - validateFeatureDefinition(def); - } catch (error) { - thrown = error; - } - expect(thrown).toBeInstanceOf(FeatureLibraryError); - expect(['EXTERNAL_DATA_ACCESS', 'INVALID_SQL_STATEMENT']).toContain( - (thrown as FeatureLibraryError).code - ); - - expect(() => createFeatureRegistry().registerSignal(def)).toThrow(FeatureLibraryError); - - const fake = createRecordingFakeExecutor(); - await expect( - runFeatureBatch( - def, - { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-06-30' }, - fake.executor - ) - ).rejects.toBeInstanceOf(FeatureLibraryError); - expect(fake.calls).toHaveLength(0); - } - }); - - it('still rejects a POSITIONAL JOIN to an undeclared relation chained after an ON predicate', () => { - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b JOIN {{input:bars_1d}} AS c ON b.ts = c.ts POSITIONAL JOIN staging_tbl', - }) - ), - 'EXTERNAL_DATA_ACCESS' - ); - }); - - it('allows POSITIONAL JOIN between declared inputs and fails closed on unknown join modifiers or unparsed JOIN tokens', () => { - expect(() => - validateFeatureDefinition( - makeSimpleDef({ - inputs: ['bars_1d', 'fx_1d'], - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close / f.close AS value FROM {{input:bars_1d}} AS b POSITIONAL JOIN {{input:fx_1d}} AS f', - }) - ) - ).not.toThrow(); - - expect(() => - validateFeatureDefinition( - makeSimpleDef({ - inputs: ['bars_1d', 'fx_1d'], - sql: 'WITH fx AS (SELECT close AS fx_close FROM {{input:fx_1d}}) SELECT listing_id, ts, ts AS known_at, close / fx_close AS value FROM {{input:bars_1d}} POSITIONAL JOIN fx', - }) - ) - ).not.toThrow(); - - // Unknown modifier immediately after FROM/alias must fail closed (never fall through to expression scan). - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b LATERAL_UNKNOWN JOIN staging_tbl AS s', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - - // Chained JOIN after an ON predicate with an unknown modifier still hits relation allow-list validation. - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b JOIN {{input:bars_1d}} AS c ON b.ts = c.ts UNKNOWN_MOD JOIN staging_tbl AS s', - }) - ), - 'EXTERNAL_DATA_ACCESS' - ); - - // Unparsed JOIN keyword inside a WHERE expression tail must fail closed. - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b WHERE b.close > 0 JOIN staging_tbl AS s', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - }); - - it('accepts a leap-day cutoff and clamps the cutoff year to the last microsecond of the prior day', () => { - const writes = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2023, - toYear: 2025, - vaultCutoffDate: '2024-02-29', - }); - expect(writes.map(w => w.year)).toEqual([2023, 2024]); - const ceiling = '2024-02-28T23:59:59.999999Z'; - expect(writes[1]?.params).toEqual([ceiling, ceiling, 2024, ceiling, ceiling]); - expect(writes[0]?.params).toEqual([ - '2023-12-31T23:59:59.999999Z', - ceiling, - 2023, - '2023-12-31T23:59:59.999999Z', - ceiling, - ]); - }); - - it('plans the cutoff year when only its first day precedes a January 2 cutoff', () => { - const writes = planFeatureBatch(RET_1D_V1, { - curatedRoot: '/c', - fromYear: 2022, - toYear: 2022, - vaultCutoffDate: '2022-01-02', - }); - expect(writes.map(w => w.year)).toEqual([2022]); - const ceiling = '2022-01-01T23:59:59.999999Z'; - expect(writes[0]?.params).toEqual([ceiling, ceiling, 2022, ceiling, ceiling]); - for (const param of writes[0]?.params ?? []) { - if (typeof param === 'string') { - expect(param < '2022-01-02').toBe(true); - } - } - }); -}); - -describe('QA round 2: undeclared-relation probes rejected before any executor call', () => { - // Each probe was also checked in a scratch in-memory DuckDB 1.4.4 session holding a - // `staging_tbl` relation; every form here is valid DuckDB that would read that table. - const undeclaredRelationProbes: ReadonlyArray<{ sql: string; code: FeatureLibraryErrorCode }> = [ - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, s.v AS value FROM {{input:bars_1d}} b NATURAL JOIN staging_tbl s', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b ANTI JOIN staging_tbl s ON s.listing_id = b.listing_id', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b SEMI JOIN staging_tbl USING (listing_id)', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} AS b(listing_id) ASOF JOIN staging_tbl s ON s.listing_id <= b.listing_id', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b, LATERAL (SELECT v FROM staging_tbl) s', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, (SELECT v FROM staging_tbl) AS value FROM {{input:bars_1d}} b', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b WHERE EXISTS ((FROM staging_tbl))', - code: 'INVALID_SQL_STATEMENT', - }, - { - sql: 'WITH x AS (SELECT * FROM {{input:bars_1d}}) SELECT x.listing_id, x.ts, x.known_at, x.close AS value FROM x WHERE x.listing_id IN (TABLE staging_tbl)', - code: 'INVALID_SQL_STATEMENT', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b WHERE b.listing_id = ANY (SELECT listing_id FROM "staging_tbl")', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b QUALIFY b.close IN (SELECT v FROM staging_tbl)', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b WINDOW w AS (ORDER BY (SELECT 1 FROM staging_tbl))', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - // An unused CTE over a catalog table still counts as an undeclared relation source. - sql: 'WITH x AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.known_at, b.close AS value FROM {{input:bars_1d}} b', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - // DuckDB method-call syntax resolves to the table function query_table(). - sql: 'SELECT b.listing_id, b.ts, b.known_at, b.close.query_table() AS value FROM {{input:bars_1d}} b', - code: 'EXTERNAL_DATA_ACCESS', - }, - { - sql: 'SELECT listing_id, ts, known_at, close AS value FROM {{input:bars_1d}} UNION ALL BY NAME SELECT listing_id, ts, ts AS known_at, v AS value FROM staging_tbl', - code: 'INVALID_SQL_STATEMENT', - }, - { - // DuckDB E-strings treat \' as an escaped quote; the tokenizer must not be - // desynchronised into hiding a subquery inside what it believes is a literal. - sql: "SELECT b.listing_id, b.ts, b.known_at, E'\\' ' || (SELECT max(v) FROM staging_tbl) || ' ' AS value FROM {{input:bars_1d}} b", - code: 'INVALID_SQL_STATEMENT', - }, - ]; - - it('rejects each undeclared-relation form with a specific code from validate, registerSignal and runFeatureBatch', async () => { - for (const probe of undeclaredRelationProbes) { - const def = makeSimpleDef({ name: 'probe_leak', sql: probe.sql }); - - expectFeatureErrorCode(() => validateFeatureDefinition(def), probe.code); - expectFeatureErrorCode(() => createFeatureRegistry().registerSignal(def), probe.code); - - const fake = createRecordingFakeExecutor(); - let thrown: unknown; - try { - await runFeatureBatch( - def, - { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-06-30' }, - fake.executor - ); - } catch (error) { - thrown = error; - } - expect((thrown as FeatureLibraryError).code).toBe(probe.code); - expect(fake.calls).toHaveLength(0); - } - }); - - it('plans contract-schema definitions for every input dataset with inner availability predicates bound before the outer filters', () => { - const cutoff = '2022-06-30'; - const ceiling = '2022-06-29T23:59:59.999999Z'; - const yearEnd = '2021-12-31T23:59:59.999999Z'; - const base = { version: 1, warmupBars: 0, knownAtRule: 'source_known_at' as const }; - const cases: ReadonlyArray<{ def: FeatureDefinition; scanParams: DuckDbParam[] }> = [ - { - def: makeSimpleDef({ - ...base, - name: 'fx_close', - family: 'fx', - inputs: ['bars_1d', 'fx_1d'], - sql: 'SELECT b.listing_id, b.ts, GREATEST(b.known_at, f.known_at) AS known_at, b.close * f.close AS value FROM {{input:bars_1d}} AS b JOIN {{input:fx_1d}} AS f ON f.session_date = b.session_date AND LEFT(f.pair, 3) = b.currency', - }), - scanParams: [yearEnd, ceiling, yearEnd, ceiling], - }, - { - def: makeSimpleDef({ - ...base, - name: 'short_int', - inputs: ['shorts'], - sql: 'SELECT listing_id, report_date AS ts, known_at, shares_short AS value FROM {{input:shorts}}', - }), - scanParams: [ceiling], - }, - { - def: makeSimpleDef({ - ...base, - name: 'evt', - family: 'event', - inputs: ['events'], - sql: 'SELECT listing_id, ts, known_at, 1.0 AS value FROM {{input:events}}', - }), - scanParams: [yearEnd, ceiling], - }, - { - def: makeSimpleDef({ - ...base, - name: 'adj', - inputs: ['adj_factors'], - sql: 'SELECT listing_id, ex_date AS ts, known_at, cum_split_factor AS value FROM {{input:adj_factors}}', - }), - scanParams: [ceiling], - }, - { - def: makeSimpleDef({ - ...base, - name: 'fund', - family: 'fundamental', - inputs: ['fundamentals_pit'], - sql: 'SELECT listing_id, effective_known_at AS ts, effective_known_at AS known_at, revenue_ttm AS value FROM {{input:fundamentals_pit}}', - }), - scanParams: [ceiling], - }, - ]; - - for (const { def, scanParams } of cases) { - const writes = planFeatureBatch(def, { - curatedRoot: '/c', - fromYear: 2021, - toYear: 2021, - vaultCutoffDate: cutoff, - }); - expect(writes).toHaveLength(1); - const write = writes[0] as (typeof writes)[number]; - expect(write.outputPath).toBe(`/c/features/${def.name}/v1/year=2021/part.parquet`); - expect(write.params).toEqual([...scanParams, 2021, yearEnd, ceiling]); - // Bind markers in SQL match the parameter count exactly. - expect(write.sql.split('?').length - 1).toBe(write.params.length); - // Every inner scan predicate appears before the outer year/Vault filter. - const outerFilter = write.sql.indexOf('WHERE year(ts) = ?'); - expect(outerFilter).toBeGreaterThan(0); - let lastScan = -1; - for (let at = write.sql.indexOf('read_parquet('); at !== -1; at = write.sql.indexOf('read_parquet(', at + 1)) { - lastScan = at; - } - expect(lastScan).toBeGreaterThan(-1); - expect(lastScan).toBeLessThan(outerFilter); - expect(write.sql).toContain('CAST(ts AS TIMESTAMPTZ) AS ts'); - expect(write.sql).toContain('CAST(known_at AS TIMESTAMPTZ) AS known_at'); - for (const param of write.params) { - if (typeof param === 'string') { - expect(param < cutoff).toBe(true); - } - } - } - }); -}); - -describe('QA round 3: WITH RECURSIVE cannot shadow an undeclared catalog relation', () => { - // Reproduced in a scratch in-memory DuckDB 1.4.4 session holding `staging_tbl(v = 42.0)`: - // DuckDB treats a RECURSIVE CTE body without a recursive UNION term (or the anchor term of - // one that has it) as a non-recursive scope, so `FROM staging_tbl` inside the body binds to - // the catalog table. runFeatureBatch then wrote 42.0 into - // features/leak/v1/year=2021/part.parquet while the manifest reported inputs ['bars_1d']. - const recursiveShadowProbes: readonly string[] = [ - 'WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, staging_tbl AS s', - 'WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl UNION ALL SELECT * FROM staging_tbl WHERE 1 = 0) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, staging_tbl AS s', - 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM (WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT b.listing_id, b.ts, b.close FROM {{input:bars_1d}} AS b, staging_tbl AS s) AS b', - 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b WHERE EXISTS (WITH RECURSIVE staging_tbl AS (SELECT * FROM staging_tbl) SELECT 1 FROM staging_tbl)', - ]; - - it('rejects top-level and nested WITH RECURSIVE CTEs with INVALID_SQL_STATEMENT and zero executor calls', async () => { - for (const sql of recursiveShadowProbes) { - const def = makeSimpleDef({ name: 'leak', sql }); - - expectFeatureErrorCode(() => validateFeatureDefinition(def), 'INVALID_SQL_STATEMENT'); - expectFeatureErrorCode(() => createFeatureRegistry().registerSignal(def), 'INVALID_SQL_STATEMENT'); - - const fake = createRecordingFakeExecutor(); - let execError: unknown; - try { - await runFeatureBatch( - def, - { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' }, - fake.executor - ); - } catch (error) { - execError = error; - } - expect(execError).toBeInstanceOf(FeatureLibraryError); - expect((execError as FeatureLibraryError).code).toBe('INVALID_SQL_STATEMENT'); - expect(fake.calls).toHaveLength(0); - } - }); -}); - -describe('QA round 4: CTE scope must match DuckDB identifier folding (ASCII-only)', () => { - // Reproduced in a scratch in-memory DuckDB 1.4.4 session (`SET TimeZone='UTC'`) holding catalog - // tables `kv(v = 42.0)` and `"ä"(v = 43.0)` plus one bars_1d row (listing 1, 2021-03-01). DuckDB - // folds identifier case for ASCII only, so `"Kv"` (KELVIN SIGN) is not the same name as `kv` - // and `"Ä"` is not `"ä"`; the validator's `toLowerCase()` treated them as the same in-scope CTE. - // runFeatureBatch then wrote 42.0 / 43.0 into features/leak_*/v1/year=2021/part.parquet while the - // manifest reported inputs ['bars_1d']. - const unicodeFoldProbes: readonly string[] = [ - 'WITH "Kv" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - 'WITH "Ä" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, "ä" AS s', - 'SELECT b.listing_id, b.ts, b.ts AS known_at, b.close AS value FROM {{input:bars_1d}} AS b WHERE EXISTS (WITH "Kv" AS (SELECT 1 AS v) SELECT 1 FROM kv)', - ]; - - it('rejects a reference that only matches a CTE under Unicode case folding, with zero executor calls', async () => { - for (const sql of unicodeFoldProbes) { - const def = makeSimpleDef({ name: 'leak', sql }); - - expectFeatureErrorCode(() => validateFeatureDefinition(def), 'EXTERNAL_DATA_ACCESS'); - expectFeatureErrorCode(() => createFeatureRegistry().registerSignal(def), 'EXTERNAL_DATA_ACCESS'); - - const fake = createRecordingFakeExecutor(); - let execError: unknown; - try { - await runFeatureBatch( - def, - { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' }, - fake.executor - ); - } catch (error) { - execError = error; - } - expect(execError).toBeInstanceOf(FeatureLibraryError); - expect((execError as FeatureLibraryError).code).toBe('EXTERNAL_DATA_ACCESS'); - expect(fake.calls).toHaveLength(0); - } - }); - - it('still accepts an ASCII case-insensitive quoted CTE reference, which DuckDB binds to the CTE', () => { - // Verified in DuckDB 1.4.4: `WITH "STAGING" AS (SELECT 1.0 AS v) SELECT v FROM staging` returns 1.0 - // even when a catalog table `staging(v = 42.0)` exists. - const def = makeSimpleDef({ - sql: 'WITH "BARS" AS (SELECT listing_id, ts, close FROM {{input:bars_1d}}) SELECT listing_id, ts, ts AS known_at, close AS value FROM bars', - }); - expect(() => validateFeatureDefinition(def)).not.toThrow(); - }); - - it('accepts an exact non-ASCII quoted CTE name match', () => { - const def = makeSimpleDef({ - sql: 'WITH "Ä" AS (SELECT listing_id, ts, close FROM {{input:bars_1d}}) SELECT listing_id, ts, ts AS known_at, close AS value FROM "Ä"', - }); - expect(() => validateFeatureDefinition(def)).not.toThrow(); - }); -}); - -describe('QA round 5: CTE scope parity with DuckDB across nesting and UNION branches', () => { - // Each case was run in a scratch in-memory DuckDB 1.4.4 session (`SET TimeZone='UTC'`) holding a - // catalog table `kv(v = 42.0)`, with {{input:bars_1d}} replaced by a one-row bars subquery. - // Leak cases returned 42.0 (catalog) in DuckDB; accepted cases returned the CTE value 1.0. - const leakCases: ReadonlyArray<{ label: string; sql: string }> = [ - { - label: 'CTE declared inside a CTE body is not visible to the outer query', - sql: 'WITH a AS (WITH kv AS (SELECT 1.0 AS v) SELECT v FROM kv) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - }, - { - label: 'CTE declared in an earlier parenthesized UNION branch is not visible to a later branch', - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, 1.0 AS value FROM {{input:bars_1d}} AS b UNION ALL (WITH kv AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, 1.0 AS value FROM {{input:bars_1d}} AS b) UNION ALL SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - }, - { - label: 'CTE declared in a derived table is not visible to a sibling FROM item', - sql: 'SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, (WITH kv AS (SELECT 1.0 AS v) SELECT v FROM kv) AS x, kv AS s', - }, - ]; - - it('rejects references that DuckDB binds to the catalog table, with zero executor calls', async () => { - for (const { label, sql } of leakCases) { - const def = makeSimpleDef({ name: 'leak', sql }); - let validateError: unknown; - try { - validateFeatureDefinition(def); - } catch (error) { - validateError = error; - } - expect(validateError, label).toBeInstanceOf(FeatureLibraryError); - expect((validateError as FeatureLibraryError).code, label).toBe('EXTERNAL_DATA_ACCESS'); - - const fake = createRecordingFakeExecutor(); - let execError: unknown; - try { - await runFeatureBatch( - def, - { curatedRoot: '/c', fromYear: 2021, toYear: 2021, vaultCutoffDate: '2022-01-01' }, - fake.executor - ); - } catch (error) { - execError = error; - } - expect(execError, label).toBeInstanceOf(FeatureLibraryError); - expect((execError as FeatureLibraryError).code, label).toBe('EXTERNAL_DATA_ACCESS'); - expect(fake.calls).toHaveLength(0); - } - }); - - it('rejects a CTE name that differs only by Unicode normalization or an invisible character', () => { - // DuckDB matches these names byte-for-byte after ASCII folding, so neither is the CTE. - for (const sql of [ - 'WITH "Ä" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, "Ä" AS s', - 'WITH "kv​" AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, "kv" AS s', - ]) { - expectFeatureErrorCode( - () => validateFeatureDefinition(makeSimpleDef({ name: 'leak', sql })), - 'EXTERNAL_DATA_ACCESS' - ); - } - }); - - it('rejects a non-ASCII space outside quotes instead of treating it as whitespace', () => { - expectFeatureErrorCode( - () => - validateFeatureDefinition( - makeSimpleDef({ - sql: 'SELECT listing_id, ts, ts AS known_at, close AS value FROM {{input:bars_1d}}', - }) - ), - 'INVALID_SQL_STATEMENT' - ); - }); - - it('accepts CTE references DuckDB binds to the CTE: outer CTE shadowing, top-level WITH over UNION, column lists, MATERIALIZED', () => { - for (const sql of [ - 'WITH kv AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, (WITH kv AS (SELECT v FROM kv) SELECT v FROM kv) AS s', - 'WITH kv AS (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, 1.0 AS value FROM {{input:bars_1d}} AS b UNION ALL SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - 'WITH kv(v) AS (SELECT 1.0) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - 'WITH kv AS MATERIALIZED (SELECT 1.0 AS v) SELECT b.listing_id, b.ts, b.ts AS known_at, s.v AS value FROM {{input:bars_1d}} AS b, kv AS s', - ]) { - expect(() => validateFeatureDefinition(makeSimpleDef({ sql }))).not.toThrow(); - } - }); -}); diff --git a/libs/research/test/market-data-store-duckdb.test.ts b/libs/research/test/market-data-store-duckdb.test.ts index 599edece..fe7922b0 100644 --- a/libs/research/test/market-data-store-duckdb.test.ts +++ b/libs/research/test/market-data-store-duckdb.test.ts @@ -13,7 +13,6 @@ import { type DuckDbPlanContext, EVENT_KINDS, EVENTS_COLUMNS, - FUNDAMENTALS_PIT_VALUE_FIELDS, FX_1D_COLUMNS, FX_PAIR_MAP, MarketDataStoreNotImplementedError, @@ -29,7 +28,6 @@ import { planAdjFactorsMetadataQuery, planBars1dQuery, planEventsQuery, - planFundamentalsAsOfQuery, planFx1dQuery, planShortsAsOfQuery, planUniverseQuery, @@ -46,7 +44,6 @@ import { DEFAULT_UNIVERSE_LOOKBACK_DAYS as subpathDefaultUniverseLookbackDays, EVENT_KINDS as subpathEventKinds, EVENTS_COLUMNS as subpathEventsColumns, - FUNDAMENTALS_PIT_VALUE_FIELDS as subpathFundamentalsPitValueFields, FX_1D_COLUMNS as subpathFx1dColumns, FX_PAIR_MAP as subpathFxPairMap, MarketDataStoreNotImplementedError as SubpathNotImplementedError, @@ -57,7 +54,6 @@ import { planAdjFactorsMetadataQuery as subpathPlanAdjFactorsMetadataQuery, planBars1dQuery as subpathPlanBars1dQuery, planEventsQuery as subpathPlanEventsQuery, - planFundamentalsAsOfQuery as subpathPlanFundamentalsAsOfQuery, planFx1dQuery as subpathPlanFx1dQuery, planShortsAsOfQuery as subpathPlanShortsAsOfQuery, planUniverseQuery as subpathPlanUniverseQuery, @@ -219,8 +215,6 @@ describe('market-data-store-duckdb exports', () => { expect(planShortsAsOfQuery).toBe(subpathPlanShortsAsOfQuery); expect(planFx1dQuery).toBe(subpathPlanFx1dQuery); expect(planUniverseQuery).toBe(subpathPlanUniverseQuery); - expect(planFundamentalsAsOfQuery).toBe(subpathPlanFundamentalsAsOfQuery); - expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toBe(subpathFundamentalsPitValueFields); expect(planAdjFactorsMetadataQuery).toBe(subpathPlanAdjFactorsMetadataQuery); expect(parseAdjFactorsSnapshotMetadata).toBe(subpathParseAdjFactorsSnapshotMetadata); expect(createDuckDbMarketDataStore).toBe(subpathCreateDuckDbMarketDataStore); @@ -2427,6 +2421,15 @@ describe('createDuckDbMarketDataStore adapter behavior', () => { universe: 'US_EQ', }), }, + { + method: 'fundamentalsAsOf', + run: () => + store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue'], + asOf: '2025-01-15', + }), + }, { method: 'macroAsOf', run: () => @@ -2865,415 +2868,3 @@ describe('planUniverseQuery & createDuckDbMarketDataStore().universe()', () => { } }); }); - -describe('planFundamentalsAsOfQuery & createDuckDbMarketDataStore().fundamentalsAsOf()', () => { - const EXPECTED_GLOB = `${CURATED_ROOT}/fundamentals_pit/year=*/part.parquet`; - - it('exports the exact 9 allow-listed FUNDAMENTALS_PIT_VALUE_FIELDS and plans parameterized Hive Parquet SQL', () => { - expect(FUNDAMENTALS_PIT_VALUE_FIELDS).toEqual([ - 'revenue', - 'net_income', - 'operating_cash_flow', - 'total_assets', - 'total_equity', - 'shares_outstanding', - 'ttm_revenue', - 'ttm_net_income', - 'ttm_operating_cash_flow', - ]); - - const nonTtm = planFundamentalsAsOfQuery( - { - listingIds: [202, 101, 202], - fields: ['net_income', 'revenue', 'net_income'], - asOf: '2025-06-15', - }, - DEFAULT_CTX - ); - - expect(nonTtm.sql).toBe( - 'WITH latest AS (SELECT f.listing_id, f.effective_known_at, f.known_at_source, f.has_estimated_lag, f.period_end, f.fiscal_period, f.currency, f.period_known_at, f.net_income, f.revenue ' + - 'FROM read_parquet(?, hive_partitioning = true) AS f ' + - 'WHERE f.listing_id IN (?, ?) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ' + - 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + - 'SELECT s.listing_id, epoch_ms(s.effective_known_at) AS effective_known_at, s.known_at_source, s.has_estimated_lag, CAST(s.period_end AS VARCHAR) AS period_end, s.fiscal_period, s.currency, epoch_ms(s.period_known_at) AS period_known_at, s.net_income, s.revenue ' + - 'FROM latest AS s ' + - 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + - 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + - 'ORDER BY s.listing_id ASC' - ); - expect(nonTtm.params).toEqual([ - EXPECTED_GLOB, - 202, - 101, - '2025-06-15T23:59:59.999999Z', - true, - ]); - expect(nonTtm.fenced).toEqual({ - fromMs: Date.UTC(2025, 5, 15, 0, 0, 0, 0), - toMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999), - asOfMs: Date.UTC(2025, 5, 15, 23, 59, 59, 999), - scope: 'vault_fenced', - clampedTo: false, - clampedAsOf: false, - }); - expect(nonTtm.sql).not.toContain(CURATED_ROOT); - expect(nonTtm.sql).not.toContain('2025-06-15'); - expect(nonTtm.sql).not.toContain('ttm_period_end'); - expect(nonTtm.sql).not.toContain('ttm_currency'); - expect(nonTtm.sql).not.toContain('ttm_has_estimated_lag'); - - const withTtm = planFundamentalsAsOfQuery( - { - listingIds: [101], - fields: ['revenue', 'ttm_revenue', 'ttm_operating_cash_flow', 'revenue', 'ttm_revenue'], - asOf: '2025-06-15T14:30:00.123456+02:00', - allowEstimatedLag: false, - }, - DEFAULT_CTX - ); - - expect(withTtm.sql).toBe( - 'WITH latest AS (SELECT f.listing_id, f.effective_known_at, f.known_at_source, f.has_estimated_lag, f.period_end, f.fiscal_period, f.currency, f.period_known_at, f.revenue, f.ttm_revenue, f.ttm_operating_cash_flow, f.ttm_period_end, f.ttm_currency, f.ttm_has_estimated_lag ' + - 'FROM read_parquet(?, hive_partitioning = true) AS f ' + - 'WHERE f.listing_id IN (?) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) ' + - 'QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) ' + - 'SELECT s.listing_id, epoch_ms(s.effective_known_at) AS effective_known_at, s.known_at_source, s.has_estimated_lag, CAST(s.period_end AS VARCHAR) AS period_end, s.fiscal_period, s.currency, epoch_ms(s.period_known_at) AS period_known_at, s.revenue, ' + - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_revenue ELSE NULL END AS ttm_revenue, ' + - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_operating_cash_flow ELSE NULL END AS ttm_operating_cash_flow, ' + - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN CAST(s.ttm_period_end AS VARCHAR) ELSE NULL END AS ttm_period_end, ' + - 'CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency, ' + - 's.ttm_has_estimated_lag ' + - 'FROM latest AS s ' + - 'CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts ' + - 'WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) ' + - 'ORDER BY s.listing_id ASC' - ); - expect(withTtm.params).toEqual([ - EXPECTED_GLOB, - 101, - '2025-06-15T12:30:00.123456Z', - false, - ]); - expect(withTtm.fenced.asOfMs).toBe(Date.UTC(2025, 5, 15, 12, 30, 0, 123)); - expect(withTtm.fenced.clampedAsOf).toBe(false); - }); - - it('clamps asOf at or after vaultCutoffTs to vaultCutoffTs * 1000 - 1 micros even when vaultOperatorAuthorized is true', () => { - const authorizedCtx: DuckDbPlanContext = { - ...DEFAULT_CTX, - vaultOperatorAuthorized: true, - }; - - for (const clampedAsOf of [ - '2026-05-28', - '2026-05-28T00:00:00.000Z', - '2026-05-28T00:00:00.000001Z', - '2026-09-01T15:00:00Z', - ]) { - const planned = planFundamentalsAsOfQuery( - { listingIds: [1], fields: ['revenue'], asOf: clampedAsOf }, - authorizedCtx - ); - expect(planned.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]); - expect(planned.fenced).toEqual({ - fromMs: CUTOFF_MS - 1, - toMs: CUTOFF_MS - 1, - asOfMs: CUTOFF_MS - 1, - scope: 'vault_fenced', - clampedTo: true, - clampedAsOf: true, - }); - } - - // Mid-day cutoff with a date-only asOf on the cutoff date clamps cleanly to 1 microsecond before cutoff. - const midDayCutoffMs = Date.UTC(2026, 4, 28, 12, 0, 0, 0); - const midDayClamped = planFundamentalsAsOfQuery( - { listingIds: [1], fields: ['revenue'], asOf: '2026-05-28' }, - { curatedRoot: CURATED_ROOT, vaultCutoffTs: midDayCutoffMs } - ); - expect(midDayClamped.params).toEqual([EXPECTED_GLOB, 1, '2026-05-28T11:59:59.999999Z', true]); - expect(midDayClamped.fenced.clampedAsOf).toBe(true); - expect(midDayClamped.fenced.clampedTo).toBe(true); - expect(midDayClamped.fenced.asOfMs).toBe(midDayCutoffMs - 1); - - // One microsecond before cutoff stays unclamped and preserves exact micros. - const preCutoffMicros = planFundamentalsAsOfQuery( - { listingIds: [1], fields: ['revenue'], asOf: MAX_ALLOWED_ISO_MICROS }, - DEFAULT_CTX - ); - expect(preCutoffMicros.params).toEqual([EXPECTED_GLOB, 1, MAX_ALLOWED_ISO_MICROS, true]); - expect(preCutoffMicros.fenced.clampedAsOf).toBe(false); - }); - - it('validates fields allow-list, allowEstimatedLag, listingIds, and asOf with zero executor calls on invalid input', async () => { - const fake = createRecordingExecutor(); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - const invalidFieldsCases: unknown[] = [ - [], - 'revenue', - null, - undefined, - ['unknown_field'], - ['revenue', 'period_end'], - ['toString'], - ['revenue; DROP TABLE x'], - [123], - ]; - for (const badFields of invalidFieldsCases) { - let caught: unknown; - try { - await store.fundamentalsAsOf({ - listingIds: [1], - fields: badFields as string[], - asOf: '2025-06-15', - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('fields'); - } - - const invalidLagCases: unknown[] = [null, 1, 0, 'true', 'false', {}]; - for (const badLag of invalidLagCases) { - let caught: unknown; - try { - await store.fundamentalsAsOf({ - listingIds: [1], - fields: ['revenue'], - asOf: '2025-06-15', - allowEstimatedLag: badLag as boolean, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('allowEstimatedLag'); - } - - const invalidAsOfCases: unknown[] = ['', 'not-a-date', '2024-02-30', '2025-06-15T12:00:00', null, undefined]; - for (const badAsOf of invalidAsOfCases) { - let caught: unknown; - try { - await store.fundamentalsAsOf({ - listingIds: [1], - fields: ['revenue'], - asOf: badAsOf as string, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('asOf'); - } - - await expect( - store.fundamentalsAsOf({ listingIds: [], fields: ['revenue'], asOf: '2025-06-15' }) - ).rejects.toBeInstanceOf(MarketDataStoreValidationError); - await expect( - store.fundamentalsAsOf(null as unknown as Parameters[0]) - ).rejects.toBeInstanceOf(MarketDataStoreValidationError); - - expect(fake.calls).toHaveLength(0); - }); - - it('initializes DuckDB budget once and maps fundamentalsAsOf columns in exact projection order with strict scalar validation', async () => { - const t1 = Date.UTC(2024, 7, 1, 20, 0, 0, 0); - const t2 = Date.UTC(2024, 7, 15, 20, 0, 0, 0); - let callIndex = 0; - const fake = createRecordingExecutor({ - onQuery: () => { - callIndex += 1; - if (callIndex === 1) { - return [ - { - listing_id: 101, - effective_known_at: t1, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: t1, - total_assets: null, - revenue: 120.5, - }, - ]; - } - return [ - { - listing_id: 101, - effective_known_at: t2, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: t1, - revenue: 120.5, - ttm_revenue: 450.25, - ttm_period_end: '2024-06-30', - ttm_currency: 'USD', - ttm_has_estimated_lag: false, - }, - ]; - }, - }); - - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - const expectedBudget = resolveDuckDbConnectionBudget().statements; - - const first = await store.fundamentalsAsOf({ - listingIds: [101], - fields: ['total_assets', 'revenue', 'total_assets'], - asOf: '2024-08-05', - }); - expect(first.columns).toEqual([ - 'listing_id', - 'effective_known_at', - 'known_at_source', - 'has_estimated_lag', - 'period_end', - 'fiscal_period', - 'currency', - 'period_known_at', - 'total_assets', - 'revenue', - ]); - expect(first.rows).toEqual([ - { - listing_id: 101, - effective_known_at: t1, - known_at_source: 'filing_date', - has_estimated_lag: false, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: t1, - total_assets: null, - revenue: 120.5, - }, - ]); - expect(fake.runCalls).toEqual(expectedBudget); - - const second = await store.fundamentalsAsOf({ - listingIds: [101], - fields: ['revenue', 'ttm_revenue'], - asOf: '2024-08-20', - allowEstimatedLag: false, - }); - expect(second.columns).toEqual([ - 'listing_id', - 'effective_known_at', - 'known_at_source', - 'has_estimated_lag', - 'period_end', - 'fiscal_period', - 'currency', - 'period_known_at', - 'revenue', - 'ttm_revenue', - 'ttm_period_end', - 'ttm_currency', - 'ttm_has_estimated_lag', - ]); - expect(second.rows).toHaveLength(1); - expect(second.rows[0]?.ttm_revenue).toBe(450.25); - expect(second.rows[0]?.ttm_has_estimated_lag).toBe(false); - // Budget SET statements must not re-run on second query. - expect(fake.runCalls).toHaveLength(3); - expect(fake.queryCalls).toHaveLength(2); - - // Rejects non-boolean has_estimated_lag from a misbehaving executor. - const badBoolFake = createRecordingExecutor({ - onQuery: () => [ - { - listing_id: 101, - effective_known_at: t1, - known_at_source: 'filing_date', - has_estimated_lag: 'false' as unknown as boolean, - period_end: '2024-06-30', - fiscal_period: 'Q2', - currency: 'USD', - period_known_at: t1, - revenue: 120.5, - }, - ], - }); - const badStore = createDuckDbMarketDataStore({ - executor: badBoolFake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - await expect( - badStore.fundamentalsAsOf({ listingIds: [101], fields: ['revenue'], asOf: '2024-08-05' }) - ).rejects.toBeInstanceOf(MarketDataStoreValidationError); - }); -}); - -describe('fundamentalsAsOf hostile request inputs', () => { - it('fails closed with zero executor calls for JSON-decoded object, symbol, and sparse field entries', async () => { - const fake = createRecordingExecutor(); - const store = createDuckDbMarketDataStore({ - executor: fake.executor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: CUTOFF_MS, - }); - - const hostileFields: unknown[] = [ - JSON.parse('[{"toString": 1}]'), - [Object.create(null)], - [Symbol('revenue')], - // eslint-disable-next-line no-sparse-arrays - [, 'revenue'], - ['REVENUE'], - [' revenue'], - ]; - for (const fields of hostileFields) { - await expect( - store.fundamentalsAsOf({ listingIds: [1], fields: fields as string[], asOf: '2025-06-15' }) - ).rejects.toThrow(); - } - - const hostileLag = JSON.parse('{"toString": 1}'); - await expect( - store.fundamentalsAsOf({ - listingIds: [1], - fields: ['revenue'], - asOf: '2025-06-15', - allowEstimatedLag: hostileLag as boolean, - }) - ).rejects.toThrow(); - - expect(fake.calls).toHaveLength(0); - expect(fake.runCalls).toHaveLength(0); - }); - - it('plans a request asOf with an offset that crosses the cutoff as a clamped bound', () => { - // 2026-05-28T01:00:00+02:00 === 2026-05-27T23:00:00Z, i.e. before the cutoff: not clamped. - const beforeCutoff = planFundamentalsAsOfQuery( - { listingIds: [1], fields: ['revenue'], asOf: '2026-05-28T01:00:00+02:00' }, - DEFAULT_CTX - ); - expect(Date.parse(beforeCutoff.params[2] as string)).toBe(Date.UTC(2026, 4, 27, 23, 0, 0, 0)); - expect(beforeCutoff.fenced.clampedAsOf).toBe(false); - - // 2026-05-27T23:00:00-02:00 === 2026-05-28T01:00:00Z, i.e. after the cutoff: clamped. - const afterCutoff = planFundamentalsAsOfQuery( - { listingIds: [1], fields: ['revenue'], asOf: '2026-05-27T23:00:00-02:00' }, - DEFAULT_CTX - ); - expect(afterCutoff.params[2]).toBe(MAX_ALLOWED_ISO_MICROS); - expect(afterCutoff.fenced.clampedAsOf).toBe(true); - }); -}); diff --git a/libs/research/test/market-data-store-questdb.qa.test.ts b/libs/research/test/market-data-store-questdb.qa.test.ts deleted file mode 100644 index bbe68fb6..00000000 --- a/libs/research/test/market-data-store-questdb.qa.test.ts +++ /dev/null @@ -1,346 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - createQuestDbIntradayBarsReader, - MarketDataStoreValidationError, - planBars1mQuery, - VaultScopeNotAuthorizedError, - type BarBatch, - type QuestDbBars1mQuery, - type QuestDbQueryExecutor, -} from '@stock-bot/research'; - -// QA edge cases for T-146 (QuestDB `bars_1m` reader) beyond the programmer suite. - -const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); - -type QueryResult = { readonly rows: readonly Record[] }; - -class ScriptedExecutor implements QuestDbQueryExecutor { - readonly calls: Array<{ sql: string; params: unknown[] }> = []; - constructor(private readonly respond: () => Promise) {} - async query(sql: string, params: readonly unknown[]): Promise { - this.calls.push({ sql, params: [...params] }); - return this.respond(); - } -} - -function executorReturning(result: unknown): ScriptedExecutor { - return new ScriptedExecutor(async () => result as QueryResult); -} - -async function collect(iterable: AsyncIterable): Promise { - const out: BarBatch[] = []; - for await (const batch of iterable) { - out.push(batch); - } - return out; -} - -function us(ms: number, extraMicros = 0n): string { - return (BigInt(ms) * 1000n + extraMicros).toString(); -} - -function row(overrides: Record): Record { - return { - listing_id: '7', - open: 10, - high: 11, - low: 9, - close: 10.5, - volume: 100, - vwap: 10.2, - ...overrides, - }; -} - -const sessionQuery: QuestDbBars1mQuery = { - listingIds: [7], - timeframe: '1m', - from: '2024-03-01T14:30:00Z', - to: '2024-03-01T21:00:00Z', - asOf: '2024-03-01T21:00:00Z', - adjustment: 'raw', -}; - -describe('QuestDB bars_1m reader QA: planner purity and param binding', () => { - it('is deterministic and binds INT32_MAX as a decimal SYMBOL string only in params', () => { - const q: QuestDbBars1mQuery = { ...sessionQuery, listingIds: [2_147_483_647, 1] }; - const a = planBars1mQuery(q, { vaultCutoffTs: VAULT_CUTOFF_TS }); - const b = planBars1mQuery(q, { vaultCutoffTs: VAULT_CUTOFF_TS }); - - expect(a).toEqual(b); - expect(a.params).toEqual([ - '2024-03-01T14:30:00.000Z', - '2024-03-01T21:00:00.000Z', - '1', - '2147483647', - '2024-03-01T21:00:00.000Z', - ]); - expect(a.sql).not.toContain('2147483647'); - expect(a.sql).toContain('listing_id IN ($3, $4) AND known_at <= $5'); - // Only ordinal placeholders and fixed identifiers: no quotes or digits outside `$n` tokens. - expect(a.sql.replace(/\$\d+/g, '').replace('bars_1m', '')).not.toMatch(/[0-9'";]/); - }); - - it('normalizes offset timestamps to UTC ISO-8601 params', () => { - const planned = planBars1mQuery( - { - ...sessionQuery, - from: '2024-03-01T09:30:00-05:00', - to: '2024-03-01T16:00:00.250-05:00', - asOf: '2024-03-01T17:00:00-05:00', - }, - { vaultCutoffTs: VAULT_CUTOFF_TS } - ); - expect(planned.params).toEqual([ - '2024-03-01T14:30:00.000Z', - '2024-03-01T21:00:00.250Z', - '7', - '2024-03-01T22:00:00.000Z', - ]); - }); - - it('passes the executor a copy of params so executor mutation cannot alter later plans', async () => { - const executor = new ScriptedExecutor(async () => ({ rows: [] })); - const mutating: QuestDbQueryExecutor = { - async query(sql, params) { - (params as unknown[]).splice(0, params.length, 'tampered'); - return executor.query(sql, params); - }, - }; - const reader = createQuestDbIntradayBarsReader({ - executor: mutating, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - await collect(reader.bars(sessionQuery)); - await collect(reader.bars(sessionQuery)); - - expect(executor.calls).toHaveLength(2); - expect(executor.calls[1]?.params).toEqual(['tampered']); - expect(planBars1mQuery(sessionQuery, { vaultCutoffTs: VAULT_CUTOFF_TS }).params).toHaveLength( - 4 - ); - }); - - it('rejects numeric-looking string listing IDs and non-array listingIds before querying', async () => { - const executor = executorReturning({ rows: [] }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - const bad: unknown[] = [ - { ...sessionQuery, listingIds: ['7'] }, - { ...sessionQuery, listingIds: [7n] }, - { ...sessionQuery, listingIds: 7 }, - { ...sessionQuery, listingIds: undefined }, - { ...sessionQuery, listingIds: [7, Number.POSITIVE_INFINITY] }, - null, - ]; - for (const q of bad) { - await expect(collect(reader.bars(q as QuestDbBars1mQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - expect(executor.calls).toHaveLength(0); - }); -}); - -describe('QuestDB bars_1m reader QA: Vault and trusted context', () => { - it('planner ignores a vaultOperatorAuthorized flag smuggled on the query object', () => { - const spoofed = { - ...sessionQuery, - from: '2025-07-02', - to: '2025-07-03', - asOf: undefined, - scope: 'vault_evaluation_only', - vaultOperatorAuthorized: true, - } as unknown as QuestDbBars1mQuery; - expect(() => planBars1mQuery(spoofed, { vaultCutoffTs: VAULT_CUTOFF_TS })).toThrow( - VaultScopeNotAuthorizedError - ); - }); - - it('rejects non-boolean truthy vaultOperatorAuthorized in factory options', () => { - for (const flag of ['true', 1, {}]) { - expect(() => - createQuestDbIntradayBarsReader({ - executor: executorReturning({ rows: [] }), - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: flag as unknown as boolean, - }) - ).toThrow(MarketDataStoreValidationError); - } - }); - - it('rejects a non-object planner context', () => { - expect(() => - planBars1mQuery(sessionQuery, null as unknown as { vaultCutoffTs: number }) - ).toThrow(MarketDataStoreValidationError); - }); - - it('rejects unknown scope values before querying', async () => { - const executor = executorReturning({ rows: [] }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - await expect( - collect(reader.bars({ ...sessionQuery, scope: 'all' } as unknown as QuestDbBars1mQuery)) - ).rejects.toThrow(MarketDataStoreValidationError); - expect(executor.calls).toHaveLength(0); - }); - - it('a row known one microsecond before a clamped asOf maps to knownAt exactly at the fence, never past it', async () => { - const executor = executorReturning({ - rows: [ - row({ - ts_us: us(VAULT_CUTOFF_TS - 60_000), - known_at_us: us(VAULT_CUTOFF_TS - 1, -1n), - }), - ], - }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - const rows = ( - await collect( - reader.bars({ - ...sessionQuery, - from: '2025-06-30T23:00:00Z', - to: '2025-12-31', - asOf: '2025-12-31', - }) - ) - ).flatMap(b => b.rows); - expect(rows).toHaveLength(1); - expect(rows[0]?.knownAt).toBe(VAULT_CUTOFF_TS - 1); - expect(rows[0]!.knownAt).toBeLessThan(VAULT_CUTOFF_TS); - }); -}); - -describe('QuestDB bars_1m reader QA: executor result and row defence-in-depth', () => { - it('rejects malformed executor results with a validation error', async () => { - for (const result of [ - null, - undefined, - {}, - { rows: null }, - { rows: 'x' }, - [], - { rows: [null] }, - { rows: [[1]] }, - ]) { - const reader = createQuestDbIntradayBarsReader({ - executor: executorReturning(result), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - await expect(collect(reader.bars(sessionQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - }); - - it('propagates executor failures unchanged and yields nothing', async () => { - const boom = new Error('pgwire connection reset'); - const reader = createQuestDbIntradayBarsReader({ - executor: new ScriptedExecutor(async () => { - throw boom; - }), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - await expect(collect(reader.bars(sessionQuery))).rejects.toBe(boom); - }); - - it('does not call the executor until iteration starts (lazy plan + query)', async () => { - const executor = executorReturning({ rows: [] }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - const iterable = reader.bars(sessionQuery); - expect(executor.calls).toHaveLength(0); - await collect(iterable); - expect(executor.calls).toHaveLength(1); - }); - - it('maps multi-listing rows, undefined vwap to null, and -0 to 0', async () => { - const t0 = Date.UTC(2024, 2, 1, 14, 30); - const executor = executorReturning({ - rows: [ - row({ listing_id: '3', ts_us: us(t0), known_at_us: us(t0 + 60_000), vwap: undefined }), - row({ listing_id: '7', ts_us: us(t0), known_at_us: us(t0 + 60_000), volume: -0, vwap: 0 }), - ], - }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - const rows = (await collect(reader.bars({ ...sessionQuery, listingIds: [7, 3] }))).flatMap( - b => b.rows - ); - expect(rows.map(r => r.listingId)).toEqual([3, 7]); - expect(rows[0]?.vwap).toBeNull(); - expect(Object.is(rows[1]?.volume, 0)).toBe(true); - expect(rows[1]?.vwap).toBe(0); - expect(executor.calls[0]?.params.slice(2, 4)).toEqual(['3', '7']); - }); - - it('rejects timestamp wire values that are unsafe numbers, padded strings, or missing', async () => { - const t0 = Date.UTC(2024, 2, 1, 14, 30); - const bad: Record[] = [ - row({ ts_us: Number.MAX_SAFE_INTEGER + 2, known_at_us: us(t0) }), - row({ ts_us: ` ${us(t0)}`, known_at_us: us(t0) }), - row({ ts_us: `+${us(t0)}`, known_at_us: us(t0) }), - row({ ts_us: us(t0) }), - row({ ts_us: new Date(t0), known_at_us: us(t0) }), - ]; - for (const r of bad) { - const reader = createQuestDbIntradayBarsReader({ - executor: executorReturning({ rows: [r] }), - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - await expect(collect(reader.bars(sessionQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - }); - - it('floors sub-millisecond ts and ceils sub-millisecond known_at for pre-1970 instants', async () => { - // ts = -1.5 ms -> floor -2 ms; known_at = -1.5 ms -> ceil -1 ms. - const executor = executorReturning({ - rows: [row({ ts_us: '-1500', known_at_us: -1500n })], - }); - const reader = createQuestDbIntradayBarsReader({ executor, vaultCutoffTs: VAULT_CUTOFF_TS }); - const rows = ( - await collect( - reader.bars({ - ...sessionQuery, - from: '1969-12-31T23:59:59.000Z', - to: '1970-01-01T00:00:00.000Z', - asOf: '1970-01-01T00:00:00.000Z', - }) - ) - ).flatMap(b => b.rows); - expect(rows).toEqual([ - { - listingId: 7, - ts: -2, - open: 10, - high: 11, - low: 9, - close: 10.5, - volume: 100, - vwap: 10.2, - knownAt: -1, - }, - ]); - }); - - it('batch size equal to row count yields one batch; batch size 1 yields one row per batch in order', async () => { - const t0 = Date.UTC(2024, 2, 1, 14, 30); - const rows = Array.from({ length: 4 }, (_, i) => - row({ ts_us: us(t0 + i * 60_000), known_at_us: us(t0 + (i + 1) * 60_000), open: 10 + i }) - ); - const exact = createQuestDbIntradayBarsReader({ - executor: executorReturning({ rows }), - vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: 4, - }); - expect((await collect(exact.bars(sessionQuery))).map(b => b.rows.length)).toEqual([4]); - - const single = createQuestDbIntradayBarsReader({ - executor: executorReturning({ rows }), - vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: 1, - }); - const batches = await collect(single.bars(sessionQuery)); - expect(batches.map(b => b.rows.length)).toEqual([1, 1, 1, 1]); - expect(batches.map(b => b.rows[0]?.open)).toEqual([10, 11, 12, 13]); - }); -}); diff --git a/libs/research/test/market-data-store-questdb.test.ts b/libs/research/test/market-data-store-questdb.test.ts deleted file mode 100644 index b17e06a2..00000000 --- a/libs/research/test/market-data-store-questdb.test.ts +++ /dev/null @@ -1,768 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - type BarBatch, - type BarRecord, - DEFAULT_QUESTDB_BARS_BATCH_SIZE, - MarketDataStoreNotImplementedError, - MarketDataStoreValidationError, - type QuestDbBars1mQuery, - type QuestDbQueryExecutor, - VaultHoldoutFenceError, - VaultScopeNotAuthorizedError, - createQuestDbIntradayBarsReader, - planBars1mQuery, -} from '@stock-bot/research'; - -interface RecordedCall { - readonly sql: string; - readonly params: readonly unknown[]; -} - -class RecordingQuestDbExecutor implements QuestDbQueryExecutor { - readonly calls: RecordedCall[] = []; - private nextResult: { readonly rows: readonly Record[] } = { rows: [] }; - - setRows(rows: readonly Record[]): void { - this.nextResult = { rows }; - } - - setRawResult(result: unknown): void { - this.nextResult = result as { readonly rows: readonly Record[] }; - } - - async query( - sql: string, - params: readonly unknown[] - ): Promise<{ readonly rows: readonly Record[] }> { - this.calls.push({ sql, params: [...params] }); - return this.nextResult; - } -} - -async function collectBatches(iterable: AsyncIterable): Promise { - const batches: BarBatch[] = []; - for await (const batch of iterable) { - batches.push(batch); - } - return batches; -} - -const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); // 2025-07-01T00:00:00.000Z - -describe('planBars1mQuery', () => { - it('snapshots exact parameterized SQL and bound params for a 1-listing, 1-year query', () => { - const query: QuestDbBars1mQuery = { - listingIds: [42], - timeframe: '1m', - from: '2024-01-02', - to: '2024-12-31', - adjustment: 'raw', - asOf: '2025-01-01T00:00:00Z', - }; - - const planned = planBars1mQuery(query, { vaultCutoffTs: VAULT_CUTOFF_TS }); - - expect(planned.sql).toBe( - 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + - 'FROM bars_1m ' + - 'WHERE ts >= $1 AND ts <= $2 AND listing_id IN ($3) AND known_at <= $4 ' + - 'ORDER BY ts, listing_id' - ); - expect(planned.params).toEqual([ - '2024-01-02T00:00:00.000Z', - '2024-12-31T23:59:59.999Z', - '42', - '2025-01-01T00:00:00.000Z', - ]); - expect(planned.fence).toEqual({ - fromMs: Date.UTC(2024, 0, 2, 0, 0, 0, 0), - toMs: Date.UTC(2024, 11, 31, 23, 59, 59, 999), - asOfMs: Date.UTC(2025, 0, 1, 0, 0, 0, 0), - scope: 'vault_fenced', - clampedTo: false, - clampedAsOf: false, - }); - - // No caller-supplied values appear in SQL text. - for (const boundValue of planned.params) { - expect(planned.sql).not.toContain(boundValue); - } - expect(planned.sql).not.toContain('42'); - expect(planned.sql).not.toContain('2024'); - expect(planned.sql).not.toContain('2025'); - }); - - it('deduplicates and sorts multi-listing IDs numerically without mutating caller input', () => { - const callerListingIds = [100, 2, 10, 2, 1]; - const snapshotBefore = [...callerListingIds]; - - const planned = planBars1mQuery( - { - listingIds: callerListingIds, - timeframe: '1m', - from: '2024-06-03T13:30:00Z', - to: '2024-06-03T20:00:00Z', - adjustment: 'raw', - asOf: '2024-06-04T00:00:00Z', - }, - { vaultCutoffTs: VAULT_CUTOFF_TS } - ); - - expect(callerListingIds).toEqual(snapshotBefore); - expect(planned.sql).toBe( - 'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' + - 'FROM bars_1m ' + - 'WHERE ts >= $1 AND ts <= $2 AND listing_id IN ($3, $4, $5, $6) AND known_at <= $7 ' + - 'ORDER BY ts, listing_id' - ); - expect(planned.params).toEqual([ - '2024-06-03T13:30:00.000Z', - '2024-06-03T20:00:00.000Z', - '1', - '2', - '10', - '100', - '2024-06-04T00:00:00.000Z', - ]); - }); - - it('port is structurally compatible with QuestDBClient.query generic signature', async () => { - class QuestDbClientLike { - readonly calls: RecordedCall[] = []; - async query>( - sql: string, - params?: unknown[] - ): Promise<{ - rows: T[]; - rowCount: number; - executionTime: number; - }> { - this.calls.push({ sql, params: params ? [...params] : [] }); - return { rows: [], rowCount: 0, executionTime: 1 }; - } - } - - const clientLike = new QuestDbClientLike(); - const executorPort: QuestDbQueryExecutor = clientLike; - const reader = createQuestDbIntradayBarsReader({ - executor: executorPort, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const batches = await collectBatches( - reader.bars({ - listingIds: [7], - timeframe: '1m', - from: '2024-05-01T13:30:00Z', - to: '2024-05-01T13:35:00Z', - adjustment: 'raw', - }) - ); - - expect(batches).toEqual([]); - expect(clientLike.calls).toHaveLength(1); - }); -}); - -describe('Vault fence enforcement', () => { - it('rejects from at or past cutoff with VaultHoldoutFenceError and zero executor calls', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - await expect( - collectBatches( - reader.bars({ - listingIds: [1], - timeframe: '1m', - from: '2025-07-01T00:00:00.000Z', - to: '2025-07-02T00:00:00.000Z', - adjustment: 'raw', - }) - ) - ).rejects.toThrow(VaultHoldoutFenceError); - - await expect( - collectBatches( - reader.bars({ - listingIds: [1], - timeframe: '1m', - from: '2025-07-15', - to: '2025-08-01', - adjustment: 'raw', - }) - ) - ).rejects.toThrow(VaultHoldoutFenceError); - - expect(executor.calls).toHaveLength(0); - }); - - it('clamps to and asOf past cutoff and defaults omitted asOf to cutoff - 1ms', () => { - const clampedPlan = planBars1mQuery( - { - listingIds: [9], - timeframe: '1m', - from: '2025-06-01', - to: '2025-09-01', - asOf: '2025-09-02', - adjustment: 'raw', - }, - { vaultCutoffTs: VAULT_CUTOFF_TS } - ); - - expect(clampedPlan.fence.clampedTo).toBe(true); - expect(clampedPlan.fence.clampedAsOf).toBe(true); - expect(clampedPlan.fence.toMs).toBe(VAULT_CUTOFF_TS - 1); - expect(clampedPlan.fence.asOfMs).toBe(VAULT_CUTOFF_TS - 1); - expect(clampedPlan.params).toEqual([ - '2025-06-01T00:00:00.000Z', - '2025-06-30T23:59:59.999Z', - '9', - '2025-06-30T23:59:59.999Z', - ]); - - const omittedAsOfPlan = planBars1mQuery( - { - listingIds: [9], - timeframe: '1m', - from: '2025-06-01', - to: '2025-06-15', - adjustment: 'raw', - }, - { vaultCutoffTs: VAULT_CUTOFF_TS } - ); - - expect(omittedAsOfPlan.fence.clampedTo).toBe(false); - expect(omittedAsOfPlan.fence.clampedAsOf).toBe(false); - expect(omittedAsOfPlan.fence.asOfMs).toBe(VAULT_CUTOFF_TS - 1); - expect(omittedAsOfPlan.params[3]).toBe('2025-06-30T23:59:59.999Z'); - }); - - it('rejects unauthorized vault_evaluation_only even if caller attaches authorization flag on query', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const spoofedQuery = { - listingIds: [1], - timeframe: '1m', - from: '2025-07-01', - to: '2025-07-10', - adjustment: 'raw', - scope: 'vault_evaluation_only', - vaultOperatorAuthorized: true, - } as unknown as QuestDbBars1mQuery; - - await expect(collectBatches(reader.bars(spoofedQuery))).rejects.toThrow( - VaultScopeNotAuthorizedError - ); - expect(executor.calls).toHaveLength(0); - }); - - it('permits vault_evaluation_only when trusted factory context is operator-authorized', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: true, - }); - - const batches = await collectBatches( - reader.bars({ - listingIds: [5], - timeframe: '1m', - from: '2025-07-02T13:30:00Z', - to: '2025-07-02T13:31:00Z', - adjustment: 'raw', - scope: 'vault_evaluation_only', - }) - ); - - expect(batches).toEqual([]); - expect(executor.calls).toHaveLength(1); - expect(executor.calls[0]?.params).toEqual([ - '2025-07-02T13:30:00.000Z', - '2025-07-02T13:31:00.000Z', - '5', - '2025-07-02T13:31:00.000Z', - ]); - }); -}); - -describe('Input validation and injection rejection', () => { - it('rejects split and total adjustments with MarketDataStoreNotImplementedError and zero executor calls', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - for (const adjustment of ['split', 'total'] as const) { - await expect( - collectBatches( - reader.bars({ - listingIds: [1], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment, - }) - ) - ).rejects.toThrow(MarketDataStoreNotImplementedError); - } - - expect(executor.calls).toHaveLength(0); - }); - - it('rejects invalid timeframe, adjustment, dates, listingIds, and SQL injection before any executor call', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const invalidQueries: unknown[] = [ - // Wrong timeframes - { listingIds: [1], timeframe: '1d', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, - { listingIds: [1], timeframe: '5m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, - { listingIds: [1], timeframe: '1h', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, - // Invalid adjustment - { - listingIds: [1], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'dividend', - }, - // Reversed or invalid dates - { listingIds: [1], timeframe: '1m', from: '2024-02-01', to: '2024-01-01', adjustment: 'raw' }, - { - listingIds: [1], - timeframe: '1m', - from: '2024-01-02T13:30:00', - to: '2024-01-03T13:30:00Z', - adjustment: 'raw', - }, - { listingIds: [1], timeframe: '1m', from: 'not-a-date', to: '2024-01-03', adjustment: 'raw' }, - // Invalid listingIds - { listingIds: [], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, - { listingIds: [0], timeframe: '1m', from: '2024-01-02', to: '2024-01-03', adjustment: 'raw' }, - { - listingIds: [-5], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'raw', - }, - { - listingIds: [2_147_483_648], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'raw', - }, - { - listingIds: [1.5], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'raw', - }, - { - listingIds: [Number.NaN], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'raw', - }, - // SQL injection attempt cast through unknown - { - listingIds: ['1; DROP TABLE bars_1m'], - timeframe: '1m', - from: '2024-01-02', - to: '2024-01-03', - adjustment: 'raw', - }, - ]; - - for (const badQuery of invalidQueries) { - await expect(collectBatches(reader.bars(badQuery as QuestDbBars1mQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - - expect(executor.calls).toHaveLength(0); - }); - - it('rejects invalid factory options (executor, vaultCutoffTs, batchSize)', () => { - const executor = new RecordingQuestDbExecutor(); - - expect(() => - createQuestDbIntradayBarsReader({ - executor: {} as unknown as QuestDbQueryExecutor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: Number.NaN, - }) - ).toThrow(MarketDataStoreValidationError); - - for (const badBatchSize of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, null]) { - expect(() => - createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: badBatchSize as unknown as number, - }) - ).toThrow(MarketDataStoreValidationError); - } - }); -}); - -describe('1-year single-listing replay, row mapping, and batching', () => { - it('streams 98,280 synthetic 1m rows (252 sessions x 390 min) in exact order across default 50k batches', async () => { - expect(DEFAULT_QUESTDB_BARS_BATCH_SIZE).toBe(50_000); - - const sessions = 252; - const minutesPerSession = 390; - const totalRows = sessions * minutesPerSession; // 98,280 - const listingId = 101; - const listingIdSymbol = String(listingId); - const baseSessionStartMs = Date.UTC(2024, 0, 2, 14, 30, 0, 0); - const msPerDay = 86_400_000; - const msPerMinute = 60_000; - - const rawRows: Record[] = new Array(totalRows); - const expected: BarRecord[] = new Array(totalRows); - - let idx = 0; - for (let s = 0; s < sessions; s += 1) { - const sessionStartMs = baseSessionStartMs + s * msPerDay; - for (let m = 0; m < minutesPerSession; m += 1) { - const tsMs = sessionStartMs + m * msPerMinute; - const knownAtMs = tsMs + msPerMinute; - const tsUs = BigInt(tsMs) * 1000n; - const knownAtUs = BigInt(knownAtMs) * 1000n; - - const open = 100 + s * 0.25 + m * 0.01; - const high = open + 0.15; - const low = open - 0.1; - const close = open + 0.05; - const volume = 1_000 + ((s * 390 + m) % 500); - const vwap = m % 10 === 0 ? null : open + 0.02; - - // Exercise all three supported LONG wire representations: decimal string, bigint, safe int. - const tsWire: unknown = - idx % 3 === 0 ? tsUs.toString() : idx % 3 === 1 ? tsUs : Number(tsUs); - const knownAtWire: unknown = - idx % 3 === 0 ? knownAtUs.toString() : idx % 3 === 1 ? knownAtUs : Number(knownAtUs); - - rawRows[idx] = { - listing_id: listingIdSymbol, - ts_us: tsWire, - open, - high, - low, - close, - volume, - vwap, - known_at_us: knownAtWire, - }; - expected[idx] = { - listingId, - ts: tsMs, - open, - high, - low, - close, - volume, - vwap, - knownAt: knownAtMs, - }; - idx += 1; - } - } - - const executor = new RecordingQuestDbExecutor(); - executor.setRows(rawRows); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const query: QuestDbBars1mQuery = { - listingIds: [listingId], - timeframe: '1m', - from: '2024-01-02', - to: '2024-12-31', - asOf: '2025-01-01T00:00:00Z', - adjustment: 'raw', - }; - - const run1Batches = await collectBatches(reader.bars(query)); - const run2Batches = await collectBatches(reader.bars(query)); - - expect(executor.calls).toHaveLength(2); - expect(run1Batches.map(b => b.rows.length)).toEqual([50_000, 48_280]); - expect(run2Batches.map(b => b.rows.length)).toEqual([50_000, 48_280]); - - const flat1 = run1Batches.flatMap(b => b.rows); - const flat2 = run2Batches.flatMap(b => b.rows); - expect(flat1).toHaveLength(totalRows); - expect(flat1).toEqual(expected); - expect(flat2).toEqual(flat1); - }); - - it('supports custom small batch sizes and yields zero batches for empty results', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: 3, - }); - - const query: QuestDbBars1mQuery = { - listingIds: [12], - timeframe: '1m', - from: '2024-03-01T14:30:00Z', - to: '2024-03-01T14:40:00Z', - asOf: '2024-03-01T15:00:00Z', - adjustment: 'raw', - }; - - executor.setRows([]); - expect(await collectBatches(reader.bars(query))).toEqual([]); - expect(executor.calls).toHaveLength(1); - - const startMs = Date.UTC(2024, 2, 1, 14, 30, 0, 0); - const rows = Array.from({ length: 7 }, (_, i) => { - const tsMs = startMs + i * 60_000; - return { - listing_id: '12', - ts_us: (BigInt(tsMs) * 1000n).toString(), - open: 10 + i, - high: 11 + i, - low: 9 + i, - close: 10.5 + i, - volume: 100 + i, - vwap: i % 2 === 0 ? null : 10.25 + i, - known_at_us: (BigInt(tsMs + 60_000) * 1000n).toString(), - }; - }); - - executor.setRows(rows); - const batches = await collectBatches(reader.bars(query)); - expect(batches.map(b => b.rows.length)).toEqual([3, 3, 1]); - expect(executor.calls).toHaveLength(2); - expect(batches[0]?.rows[0]?.vwap).toBeNull(); - expect(batches[0]?.rows[1]?.vwap).toBe(11.25); - }); -}); - -describe('Malformed and out-of-fence row defence-in-depth', () => { - const baseQuery: QuestDbBars1mQuery = { - listingIds: [101], - timeframe: '1m', - from: '2025-06-30T23:58:00.000Z', - to: '2025-07-05T00:00:00.000Z', // clamped to VAULT_CUTOFF_TS - 1 (2025-06-30T23:59:59.999Z) - asOf: '2025-07-05T00:00:00.000Z', // clamped to VAULT_CUTOFF_TS - 1 - adjustment: 'raw', - }; - - const fromUs = BigInt(Date.UTC(2025, 5, 30, 23, 58, 0, 0)) * 1000n; - const clampedToUs = BigInt(VAULT_CUTOFF_TS - 1) * 1000n; - const clampedAsOfUs = BigInt(VAULT_CUTOFF_TS - 1) * 1000n; - - function makeValidRow(overrides: Record = {}): Record { - return { - listing_id: '101', - ts_us: fromUs.toString(), - open: 150, - high: 151, - low: 149.5, - close: 150.25, - volume: 2500, - vwap: 150.1, - known_at_us: clampedAsOfUs.toString(), - ...overrides, - }; - } - - it('accepts rows at exact fenced microsecond endpoints', async () => { - const executor = new RecordingQuestDbExecutor(); - executor.setRows([ - makeValidRow({ ts_us: fromUs.toString(), known_at_us: clampedAsOfUs.toString() }), - makeValidRow({ ts_us: clampedToUs.toString(), known_at_us: clampedAsOfUs.toString() }), - ]); - - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const batches = await collectBatches(reader.bars(baseQuery)); - expect(batches).toHaveLength(1); - expect(batches[0]?.rows).toHaveLength(2); - expect(batches[0]?.rows[0]?.ts).toBe(Date.UTC(2025, 5, 30, 23, 58, 0, 0)); - expect(batches[0]?.rows[1]?.ts).toBe(VAULT_CUTOFF_TS - 1); - }); - - it('rejects rows 1 microsecond before from, 1 microsecond after clamped to, or 1 microsecond after fenced asOf', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const outOfFenceRows: Array<{ label: string; row: Record }> = [ - { label: 'ts 1us before from', row: makeValidRow({ ts_us: (fromUs - 1n).toString() }) }, - { label: 'ts 1us after clamped to', row: makeValidRow({ ts_us: (clampedToUs + 1n).toString() }) }, - { - label: 'known_at 1us after clamped asOf', - row: makeValidRow({ known_at_us: (clampedAsOfUs + 1n).toString() }), - }, - ]; - - for (const testCase of outOfFenceRows) { - executor.setRows([testCase.row]); - await expect(collectBatches(reader.bars(baseQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - }); - - it('rejects invalid SYMBOLs, unrequested listings, non-finite OHLCV/vwap, and invalid timestamps', async () => { - const executor = new RecordingQuestDbExecutor(); - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const malformedRows: Record[] = [ - makeValidRow({ listing_id: '0101' }), - makeValidRow({ listing_id: '-101' }), - makeValidRow({ listing_id: '0' }), - makeValidRow({ listing_id: '2147483648' }), - makeValidRow({ listing_id: 101 }), - makeValidRow({ listing_id: '102' }), // valid INT32 SYMBOL, but unrequested - makeValidRow({ open: Number.NaN }), - makeValidRow({ high: Number.POSITIVE_INFINITY }), - makeValidRow({ low: Number.NEGATIVE_INFINITY }), - makeValidRow({ close: '150.25' }), - makeValidRow({ volume: Number.NaN }), - makeValidRow({ vwap: Number.NaN }), - makeValidRow({ vwap: Number.POSITIVE_INFINITY }), - makeValidRow({ ts_us: 'not-a-timestamp' }), - makeValidRow({ ts_us: 1.5 }), - makeValidRow({ known_at_us: null }), - ]; - - for (const badRow of malformedRows) { - executor.setRows([badRow]); - await expect(collectBatches(reader.bars(baseQuery))).rejects.toThrow( - MarketDataStoreValidationError - ); - } - }); - - it('fails before yielding any batch when a malformed row appears beyond the first batch boundary', async () => { - const executor = new RecordingQuestDbExecutor(); - executor.setRows([ - makeValidRow(), - makeValidRow(), - makeValidRow({ close: Number.NaN }), // row index 2 is past batchSize: 2 - ]); - - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - batchSize: 2, - }); - - const yielded: BarBatch[] = []; - let caught: unknown; - try { - for await (const batch of reader.bars(baseQuery)) { - yielded.push(batch); - } - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect(yielded).toHaveLength(0); - }); - - it('rounds sub-millisecond known_at up so wider-window replay never exposes a bar before arrival', async () => { - // Matches the QuestDB storage fixture: - // ts = 2024-01-02T14:30:00.000000Z (1704205800000000 us) - // known_at = 2024-01-02T14:31:00.000700Z (1704205860000700 us) - const executor = new RecordingQuestDbExecutor(); - executor.setRows([ - { - listing_id: '1042', - ts_us: '1704205800000000', - open: 185.1, - high: 185.5, - low: 184.9, - close: 185.4, - volume: 12500, - vwap: 185.28, - known_at_us: '1704205860000700', - }, - { - listing_id: '1042', - ts_us: '1704205860000000', - open: 185.4, - high: 185.6, - low: 185.3, - close: 185.55, - volume: 8200, - vwap: null, - known_at_us: '1704205920000000', // exact millisecond: 2024-01-02T14:32:00.000000Z - }, - ]); - - const reader = createQuestDbIntradayBarsReader({ - executor, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - - const query: QuestDbBars1mQuery = { - listingIds: [1042], - timeframe: '1m', - from: '2024-01-02T14:30:00.000Z', - to: '2024-01-02T21:00:00.000Z', - asOf: '2024-01-02T21:00:00.000Z', - adjustment: 'raw', - }; - - const run1 = (await collectBatches(reader.bars(query))).flatMap(b => b.rows); - const run2 = (await collectBatches(reader.bars(query))).flatMap(b => b.rows); - expect(run1).toEqual(run2); - expect(run1).toHaveLength(2); - - const decisionAt143100000 = Date.UTC(2024, 0, 2, 14, 31, 0, 0); - const decisionAt143100001 = Date.UTC(2024, 0, 2, 14, 31, 0, 1); - const exactKnownAt143200000 = Date.UTC(2024, 0, 2, 14, 32, 0, 0); - - const subMsBar = run1[0]!; - expect(subMsBar.knownAt).toBe(decisionAt143100001); - // Ineligible at 14:31:00.000 UTC, eligible at 14:31:00.001 UTC. - expect(subMsBar.knownAt <= decisionAt143100000).toBe(false); - expect(subMsBar.knownAt <= decisionAt143100001).toBe(true); - - // Exact whole-millisecond known_at is not pushed forward. - const exactMsBar = run1[1]!; - expect(exactMsBar.knownAt).toBe(exactKnownAt143200000); - expect(exactMsBar.knownAt <= exactKnownAt143200000).toBe(true); - }); -}); diff --git a/libs/research/test/market-data-store-routed.test.ts b/libs/research/test/market-data-store-routed.test.ts deleted file mode 100644 index 81b38fb6..00000000 --- a/libs/research/test/market-data-store-routed.test.ts +++ /dev/null @@ -1,1098 +0,0 @@ -import { describe, expect, it } from 'bun:test'; -import { - type BarBatch, - type BarRecord, - type DuckDbExecutor, - type DuckDbParam, - type MarketDataStore, - MarketDataStoreNotImplementedError, - MarketDataStoreValidationError, - type QuestDbQueryExecutor, - type RoutedMarketDataStoreOptions, - type Table, - type TableRow, - createDuckDbMarketDataStore, - createQuestDbIntradayBarsReader, - createRoutedMarketDataStore, -} from '@stock-bot/research'; -import { createQuestDbIntradayBarsReader as subpathCreateQuestDbIntradayBarsReader } from '@stock-bot/research/market-data-store-questdb'; -import { createRoutedMarketDataStore as subpathCreateRoutedMarketDataStore } from '@stock-bot/research/market-data-store-routed'; -import { - type QueryDataResultPayload, - createMcpServer, - createQueryDataTool, -} from '../src/mcp/index'; - -type BarsQuery = Parameters[0]; -type CrossSectionQuery = Parameters[0]; -type FundamentalsQuery = Parameters[0]; -type EventsQuery = Parameters[0]; -type ShortsQuery = Parameters[0]; -type MacroQuery = Parameters[0]; -type FxQuery = Parameters[0]; -type UniverseQuery = Parameters[0]; - -const LISTING_ID = 42; -const VAULT_CUTOFF_TS = Date.UTC(2025, 6, 1, 0, 0, 0, 0); // 2025-07-01T00:00:00.000Z -const VAULT_CUTOFF_US = VAULT_CUTOFF_TS * 1000; -const CLAMPED_END_ISO = '2025-06-30T23:59:59.999Z'; -const CURATED_ROOT = '/mnt/data/stockbot/curated'; - -function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { - return { - listingId, - ts, - open: close - 0.5, - high: close + 0.5, - low: close - 1, - close, - volume: 1_000, - vwap: close, - knownAt, - }; -} - -async function collectBatches(iterable: AsyncIterable): Promise { - const batches: BarBatch[] = []; - for await (const batch of iterable) { - batches.push(batch); - } - return batches; -} - -class PrototypeDailyStore implements MarketDataStore { - readonly calls: { method: keyof MarketDataStore; arg: unknown }[] = []; - readonly returnedPromises = new Map>(); - readonly barsBatches: BarBatch[]; - - constructor(barsBatches: BarBatch[] = []) { - this.barsBatches = barsBatches; - } - - private assertReceiver(): void { - if (!(this instanceof PrototypeDailyStore)) { - throw new Error('Lost daily receiver (`this`).'); - } - } - - bars(q: BarsQuery): AsyncIterable { - this.assertReceiver(); - this.calls.push({ method: 'bars', arg: q }); - const batches = this.barsBatches; - return { - async *[Symbol.asyncIterator]() { - for (const batch of batches) { - yield batch; - } - }, - }; - } - - crossSection(q: CrossSectionQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'crossSection', arg: q }); - const p = Promise.resolve
({ columns: ['listing_id'], rows: [{ listing_id: 42 }] }); - this.returnedPromises.set('crossSection', p); - return p; - } - - fundamentalsAsOf(q: FundamentalsQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'fundamentalsAsOf', arg: q }); - const p = Promise.resolve
({ columns: ['listing_id', 'revenue'], rows: [] }); - this.returnedPromises.set('fundamentalsAsOf', p); - return p; - } - - events(q: EventsQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'events', arg: q }); - const p = Promise.resolve
({ columns: ['listing_id', 'kind'], rows: [] }); - this.returnedPromises.set('events', p); - return p; - } - - shortsAsOf(q: ShortsQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'shortsAsOf', arg: q }); - const p = Promise.resolve
({ columns: ['listing_id', 'shares_short'], rows: [] }); - this.returnedPromises.set('shortsAsOf', p); - return p; - } - - macroAsOf(q: MacroQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'macroAsOf', arg: q }); - const p = Promise.resolve
({ columns: ['country', 'value'], rows: [] }); - this.returnedPromises.set('macroAsOf', p); - return p; - } - - fx(q: FxQuery): Promise
{ - this.assertReceiver(); - this.calls.push({ method: 'fx', arg: q }); - const p = Promise.resolve
({ columns: ['pair', 'close'], rows: [] }); - this.returnedPromises.set('fx', p); - return p; - } - - universe(q: UniverseQuery): Promise { - this.assertReceiver(); - this.calls.push({ method: 'universe', arg: q }); - const p = Promise.resolve([42, 101]); - this.returnedPromises.set('universe', p); - return p; - } -} - -class PrototypeIntradayReader implements Pick { - readonly calls: BarsQuery[] = []; - readonly barsBatches: BarBatch[]; - - constructor(barsBatches: BarBatch[] = []) { - this.barsBatches = barsBatches; - } - - bars(q: BarsQuery): AsyncIterable { - if (!(this instanceof PrototypeIntradayReader)) { - throw new Error('Lost intraday receiver (`this`).'); - } - this.calls.push(q); - const batches = this.barsBatches; - return { - async *[Symbol.asyncIterator]() { - for (const batch of batches) { - yield batch; - } - }, - }; - } -} - -interface QuestDbFixtureRow { - readonly listing_id: string; - readonly ts_us: number; - readonly open: number; - readonly high: number; - readonly low: number; - readonly close: number; - readonly volume: number; - readonly vwap: number | null; - readonly known_at_us: number; -} - -class PredicateAwareQuestDbExecutor implements QuestDbQueryExecutor { - readonly calls: { readonly sql: string; readonly params: readonly unknown[] }[] = []; - private readonly rows: readonly QuestDbFixtureRow[]; - private readonly leaky: boolean; - - constructor(rows: readonly QuestDbFixtureRow[], options?: { leaky?: boolean }) { - this.rows = rows; - this.leaky = options?.leaky === true; - } - - async query( - sql: string, - params: readonly unknown[] - ): Promise<{ readonly rows: readonly Record[] }> { - this.calls.push({ sql, params: [...params] }); - if (this.leaky) { - return { rows: this.rows as unknown as readonly Record[] }; - } - const fromUs = Date.parse(String(params[0])) * 1000; - const toUs = Date.parse(String(params[1])) * 1000; - const asOfUs = Date.parse(String(params[params.length - 1])) * 1000; - const listingIds = new Set(params.slice(2, params.length - 1).map(String)); - - const filtered = this.rows.filter( - row => - row.ts_us >= fromUs && - row.ts_us <= toUs && - row.known_at_us <= asOfUs && - listingIds.has(row.listing_id) - ); - return { rows: filtered as unknown as readonly Record[] }; - } -} - -class RecordingDuckDbExecutor implements DuckDbExecutor { - readonly runCalls: string[] = []; - readonly queryCalls: { readonly sql: string; readonly params: readonly DuckDbParam[] }[] = []; - private readonly rows: readonly TableRow[]; - - constructor(rows: readonly TableRow[] = []) { - this.rows = rows; - } - - async run(sql: string): Promise { - this.runCalls.push(sql); - } - - async query(sql: string, params: readonly DuckDbParam[]): Promise { - this.queryCalls.push({ sql, params: [...params] }); - return this.rows; - } -} - -describe('package exports', () => { - it('re-exports createRoutedMarketDataStore and createQuestDbIntradayBarsReader from root and subpaths', () => { - expect(createRoutedMarketDataStore).toBe(subpathCreateRoutedMarketDataStore); - expect(createQuestDbIntradayBarsReader).toBe(subpathCreateQuestDbIntradayBarsReader); - }); -}); - -describe('createRoutedMarketDataStore', () => { - describe('constructor validation', () => { - it('rejects null, primitives, arrays, and class instances for options', () => { - const invalidOptions: unknown[] = [ - null, - undefined, - 42, - 'options', - true, - [], - new Date(), - new (class OptionsClass { - daily = new PrototypeDailyStore(); - intraday = new PrototypeIntradayReader(); - })(), - ]; - - for (const bad of invalidOptions) { - let caught: unknown; - try { - createRoutedMarketDataStore(bad as RoutedMarketDataStoreOptions); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('options'); - } - }); - - it('accepts a null-prototype options object and prototype-backed delegates', () => { - const options = Object.create(null) as { - daily: MarketDataStore; - intraday: Pick; - }; - options.daily = new PrototypeDailyStore(); - options.intraday = new PrototypeIntradayReader(); - - const store = createRoutedMarketDataStore(options); - expect(typeof store.bars).toBe('function'); - }); - - it('rejects missing or malformed daily delegate and each missing daily method', () => { - const intraday = new PrototypeIntradayReader(); - - for (const badDaily of [null, undefined, 'daily', 123, []]) { - let caught: unknown; - try { - createRoutedMarketDataStore({ - daily: badDaily as unknown as MarketDataStore, - intraday, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('daily'); - } - - const requiredMethods: (keyof MarketDataStore)[] = [ - 'bars', - 'crossSection', - 'fundamentalsAsOf', - 'events', - 'shortsAsOf', - 'macroAsOf', - 'fx', - 'universe', - ]; - - for (const missingMethod of requiredMethods) { - const base = new PrototypeDailyStore(); - const incomplete: Record = { - bars: base.bars.bind(base), - crossSection: base.crossSection.bind(base), - fundamentalsAsOf: base.fundamentalsAsOf.bind(base), - events: base.events.bind(base), - shortsAsOf: base.shortsAsOf.bind(base), - macroAsOf: base.macroAsOf.bind(base), - fx: base.fx.bind(base), - universe: base.universe.bind(base), - }; - delete incomplete[missingMethod]; - - let caughtMissing: unknown; - try { - createRoutedMarketDataStore({ - daily: incomplete as unknown as MarketDataStore, - intraday, - }); - } catch (err) { - caughtMissing = err; - } - expect(caughtMissing).toBeInstanceOf(MarketDataStoreValidationError); - expect((caughtMissing as MarketDataStoreValidationError).field).toBe( - `daily.${missingMethod}` - ); - - incomplete[missingMethod] = 'not-a-function'; - let caughtNonFn: unknown; - try { - createRoutedMarketDataStore({ - daily: incomplete as unknown as MarketDataStore, - intraday, - }); - } catch (err) { - caughtNonFn = err; - } - expect(caughtNonFn).toBeInstanceOf(MarketDataStoreValidationError); - expect((caughtNonFn as MarketDataStoreValidationError).field).toBe( - `daily.${missingMethod}` - ); - } - }); - - it('rejects missing or non-callable intraday delegate and intraday.bars', () => { - const daily = new PrototypeDailyStore(); - - for (const badIntraday of [null, undefined, 'intraday', 99, []]) { - let caught: unknown; - try { - createRoutedMarketDataStore({ - daily, - intraday: badIntraday as unknown as Pick, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('intraday'); - } - - for (const badBars of [undefined, null, 'bars', 42, {}]) { - let caught: unknown; - try { - createRoutedMarketDataStore({ - daily, - intraday: { bars: badBars } as unknown as Pick, - }); - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect((caught as MarketDataStoreValidationError).field).toBe('intraday.bars'); - } - }); - }); - - describe('routing and delegation', () => { - it('routes 1m bars exclusively to intraday and 1d bars exclusively to daily with exact query identity', async () => { - const intradayBatch: BarBatch = { - rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 101.25)], - }; - const dailyBatch: BarBatch = { - rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 20, 0, 0), 102.5)], - }; - const daily = new PrototypeDailyStore([dailyBatch]); - const intraday = new PrototypeIntradayReader([intradayBatch]); - const store = createRoutedMarketDataStore({ daily, intraday }); - - const q1m: BarsQuery = { - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30', - to: '2025-06-30', - adjustment: 'raw', - }; - const q1d: BarsQuery = { - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-06-01', - to: '2025-06-30', - adjustment: 'raw', - }; - - const intradayOut = await collectBatches(store.bars(q1m)); - expect(intraday.calls).toHaveLength(1); - expect(intraday.calls[0]).toBe(q1m); - expect(daily.calls).toHaveLength(0); - expect(intradayOut).toHaveLength(1); - expect(intradayOut[0]).toBe(intradayBatch); - - const dailyOut = await collectBatches(store.bars(q1d)); - expect(daily.calls).toHaveLength(1); - expect(daily.calls[0]?.method).toBe('bars'); - expect(daily.calls[0]?.arg).toBe(q1d); - expect(intraday.calls).toHaveLength(1); - expect(dailyOut).toHaveLength(1); - expect(dailyOut[0]).toBe(dailyBatch); - }); - - it('forwards invalid timeframe values and non-object inputs to daily unchanged', async () => { - const daily = new PrototypeDailyStore(); - const intraday = new PrototypeIntradayReader(); - const store = createRoutedMarketDataStore({ daily, intraday }); - - const arrayWithTimeframe = Object.assign(['1m'], { timeframe: '1m' }); - const malformedInputs: unknown[] = [ - null, - undefined, - '1m', - 42, - ['1m'], - arrayWithTimeframe, - { listingIds: [42], timeframe: '2m', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, - { listingIds: [42], timeframe: '', from: '2025-06-01', to: '2025-06-30', adjustment: 'raw' }, - ]; - - for (const badInput of malformedInputs) { - await collectBatches(store.bars(badInput as BarsQuery)); - } - - expect(intraday.calls).toHaveLength(0); - expect(daily.calls).toHaveLength(malformedInputs.length); - for (let i = 0; i < malformedInputs.length; i += 1) { - expect(daily.calls[i]?.method).toBe('bars'); - expect(daily.calls[i]?.arg).toBe(malformedInputs[i]); - } - }); - - it('preserves DuckDB MarketDataStoreNotImplementedError for 5m and 1h with zero executor or intraday calls', async () => { - const duckExecutor = new RecordingDuckDbExecutor(); - const daily = createDuckDbMarketDataStore({ - executor: duckExecutor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - const intraday = new PrototypeIntradayReader(); - const store = createRoutedMarketDataStore({ daily, intraday }); - - for (const timeframe of ['5m', '1h'] as const) { - let caught: unknown; - try { - for await (const _batch of store.bars({ - listingIds: [LISTING_ID], - timeframe, - from: '2025-06-01', - to: '2025-06-30', - adjustment: 'raw', - })) { - // unreachable - } - } catch (err) { - caught = err; - } - expect(caught).toBeInstanceOf(MarketDataStoreNotImplementedError); - } - - expect(duckExecutor.runCalls).toHaveLength(0); - expect(duckExecutor.queryCalls).toHaveLength(0); - expect(intraday.calls).toHaveLength(0); - }); - - it('delegates all seven non-bars methods (including fx 1m) to daily with argument, receiver, and promise identity', async () => { - const daily = new PrototypeDailyStore(); - const intraday = new PrototypeIntradayReader(); - const store = createRoutedMarketDataStore({ daily, intraday }); - - const crossSectionArg: CrossSectionQuery = { - features: ['ret_1d@v1'], - date: '2025-06-30', - universe: 'US_EQ', - }; - const fundamentalsArg: FundamentalsQuery = { - listingIds: [LISTING_ID], - fields: ['revenue'], - asOf: '2025-06-30', - }; - const eventsArg: EventsQuery = { - kinds: ['filing'], - listingIds: [LISTING_ID], - from: '2025-06-01', - to: '2025-06-30', - }; - const shortsArg: ShortsQuery = { - listingIds: [LISTING_ID], - from: '2025-06-01', - to: '2025-06-30', - }; - const macroArg: MacroQuery = { - countries: ['US'], - indicators: ['CPI'], - from: '2025-06-01', - to: '2025-06-30', - }; - const fxArg: FxQuery = { - pair: 'USD.CAD', - timeframe: '1m', - from: '2025-06-01', - to: '2025-06-30', - }; - const universeArg: UniverseQuery = { - ref: 'US_EQ', - date: '2025-06-30', - }; - - const pCrossSection = store.crossSection(crossSectionArg); - const pFundamentals = store.fundamentalsAsOf(fundamentalsArg); - const pEvents = store.events(eventsArg); - const pShorts = store.shortsAsOf(shortsArg); - const pMacro = store.macroAsOf(macroArg); - const pFx = store.fx(fxArg); - const pUniverse = store.universe(universeArg); - - expect(pCrossSection).toBe(daily.returnedPromises.get('crossSection') as Promise
); - expect(pFundamentals).toBe(daily.returnedPromises.get('fundamentalsAsOf') as Promise
); - expect(pEvents).toBe(daily.returnedPromises.get('events') as Promise
); - expect(pShorts).toBe(daily.returnedPromises.get('shortsAsOf') as Promise
); - expect(pMacro).toBe(daily.returnedPromises.get('macroAsOf') as Promise
); - expect(pFx).toBe(daily.returnedPromises.get('fx') as Promise
); - expect(pUniverse).toBe(daily.returnedPromises.get('universe') as Promise); - - await Promise.all([ - pCrossSection, - pFundamentals, - pEvents, - pShorts, - pMacro, - pFx, - pUniverse, - ]); - - expect(intraday.calls).toHaveLength(0); - expect(daily.calls).toHaveLength(7); - expect(daily.calls[0]).toEqual({ method: 'crossSection', arg: crossSectionArg }); - expect(daily.calls[0]?.arg).toBe(crossSectionArg); - expect(daily.calls[1]).toEqual({ method: 'fundamentalsAsOf', arg: fundamentalsArg }); - expect(daily.calls[1]?.arg).toBe(fundamentalsArg); - expect(daily.calls[2]).toEqual({ method: 'events', arg: eventsArg }); - expect(daily.calls[2]?.arg).toBe(eventsArg); - expect(daily.calls[3]).toEqual({ method: 'shortsAsOf', arg: shortsArg }); - expect(daily.calls[3]?.arg).toBe(shortsArg); - expect(daily.calls[4]).toEqual({ method: 'macroAsOf', arg: macroArg }); - expect(daily.calls[4]?.arg).toBe(macroArg); - expect(daily.calls[5]).toEqual({ method: 'fx', arg: fxArg }); - expect(daily.calls[5]?.arg).toBe(fxArg); - expect(daily.calls[6]).toEqual({ method: 'universe', arg: universeArg }); - expect(daily.calls[6]?.arg).toBe(universeArg); - }); - }); - - describe('error propagation and lazy iteration', () => { - it('propagates exact error instances for sync throws, promise rejections, and mid-iteration failures', async () => { - const syncIntradayErr = new Error('sync intraday boom'); - const syncDailyErr = new Error('sync daily boom'); - const rejectedUniverseErr = new Error('async universe boom'); - const iterErr = new Error('mid-iteration boom'); - - const baseDaily = new PrototypeDailyStore(); - const firstBatch: BarBatch = { - rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], - }; - - const dailySyncStore = createRoutedMarketDataStore({ - daily: { - bars: () => { - throw syncDailyErr; - }, - crossSection: baseDaily.crossSection.bind(baseDaily), - fundamentalsAsOf: baseDaily.fundamentalsAsOf.bind(baseDaily), - events: baseDaily.events.bind(baseDaily), - shortsAsOf: baseDaily.shortsAsOf.bind(baseDaily), - macroAsOf: baseDaily.macroAsOf.bind(baseDaily), - fx: baseDaily.fx.bind(baseDaily), - universe: () => Promise.reject(rejectedUniverseErr), - }, - intraday: { - bars: () => { - throw syncIntradayErr; - }, - }, - }); - - let caughtSyncIntraday: unknown; - try { - dailySyncStore.bars({ - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30', - to: '2025-06-30', - adjustment: 'raw', - }); - } catch (err) { - caughtSyncIntraday = err; - } - expect(caughtSyncIntraday).toBe(syncIntradayErr); - - let caughtSyncDaily: unknown; - try { - dailySyncStore.bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-06-30', - to: '2025-06-30', - adjustment: 'raw', - }); - } catch (err) { - caughtSyncDaily = err; - } - expect(caughtSyncDaily).toBe(syncDailyErr); - - let caughtRejected: unknown; - try { - await dailySyncStore.universe({ ref: 'US_EQ', date: '2025-06-30' }); - } catch (err) { - caughtRejected = err; - } - expect(caughtRejected).toBe(rejectedUniverseErr); - - const iterFailStore = createRoutedMarketDataStore({ - daily: baseDaily, - intraday: { - bars() { - return { - async *[Symbol.asyncIterator]() { - yield firstBatch; - throw iterErr; - }, - }; - }, - }, - }); - - const received: BarBatch[] = []; - let caughtIter: unknown; - try { - for await (const batch of iterFailStore.bars({ - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30', - to: '2025-06-30', - adjustment: 'raw', - })) { - received.push(batch); - } - } catch (err) { - caughtIter = err; - } - expect(received).toHaveLength(1); - expect(received[0]).toBe(firstBatch); - expect(caughtIter).toBe(iterErr); - }); - - it('preserves lazy iteration and closes the delegate iterator on early exit', async () => { - const batch1: BarBatch = { - rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 30, 0), 100)], - }; - const batch2: BarBatch = { - rows: [makeBar(LISTING_ID, Date.UTC(2025, 5, 30, 13, 31, 0), 101)], - }; - let nextCalls = 0; - let returnCalls = 0; - - const store = createRoutedMarketDataStore({ - daily: new PrototypeDailyStore(), - intraday: { - bars() { - return { - [Symbol.asyncIterator]() { - const batches = [batch1, batch2]; - return { - async next() { - const idx = nextCalls; - nextCalls += 1; - const value = batches[idx]; - if (value === undefined) { - return { done: true as const, value: undefined }; - } - return { done: false as const, value }; - }, - async return() { - returnCalls += 1; - return { done: true as const, value: undefined }; - }, - }; - }, - }; - }, - }, - }); - - const consumed: BarBatch[] = []; - for await (const batch of store.bars({ - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30', - to: '2025-06-30', - adjustment: 'raw', - })) { - consumed.push(batch); - break; - } - - expect(consumed).toHaveLength(1); - expect(consumed[0]).toBe(batch1); - expect(nextCalls).toBe(1); - expect(returnCalls).toBe(1); - }); - }); - - describe('QuestDB intraday reader integration and Vault fence', () => { - const preCutoffTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; - const preCutoffTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; - const fixtureRows: readonly QuestDbFixtureRow[] = [ - { - listing_id: String(LISTING_ID), - ts_us: preCutoffTs1Us, - open: 100.0, - high: 101.0, - low: 99.5, - close: 100.5, - volume: 500, - vwap: 100.25, - known_at_us: preCutoffTs1Us + 60_000_000, - }, - { - listing_id: String(LISTING_ID), - ts_us: preCutoffTs2Us, - open: 100.5, - high: 101.5, - low: 100.25, - close: 101.25, - volume: 750, - vwap: 101.0, - known_at_us: preCutoffTs2Us + 60_000_000, - }, - // Row with ts exactly at Vault cutoff (must be excluded by fence) - { - listing_id: String(LISTING_ID), - ts_us: VAULT_CUTOFF_US, - open: 102.0, - high: 103.0, - low: 101.5, - close: 102.5, - volume: 900, - vwap: 102.25, - known_at_us: preCutoffTs2Us + 60_000_000, - }, - // Row with known_at exactly at Vault cutoff (must be excluded by fence) - { - listing_id: String(LISTING_ID), - ts_us: preCutoffTs2Us + 60_000_000, - open: 101.25, - high: 102.0, - low: 101.0, - close: 101.75, - volume: 600, - vwap: 101.5, - known_at_us: VAULT_CUTOFF_US, - }, - ]; - - const straddlingQuery: BarsQuery = { - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30T13:30:00Z', - to: '2025-07-05T20:00:00Z', - adjustment: 'raw', - asOf: '2025-07-10T00:00:00Z', - }; - - it('streams batches unchanged from createQuestDbIntradayBarsReader and clamps to/asOf strictly below vaultCutoffTs', async () => { - const directExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); - const directReader = createQuestDbIntradayBarsReader({ - executor: directExecutor, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - batchSize: 1, - }); - - const routedExecutor = new PredicateAwareQuestDbExecutor(fixtureRows); - const underlyingIntraday = createQuestDbIntradayBarsReader({ - executor: routedExecutor, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - batchSize: 1, - }); - - const yieldedByIntraday: BarBatch[] = []; - const recordingIntraday: Pick = { - bars(q) { - const inner = underlyingIntraday.bars(q); - return { - async *[Symbol.asyncIterator]() { - for await (const batch of inner) { - yieldedByIntraday.push(batch); - yield batch; - } - }, - }; - }, - }; - - const daily = new PrototypeDailyStore(); - const store = createRoutedMarketDataStore({ daily, intraday: recordingIntraday }); - - const directBatches = await collectBatches(directReader.bars(straddlingQuery)); - const routedBatches = await collectBatches(store.bars(straddlingQuery)); - - expect(daily.calls).toHaveLength(0); - expect(routedExecutor.calls).toHaveLength(1); - expect(routedExecutor.calls[0]?.params[1]).toBe(CLAMPED_END_ISO); - expect(routedExecutor.calls[0]?.params[3]).toBe(CLAMPED_END_ISO); - - expect(routedBatches).toEqual(directBatches); - expect(routedBatches).toHaveLength(2); - expect(routedBatches[0]).toBe(yieldedByIntraday[0]); - expect(routedBatches[1]).toBe(yieldedByIntraday[1]); - - for (const batch of routedBatches) { - for (const row of batch.rows) { - expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); - expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); - } - } - }); - - it('rejects a leaky QuestDB executor returning a row with ts or known_at at vaultCutoffTs before yielding any batch', async () => { - const tsCutoffRow = fixtureRows[2] as QuestDbFixtureRow; - const knownAtCutoffRow = fixtureRows[3] as QuestDbFixtureRow; - const preCutoffRow = fixtureRows[0] as QuestDbFixtureRow; - - for (const leakyRows of [ - [preCutoffRow, tsCutoffRow], - [preCutoffRow, knownAtCutoffRow], - ]) { - const leakyExecutor = new PredicateAwareQuestDbExecutor(leakyRows, { leaky: true }); - const intraday = createQuestDbIntradayBarsReader({ - executor: leakyExecutor, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - batchSize: 1, - }); - const store = createRoutedMarketDataStore({ - daily: new PrototypeDailyStore(), - intraday, - }); - - const yielded: BarBatch[] = []; - let caught: unknown; - try { - for await (const batch of store.bars(straddlingQuery)) { - yielded.push(batch); - } - } catch (err) { - caught = err; - } - - expect(caught).toBeInstanceOf(MarketDataStoreValidationError); - expect(yielded).toHaveLength(0); - } - }); - }); - - describe('MCP query_data end-to-end over routed store', () => { - it('routes 1m calls to fake QuestDB and 1d calls to fake DuckDB, enforcing the Vault cutoff deterministically', async () => { - const intradayTs1Us = Date.UTC(2025, 5, 30, 13, 30, 0, 0) * 1000; - const intradayTs2Us = Date.UTC(2025, 5, 30, 13, 31, 0, 0) * 1000; - const questDbRows: readonly QuestDbFixtureRow[] = [ - { - listing_id: String(LISTING_ID), - ts_us: intradayTs1Us, - open: 100.0, - high: 100.75, - low: 99.5, - close: 100.5, - volume: 1_200, - vwap: 100.2, - known_at_us: intradayTs1Us + 60_000_000, - }, - { - listing_id: String(LISTING_ID), - ts_us: intradayTs2Us, - open: 100.5, - high: 101.25, - low: 100.25, - close: 101.0, - volume: 1_500, - vwap: 100.8, - known_at_us: intradayTs2Us + 60_000_000, - }, - // Out-of-fence rows at exact cutoff (filtered by predicate-aware executor) - { - listing_id: String(LISTING_ID), - ts_us: VAULT_CUTOFF_US, - open: 105.0, - high: 106.0, - low: 104.0, - close: 105.5, - volume: 2_000, - vwap: 105.2, - known_at_us: intradayTs2Us + 60_000_000, - }, - { - listing_id: String(LISTING_ID), - ts_us: intradayTs2Us + 60_000_000, - open: 101.0, - high: 101.5, - low: 100.75, - close: 101.25, - volume: 1_100, - vwap: 101.1, - known_at_us: VAULT_CUTOFF_US, - }, - ]; - - const dailyBarTs = Date.UTC(2025, 5, 30, 20, 0, 0, 0); - const duckDbRows: readonly TableRow[] = [ - { - listing_id: LISTING_ID, - ts: dailyBarTs, - open: 99.0, - high: 102.0, - low: 98.5, - close: 101.5, - volume: 250_000, - vwap: 100.75, - known_at: dailyBarTs, - }, - ]; - - const questExecutor = new PredicateAwareQuestDbExecutor(questDbRows); - const duckExecutor = new RecordingDuckDbExecutor(duckDbRows); - - const daily = createDuckDbMarketDataStore({ - executor: duckExecutor, - curatedRoot: CURATED_ROOT, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - }); - const intraday = createQuestDbIntradayBarsReader({ - executor: questExecutor, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - }); - const routedStore = createRoutedMarketDataStore({ daily, intraday }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: routedStore, - vaultContext: { - vaultCutoffTs: VAULT_CUTOFF_TS, - }, - }), - ], - }); - - const direct1mBatches = await collectBatches( - createQuestDbIntradayBarsReader({ - executor: new PredicateAwareQuestDbExecutor(questDbRows), - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - }).bars({ - listingIds: [LISTING_ID], - timeframe: '1m', - from: '2025-06-30', - to: '2025-07-05', - adjustment: 'raw', - }) - ); - const expected1mRows = direct1mBatches.flatMap(b => b.rows); - - const req1m = JSON.stringify({ - jsonrpc: '2.0', - id: 'mcp-1m', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [LISTING_ID], - from: '2025-06-30', - to: '2025-07-05', - timeframe: '1m', - adjustment: 'raw', - }, - }, - }); - - const raw1mFirst = await server.handleMessage(req1m); - const raw1mSecond = await server.handleMessage(req1m); - expect(raw1mFirst).not.toBeNull(); - expect(raw1mSecond).toBe(raw1mFirst); - - expect(questExecutor.calls).toHaveLength(2); - expect(duckExecutor.queryCalls).toHaveLength(0); - expect(duckExecutor.runCalls).toHaveLength(0); - - const resp1m = JSON.parse(raw1mFirst as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(resp1m.result.isError).toBeUndefined(); - const payload1m = JSON.parse(resp1m.result.content[0]?.text ?? '') as QueryDataResultPayload; - expect(payload1m.rows).toEqual(expected1mRows); - expect(payload1m.rows).toHaveLength(2); - for (const row of payload1m.rows) { - expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); - expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); - } - - const direct1dBatches = await collectBatches( - createDuckDbMarketDataStore({ - executor: new RecordingDuckDbExecutor(duckDbRows), - curatedRoot: CURATED_ROOT, - vaultCutoffTs: VAULT_CUTOFF_TS, - vaultOperatorAuthorized: false, - }).bars({ - listingIds: [LISTING_ID], - timeframe: '1d', - from: '2025-06-25', - to: '2025-07-05', - adjustment: 'raw', - }) - ); - const expected1dRows = direct1dBatches.flatMap(b => b.rows); - - const req1d = JSON.stringify({ - jsonrpc: '2.0', - id: 'mcp-1d', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [LISTING_ID], - from: '2025-06-25', - to: '2025-07-05', - timeframe: '1d', - adjustment: 'raw', - }, - }, - }); - - const raw1dFirst = await server.handleMessage(req1d); - const raw1dSecond = await server.handleMessage(req1d); - expect(raw1dFirst).not.toBeNull(); - expect(raw1dSecond).toBe(raw1dFirst); - - expect(questExecutor.calls).toHaveLength(2); - expect(duckExecutor.queryCalls).toHaveLength(2); - - const resp1d = JSON.parse(raw1dFirst as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(resp1d.result.isError).toBeUndefined(); - const payload1d = JSON.parse(resp1d.result.content[0]?.text ?? '') as QueryDataResultPayload; - expect(payload1d.rows).toEqual(expected1dRows); - expect(payload1d.rows).toHaveLength(1); - for (const row of payload1d.rows) { - expect(row.ts).toBeLessThan(VAULT_CUTOFF_TS); - expect(row.knownAt).toBeLessThan(VAULT_CUTOFF_TS); - } - }); - }); -}); diff --git a/libs/research/test/mcp-analyze-signal-qa.test.ts b/libs/research/test/mcp-analyze-signal-qa.test.ts deleted file mode 100644 index 78f010c8..00000000 --- a/libs/research/test/mcp-analyze-signal-qa.test.ts +++ /dev/null @@ -1,820 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type BarBatch, - type BarRecord, - type MarketDataStore, - MarketDataStoreValidationError, - type Table, - type TableRow, -} from '../src/market-data-store'; -import { - type BarsQuery, - MarketDataStoreNotImplementedError, - type ShortsAsOfQuery, - type UniverseQuery, -} from '../src/market-data-store-duckdb'; -import { - type AnalyzeSignalResultPayload, - createAnalyzeSignalTool, - createMcpServer, -} from '../src/mcp/index'; -import { - SignalPanelError, - buildForwardReturnPanel, - shortsTableToSignalRows, -} from '../src/signal-panel'; -import { TrialLedgerError, type TrialLedgerExecutor } from '../src/trial-ledger'; - -// QA fixture: seeded synthetic short-interest panel (SEED below), 12 listings, -// 140 pre-cutoff + 10 post-cutoff business sessions from 2022-09-01, shorts -// every 10 sessions published T+4 at 22:00 UTC, gross close-to-close returns, -// raw adjustment, no fills or fees. -const SEED = 4_242_026; -const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const POISON = 'POISON' as unknown as number; -const SHORTS_COLUMNS = [ - 'listing_id', - 'report_date', - 'known_at', - 'shares_short', - 'net_change', - 'pct_float', - 'source', -] as const; - -function createSeededRng(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = []; - const current = new Date(`${startDate}T00:00:00.000Z`); - while (out.length < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out.push(current.toISOString().slice(0, 10)); - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function utcMs(date: string, hour: number, minute = 0): number { - return Date.parse(`${date}T00:00:00.000Z`) + hour * 3_600_000 + minute * 60_000; -} - -interface Fixture { - readonly listingIds: number[]; - readonly allDates: string[]; - readonly cutoffDate: string; - readonly cutoffTs: number; - readonly bars: BarRecord[]; - readonly shorts: Table; -} - -function buildFixture(): Fixture { - const rand = createSeededRng(SEED); - const listingCount = 12; - const pre = 140; - const allDates = makeBusinessDates('2022-09-01', pre + 10); - const cutoffDate = allDates[pre]!; - const listingIds = Array.from({ length: listingCount }, (_, i) => 70_001 + i); - const bars: BarRecord[] = []; - const shortsRows: TableRow[] = []; - const active = new Float64Array(listingCount); - const pending = new Map(); - const prices = Array.from({ length: listingCount }, (_, l) => 20 + l); - - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const released = pending.get(t - 1); - if (released !== undefined) { - for (let l = 0; l < listingCount; l += 1) { - active[l] = released[l]! / 20_000; - } - } - if (t % 10 === 0 && t + 4 < allDates.length) { - const knownAt = utcMs(allDates[t + 4]!, 22); - const values: number[] = []; - for (let l = 0; l < listingCount; l += 1) { - const netChange = Math.round((rand() * 2 - 1) * 20_000); - values.push(netChange); - shortsRows.push({ - listing_id: listingIds[l]!, - report_date: date, - known_at: knownAt, - shares_short: 100_000 + Math.round(rand() * 10_000), - net_change: netChange, - pct_float: Number((0.02 + rand() * 0.08).toFixed(4)), - source: 'ceoShorts', - }); - } - pending.set(t + 4, values); - } - for (let l = 0; l < listingCount; l += 1) { - prices[l] = Math.max(0.5, prices[l]! * (1 - 0.004 * active[l]! + (rand() * 2 - 1) * 0.008)); - const close = Number(prices[l]!.toFixed(6)); - const ts = utcMs(date, 21); - bars.push({ - listingId: listingIds[l]!, - ts, - open: close, - high: close, - low: close, - close, - volume: 10_000, - knownAt: ts, - }); - } - } - - return { - listingIds, - allDates, - cutoffDate, - cutoffTs: utcMs(cutoffDate, 0), - bars, - shorts: { columns: SHORTS_COLUMNS, rows: shortsRows }, - }; -} - -function parseBound(raw: string, endOfDay: boolean): number { - if (raw.length === 10) { - return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); - } - return Date.parse(raw); -} - -interface FakeStore { - readonly store: MarketDataStore; - readonly barsCalls: BarsQuery[]; - readonly shortsCalls: ShortsAsOfQuery[]; - readonly universeCalls: UniverseQuery[]; -} - -/** - * Correctly filtering store; `extraBars` / `extraShorts` are appended - * unconditionally to simulate an adapter that leaks rows past its filters. - */ -function createStore( - fixture: Fixture, - options?: { - extraBars?: readonly BarRecord[]; - extraShorts?: readonly TableRow[]; - universe?: (q: UniverseQuery) => number[]; - barsThrow?: unknown; - shortsThrow?: unknown; - } -): FakeStore { - const barsCalls: BarsQuery[] = []; - const shortsCalls: ShortsAsOfQuery[] = []; - const universeCalls: UniverseQuery[] = []; - const store: MarketDataStore = { - bars(q: BarsQuery): AsyncIterable { - barsCalls.push(q); - const ids = new Set(q.listingIds); - const fromMs = parseBound(q.from, false); - const toMs = parseBound(q.to, true); - const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); - const rows = fixture.bars.filter( - b => - ids.has(b.listingId) && - b.ts >= fromMs && - b.ts <= toMs && - b.ts <= asOfMs && - b.knownAt <= asOfMs - ); - const thrown = options?.barsThrow; - return { - async *[Symbol.asyncIterator]() { - if (thrown !== undefined) { - throw thrown; - } - yield { rows: [...rows, ...(options?.extraBars ?? [])] }; - }, - }; - }, - async shortsAsOf(q: ShortsAsOfQuery): Promise
{ - shortsCalls.push(q); - if (options?.shortsThrow !== undefined) { - throw options.shortsThrow; - } - const ids = new Set(q.listingIds); - const fromDate = q.from.slice(0, 10); - const toDate = q.to.slice(0, 10); - const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); - const rows = fixture.shorts.rows.filter( - r => - ids.has(r.listing_id as number) && - (r.report_date as string) >= fromDate && - (r.report_date as string) <= toDate && - (r.known_at as number) <= asOfMs - ); - return { columns: fixture.shorts.columns, rows: [...rows, ...(options?.extraShorts ?? [])] }; - }, - async universe(q: UniverseQuery): Promise { - universeCalls.push(q); - return options?.universe?.(q) ?? []; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - return { store, barsCalls, shortsCalls, universeCalls }; -} - -interface LedgerRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -function createLedger(options?: { insertThrow?: unknown }): { - executor: TrialLedgerExecutor; - rows: LedgerRow[]; -} { - const rows: LedgerRow[] = []; - const executor: TrialLedgerExecutor = { - async query>(text: string, params?: readonly unknown[]) { - const sql = text.trimStart(); - if (sql.startsWith('INSERT INTO trial_ledger')) { - if (options?.insertThrow !== undefined) { - throw options.insertThrow; - } - const p = params ?? []; - const id = rows.length + 1; - const row: LedgerRow = { - trial_id: String(id), - created_at: new Date(Date.UTC(2024, 0, 1, 0, 0, id)), - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)), - }; - rows.push(row); - return { - rows: [{ trial_id: row.trial_id, created_at: row.created_at } as unknown as Row], - rowCount: 1, - }; - } - if (sql.startsWith('SELECT')) { - if (text.includes('WHERE trial_id = $1::bigint')) { - const m = rows.filter(r => r.trial_id === String(params?.[0])); - return { rows: m as unknown as Row[], rowCount: m.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const m = rows.filter( - r => r.universe_market === params?.[0] && r.horizon_bucket === params?.[1] - ); - return { rows: m as unknown as Row[], rowCount: m.length }; - } - } - return { rows: [], rowCount: 0 }; - }, - }; - return { executor, rows }; -} - -async function call(params: { - store: MarketDataStore; - ledger: TrialLedgerExecutor; - cutoffTs: number; - args: Record; - principalId?: string; -}): Promise<{ raw: string; isError: boolean; text: string }> { - const server = createMcpServer({ - name: 'qa', - version: '0.0.0', - tools: [ - createAnalyzeSignalTool({ - store: params.store, - ledger: params.ledger, - vaultContext: { vaultCutoffTs: params.cutoffTs }, - principalId: params.principalId ?? AGENT_PRINCIPAL, - }), - ], - }); - const raw = (await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/call', - params: { name: 'analyze_signal', arguments: params.args }, - }) - )) as string; - const parsed = JSON.parse(raw) as { - result: { isError?: boolean; content: { text: string }[] }; - }; - return { - raw, - isError: parsed.result.isError === true, - text: parsed.result.content[0]?.text ?? '', - }; -} - -function baseArgs(fixture: Fixture): Record { - return { - listingIds: fixture.listingIds, - from: fixture.allDates[0]!, - to: fixture.allDates[fixture.allDates.length - 1]!, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; -} - -function poisonBar(listingId: number, ts: number, knownAt: number): BarRecord { - return { - listingId, - ts, - open: POISON, - high: POISON, - low: POISON, - close: POISON, - volume: 1, - knownAt, - }; -} - -function poisonShort(listingId: number, reportDate: string, knownAt: number): TableRow { - return { - listing_id: listingId, - report_date: reportDate, - known_at: knownAt, - shares_short: POISON, - net_change: POISON, - pct_float: POISON, - source: 'poison', - }; -} - -describe('analyze_signal QA: sentinel rows that would fail panel validation if forwarded', () => { - test('positive control: a poison bar or poison shorts row inside the window reaches the panel and maps to a fixed SignalPanelError', async () => { - const fixture = buildFixture(); - const inWindowTs = utcMs(fixture.allDates[50]!, 21); - - expect(() => - shortsTableToSignalRows( - { columns: SHORTS_COLUMNS, rows: [poisonShort(fixture.listingIds[0]!, '2022-10-03', 1)] }, - 'net_change' - ) - ).toThrow(SignalPanelError); - - const leakedBar = await call({ - store: createStore(fixture, { - extraBars: [poisonBar(fixture.listingIds[0]!, inWindowTs + 60_000, inWindowTs + 60_000)], - }).store, - ledger: createLedger().executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - expect(leakedBar.isError).toBe(true); - expect(leakedBar.text).toBe('SignalPanelError: Market bar data failed panel validation.'); - expect(leakedBar.raw).not.toContain('POISON'); - - const ledger = createLedger(); - const leakedShort = await call({ - store: createStore(fixture, { - extraShorts: [poisonShort(fixture.listingIds[0]!, fixture.allDates[50]!, inWindowTs)], - }).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - expect(leakedShort.isError).toBe(true); - expect(leakedShort.text).toBe('SignalPanelError: Signal table data failed panel validation.'); - expect(leakedShort.raw).not.toContain('POISON'); - expect(ledger.rows).toHaveLength(0); - }); - - test('midnight Vault clamp: sentinels at/after the cutoff, before from, or for foreign listings never reach the panel; result equals clean replay', async () => { - const fixture = buildFixture(); - const lid = fixture.listingIds[3]!; - const extraBars = [ - poisonBar(lid, fixture.cutoffTs, fixture.cutoffTs - 1), // exact cutoff ts, backdated knownAt - poisonBar(lid, utcMs(fixture.allDates[100]!, 21), fixture.cutoffTs), // knownAt at cutoff - poisonBar(99_999, utcMs(fixture.allDates[100]!, 15), utcMs(fixture.allDates[100]!, 15)), - poisonBar(lid, utcMs('2022-08-15', 21), utcMs('2022-08-15', 21)), // before from - ]; - const extraShorts = [ - poisonShort(lid, fixture.cutoffDate, fixture.cutoffTs - 1), // cutoff-day report, backdated - poisonShort(lid, fixture.allDates[100]!, fixture.cutoffTs), // known exactly at cutoff - poisonShort(99_999, fixture.allDates[100]!, utcMs(fixture.allDates[105]!, 22)), - poisonShort(lid, '2022-08-15', utcMs('2022-08-19', 22)), // report before from - ]; - - const cleanLedger = createLedger(); - const clean = await call({ - store: createStore(fixture).store, - ledger: cleanLedger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - const poisonedLedger = createLedger(); - const poisoned = await call({ - store: createStore(fixture, { extraBars, extraShorts }).store, - ledger: poisonedLedger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - - expect(clean.isError).toBe(false); - expect(poisoned.isError).toBe(false); - const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; - expect(payload.status).toBe('ok'); - expect(payload.clampedTo).toBe(true); - // Omitted asOf defaults to the already-clamped `to`, so only `to` reports a clamp. - expect(payload.clampedAsOf).toBe(false); - expect(payload.asOfMs).toBe(fixture.cutoffTs - 1); - if (payload.status === 'ok') { - expect(payload.trial.sampleEnd < fixture.cutoffDate).toBe(true); - } - expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); - expect(poisonedLedger.rows).toEqual(cleanLedger.rows); - }); - - test('intraday Vault cutoff: cutoff-date bars before the cutoff instant and cutoff-date shorts are excluded; result equals clean replay', async () => { - const fixture = buildFixture(); - const cutoffTs = utcMs(fixture.cutoffDate, 15); - const lid = fixture.listingIds[5]!; - const earlyCutoffDay = utcMs(fixture.cutoffDate, 14); - const extraBars = [ - poisonBar(lid, earlyCutoffDay, earlyCutoffDay), // before cutoff instant, same UTC date - poisonBar(lid, cutoffTs, earlyCutoffDay), // exactly at cutoff - ]; - const extraShorts = [ - poisonShort(lid, fixture.cutoffDate, utcMs(fixture.cutoffDate, 10)), // known before cutoff instant - ]; - - const cleanLedger = createLedger(); - const clean = await call({ - store: createStore(fixture).store, - ledger: cleanLedger.executor, - cutoffTs, - args: { ...baseArgs(fixture), asOf: fixture.allDates[fixture.allDates.length - 1]! }, - }); - const poisonedLedger = createLedger(); - const poisoned = await call({ - store: createStore(fixture, { extraBars, extraShorts }).store, - ledger: poisonedLedger.executor, - cutoffTs, - args: { ...baseArgs(fixture), asOf: fixture.allDates[fixture.allDates.length - 1]! }, - }); - - expect(poisoned.isError).toBe(false); - const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; - expect(payload.clampedTo).toBe(true); - expect(payload.clampedAsOf).toBe(true); - expect(payload.effectiveTo).toBe(`${fixture.cutoffDate}T14:59:59.999999Z`); - expect(payload.status).toBe('ok'); - expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); - expect(poisonedLedger.rows).toEqual(cleanLedger.rows); - }); - - test('earlier explicit asOf: shorts known after asOf and bars stamped or known after asOf are excluded; result equals clean replay', async () => { - const fixture = buildFixture(); - const asOfDate = fixture.allDates[120]!; - const asOf = `${asOfDate}T18:00:00.000Z`; - const asOfMs = Date.parse(asOf); - const lid = fixture.listingIds[7]!; - const extraBars = [ - poisonBar(lid, utcMs(asOfDate, 21), utcMs(asOfDate, 0)), // close after asOf, backdated knownAt - poisonBar(lid, utcMs(fixture.allDates[119]!, 22), asOfMs + 1), // known 1ms after asOf - ]; - const extraShorts = [poisonShort(lid, fixture.allDates[100]!, asOfMs + 1)]; - const args = { ...baseArgs(fixture), asOf }; - - const cleanLedger = createLedger(); - const clean = await call({ - store: createStore(fixture).store, - ledger: cleanLedger.executor, - cutoffTs: fixture.cutoffTs, - args, - }); - const poisonedLedger = createLedger(); - const poisoned = await call({ - store: createStore(fixture, { extraBars, extraShorts }).store, - ledger: poisonedLedger.executor, - cutoffTs: fixture.cutoffTs, - args, - }); - - expect(poisoned.isError).toBe(false); - const payload = JSON.parse(poisoned.text) as AnalyzeSignalResultPayload; - expect(payload.status).toBe('ok'); - expect(payload.clampedAsOf).toBe(false); - expect(payload.effectiveAsOf).toBe(asOf); - if (payload.status === 'ok') { - expect(payload.trial.sampleEnd < asOfDate).toBe(true); - } - expect(JSON.parse(poisoned.text)).toEqual(JSON.parse(clean.text)); - expect(poisonedLedger.rows).toEqual(cleanLedger.rows); - }); -}); - -describe('analyze_signal QA: store arguments, universe and ledger behaviour', () => { - test('bars and shorts receive identical fenced bounds, 1d timeframe, vault_fenced scope and requested adjustment', async () => { - const fixture = buildFixture(); - const fake = createStore(fixture); - await call({ - store: fake.store, - ledger: createLedger().executor, - cutoffTs: fixture.cutoffTs, - args: { ...baseArgs(fixture), adjustment: 'split' }, - }); - - expect(fake.barsCalls).toHaveLength(1); - expect(fake.shortsCalls).toHaveLength(1); - const bars = fake.barsCalls[0]!; - const shorts = fake.shortsCalls[0]!; - expect(bars.timeframe).toBe('1d'); - expect(bars.scope).toBe('vault_fenced'); - expect(bars.adjustment).toBe('split'); - expect(bars.from).toBe(shorts.from); - expect(bars.to).toBe(shorts.to); - expect(bars.asOf).toBe(shorts.asOf); - expect(bars.listingIds).toEqual(shorts.listingIds); - const lastAllowed = new Date(fixture.cutoffTs - 1).toISOString().replace('Z', '999Z'); - expect(bars.to).toBe(lastAllowed); - expect(bars.asOf).toBe(lastAllowed); - - const defaulted = createStore(fixture); - await call({ - store: defaulted.store, - ledger: createLedger().executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - expect(defaulted.barsCalls[0]?.adjustment).toBe('raw'); - }); - - test('named universe: one snapshot lookup before from; resolved IDs are sorted and deduplicated before the store query', async () => { - const fixture = buildFixture(); - const shuffled = [...fixture.listingIds].reverse(); - const fake = createStore(fixture, { - universe: () => [...shuffled, fixture.listingIds[0]!, fixture.listingIds[1]!], - }); - const ledger = createLedger(); - const args = { ...baseArgs(fixture), universe: 'CA_EQ' } as Record; - delete args.listingIds; - - const res = await call({ store: fake.store, ledger: ledger.executor, cutoffTs: fixture.cutoffTs, args }); - expect(res.isError).toBe(false); - expect(fake.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-31' }]); - expect(fake.barsCalls[0]?.listingIds).toEqual(fixture.listingIds); - expect(fake.shortsCalls[0]?.listingIds).toEqual(fixture.listingIds); - const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; - expect(payload.listingCount).toBe(fixture.listingIds.length); - }); - - test('named-universe expression hash differs from the same IDs selected explicitly', async () => { - const fixture = buildFixture(); - const explicitLedger = createLedger(); - await call({ - store: createStore(fixture).store, - ledger: explicitLedger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - const universeLedger = createLedger(); - const args = { ...baseArgs(fixture), universe: 'CA_EQ' } as Record; - delete args.listingIds; - await call({ - store: createStore(fixture, { universe: () => fixture.listingIds }).store, - ledger: universeLedger.executor, - cutoffTs: fixture.cutoffTs, - args, - }); - expect(explicitLedger.rows).toHaveLength(1); - expect(universeLedger.rows).toHaveLength(1); - expect(universeLedger.rows[0]!.expression_hash).not.toBe(explicitLedger.rows[0]!.expression_hash); - expect(universeLedger.rows[0]!.daily_series).toEqual(explicitLedger.rows[0]!.daily_series); - }); - - test('maxSignalAgeSessions is applied to the panel and changes the expression hash', async () => { - const fixture = buildFixture(); - const run = async (extra: Record) => { - const ledger = createLedger(); - const res = await call({ - store: createStore(fixture).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - args: { ...baseArgs(fixture), ...extra }, - }); - return { payload: JSON.parse(res.text) as AnalyzeSignalResultPayload, ledger }; - }; - const unbounded = await run({}); - const capped = await run({ maxSignalAgeSessions: 3 }); - - expect(unbounded.payload.panelDiagnostics.droppedStaleSignal).toBe(0); - expect(capped.payload.panelDiagnostics.droppedStaleSignal).toBeGreaterThan(0); - expect(capped.payload.status).toBe('ok'); - expect(capped.ledger.rows[0]!.expression_hash).not.toBe(unbounded.ledger.rows[0]!.expression_hash); - }); - - test('replaying the same request on one ledger appends a second row with the same hash and grows the DSR cluster', async () => { - const fixture = buildFixture(); - const ledger = createLedger(); - const first = await call({ - store: createStore(fixture).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - const second = await call({ - store: createStore(fixture).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - const p1 = JSON.parse(first.text) as AnalyzeSignalResultPayload; - const p2 = JSON.parse(second.text) as AnalyzeSignalResultPayload; - if (p1.status !== 'ok' || p2.status !== 'ok') { - throw new Error('expected ok'); - } - expect(ledger.rows).toHaveLength(2); - expect(p2.trial.expressionHash).toBe(p1.trial.expressionHash); - expect(p2.trial.trialId).not.toBe(p1.trial.trialId); - expect(p1.deflatedSharpe.clusterSize).toBe(1); - expect(p2.deflatedSharpe.clusterSize).toBe(2); - }); - - test('operator principal is accepted and recorded; caller cannot change it', async () => { - const fixture = buildFixture(); - const ledger = createLedger(); - const res = await call({ - store: createStore(fixture).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - principalId: 'operator', - args: baseArgs(fixture), - }); - expect(res.isError).toBe(false); - expect(ledger.rows.map(r => r.principal_id)).toEqual(['operator']); - }); - - test('unsupported universe refs accept equity market labels but reject FX before any store call', async () => { - const fixture = buildFixture(); - const args = { ...baseArgs(fixture), universe: 'TSX_COMPOSITE' } as Record; - delete args.listingIds; - - const okStore = createStore(fixture, { universe: () => fixture.listingIds }); - const ok = await call({ store: okStore.store, ledger: createLedger().executor, cutoffTs: fixture.cutoffTs, args }); - expect(ok.isError).toBe(false); - expect(okStore.universeCalls[0]?.ref).toBe('TSX_COMPOSITE'); - - const fxStore = createStore(fixture); - const fxLedger = createLedger(); - const fx = await call({ - store: fxStore.store, - ledger: fxLedger.executor, - cutoffTs: fixture.cutoffTs, - args: { ...args, universeMarket: 'FX' }, - }); - expect(JSON.parse(fx.raw).error ?? JSON.parse(fx.raw).result?.isError).toBeTruthy(); - expect(fxStore.universeCalls).toHaveLength(0); - expect(fxStore.barsCalls).toHaveLength(0); - expect(fxLedger.rows).toHaveLength(0); - }); -}); - -describe('analyze_signal QA: factory validation and error sanitisation', () => { - test('factory rejects invalid principal, ledger, store and cutoff without touching the store', () => { - const fixture = buildFixture(); - const fake = createStore(fixture); - const ledger = createLedger().executor; - const vaultContext = { vaultCutoffTs: fixture.cutoffTs }; - - expect(() => - createAnalyzeSignalTool({ store: fake.store, ledger, vaultContext, principalId: 'agent:not-a-uuid' }) - ).toThrow(TrialLedgerError); - expect(() => - createAnalyzeSignalTool({ - store: fake.store, - ledger: {} as TrialLedgerExecutor, - vaultContext, - principalId: AGENT_PRINCIPAL, - }) - ).toThrow(); - expect(() => - createAnalyzeSignalTool({ - store: { bars: fake.store.bars } as unknown as MarketDataStore, - ledger, - vaultContext, - principalId: AGENT_PRINCIPAL, - }) - ).toThrow(MarketDataStoreValidationError); - for (const bad of [Number.NaN, 1.5, Number.POSITIVE_INFINITY, undefined]) { - expect(() => - createAnalyzeSignalTool({ - store: fake.store, - ledger, - vaultContext: { vaultCutoffTs: bad as number }, - principalId: AGENT_PRINCIPAL, - }) - ).toThrow(MarketDataStoreValidationError); - } - expect(fake.barsCalls).toHaveLength(0); - expect(fake.universeCalls).toHaveLength(0); - }); - - test('unknown errors, non-Error throws and unsafe validation fields return fixed generic text with no secrets', async () => { - const fixture = buildFixture(); - const secret = - 'SELECT * FROM bars_1d WHERE x; /srv/data/parquet/bars.parquet postgres://user:pass@host:5432/db'; - const cases: readonly [string, Parameters[1], { insertThrow?: unknown } | undefined, string][] = [ - ['plain Error from bars stream', { barsThrow: new Error(secret) }, undefined, 'Error: Tool execution failed.'], - ['string thrown from shortsAsOf', { shortsThrow: secret }, undefined, 'Error: Tool execution failed.'], - [ - 'validation error with unsafe field name', - { shortsThrow: new MarketDataStoreValidationError(secret, secret) }, - undefined, - 'MarketDataStoreValidationError: Query parameters failed store validation.', - ], - [ - 'not-implemented error for unknown method', - { barsThrow: new MarketDataStoreNotImplementedError(secret as never) }, - undefined, - 'MarketDataStoreNotImplementedError: Requested store operation is not supported.', - ], - ['plain Error from ledger insert', undefined, { insertThrow: new Error(secret) }, 'Error: Tool execution failed.'], - [ - 'unmapped TrialLedgerError code', - undefined, - { insertThrow: new TrialLedgerError('INVALID_ROW', secret) }, - 'TrialLedgerError: Trial ledger operation failed.', - ], - ]; - - for (const [label, storeOpts, ledgerOpts, expected] of cases) { - const ledger = createLedger(ledgerOpts); - const res = await call({ - store: createStore(fixture, storeOpts).store, - ledger: ledger.executor, - cutoffTs: fixture.cutoffTs, - args: baseArgs(fixture), - }); - expect(res.isError, label).toBe(true); - expect(res.text, label).toBe(expected); - for (const fragment of ['SELECT', 'bars_1d', '/srv/data', 'postgres://', 'user:pass', 'stack']) { - expect(res.raw.includes(fragment), `${label}: ${fragment}`).toBe(false); - } - expect(ledger.rows, label).toHaveLength(0); - } - }); - - test('a poison bar forwarded to the panel builder directly throws, proving the sentinel is meaningful', () => { - const fixture = buildFixture(); - const ts = utcMs(fixture.allDates[10]!, 21); - expect(() => - buildForwardReturnPanel({ - bars: [...fixture.bars.filter(b => b.ts < fixture.cutoffTs), poisonBar(fixture.listingIds[0]!, ts + 1, ts + 1)], - signals: [], - horizonSessions: 5, - vaultCutoffDate: fixture.cutoffDate, - }) - ).toThrow(SignalPanelError); - }); -}); diff --git a/libs/research/test/mcp-analyze-signal.test.ts b/libs/research/test/mcp-analyze-signal.test.ts deleted file mode 100644 index e871fdeb..00000000 --- a/libs/research/test/mcp-analyze-signal.test.ts +++ /dev/null @@ -1,3403 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type BarBatch, - type BarRecord, - type MarketDataStore, - MarketDataStoreValidationError, - type Table, - type TableRow, - VaultScopeNotAuthorizedError, -} from '../src/market-data-store'; -import { - type BarsQuery, - FUNDAMENTALS_PIT_VALUE_FIELDS, - type FundamentalsAsOfQuery, - MarketDataStoreNotImplementedError, - type ShortsAsOfQuery, - type UniverseQuery, -} from '../src/market-data-store-duckdb'; -import { - ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS, - ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS, - ANALYZE_SIGNAL_MAX_LISTING_IDS, - ANALYZE_SIGNAL_MAX_SERIES_POINTS, - type AnalyzeSignalResultPayload, - createAnalyzeSignalTool, - createMcpServer, - createQueryDataTool, -} from '../src/mcp/index'; -import { - type SignalObservation, - buildForwardReturnPanel, - shortsTableToSignalRows, -} from '../src/signal-panel'; -import { analyzeSignal } from '../src/signal-study'; -import { type TrialLedgerExecutor, canonicalExpressionHash } from '../src/trial-ledger'; - -const SEED = 20261129; -const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const CAMPAIGN_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; -const HYPOTHESIS_UUID = '12345678-1234-4123-8123-123456789abc'; - -function createSeededRng(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = new Array(count); - const current = new Date(`${startDate}T00:00:00.000Z`); - let written = 0; - while (written < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out[written] = current.toISOString().slice(0, 10); - written += 1; - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeUtcMs(date: string, hourUtc: number): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0); -} - -interface StoredTrialRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -function createFakeTrialLedger(options?: { - insertError?: Error; - dsrReadError?: Error; -}): { - executor: TrialLedgerExecutor; - rows: StoredTrialRow[]; - insertCalls: number; - selectCalls: number; -} { - const rows: StoredTrialRow[] = []; - let nextTrialId = 1; - const state = { - rows, - insertCalls: 0, - selectCalls: 0, - executor: null as unknown as TrialLedgerExecutor, - }; - - state.executor = { - async query>(text: string, params?: readonly unknown[]) { - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - state.insertCalls += 1; - if (options?.insertError !== undefined) { - throw options.insertError; - } - const p = params ?? []; - const trialId = nextTrialId++; - const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); - const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); - const stored: StoredTrialRow = { - trial_id: String(trialId), - created_at: createdAt, - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: dailySeries, - }; - rows.push(stored); - return { - rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], - rowCount: 1, - }; - } - - if (trimmed.startsWith('SELECT')) { - state.selectCalls += 1; - if (options?.dsrReadError !== undefined) { - throw options.dsrReadError; - } - if (text.includes('WHERE trial_id = $1::bigint')) { - const targetId = String(params?.[0]); - const matched = rows.filter(r => r.trial_id === targetId); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const market = params?.[0] as string; - const bucket = params?.[1] as string; - const matched = rows.filter( - r => r.universe_market === market && r.horizon_bucket === bucket - ); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - } - - return { rows: [], rowCount: 0 }; - }, - }; - - return state; -} - -interface CeoShortsFixture { - readonly listingIds: number[]; - readonly allDates: string[]; - readonly vaultCutoffDate: string; - readonly vaultCutoffTs: number; - readonly bars: BarRecord[]; - readonly shortsTable: Table; -} - -const SHORTS_COLUMNS = [ - 'listing_id', - 'report_date', - 'known_at', - 'shares_short', - 'net_change', - 'pct_float', - 'source', -] as const; - -function buildCeoShortsFixture(options?: { - preCutoffSessions?: number; - postCutoffSessions?: number; - listingCount?: number; - poisonPostCutoff?: boolean; -}): CeoShortsFixture { - const rand = createSeededRng(SEED); - const listingCount = options?.listingCount ?? 28; - const preCutoffSessions = options?.preCutoffSessions ?? 140; - const postCutoffSessions = options?.postCutoffSessions ?? 10; - const poisonPostCutoff = options?.poisonPostCutoff ?? false; - - const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions); - const vaultCutoffDate = allDates[preCutoffSessions]!; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - - const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i); - const bars: BarRecord[] = []; - const shortsRows: TableRow[] = []; - - const PUBLICATION_LAG_SESSIONS = 4; - const activeNetChange = new Float64Array(listingCount); - const pendingByPublishIdx = new Map(); - const prices = new Float64Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - prices[l] = 10 + l * 1.5; - } - - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); // 16:00 ET close - - const released = pendingByPublishIdx.get(t - 1); - if (released !== undefined) { - for (let l = 0; l < listingCount; l += 1) { - const v = released[l]; - if (v !== null && v !== undefined) { - activeNetChange[l] = v / 20_000; - } - } - } - - const publishIdx = t + PUBLICATION_LAG_SESSIONS; - if (t % 10 === 0 && publishIdx < allDates.length) { - const reportKnownAt = makeUtcMs(allDates[publishIdx]!, 22); // 17:00 ET on T+4 - const pending: (number | null)[] = []; - for (let l = 0; l < listingCount; l += 1) { - const isNullCell = t > 0 && (t + l) % 19 === 0; - const netChange = isNullCell ? null : Math.round((rand() * 2 - 1) * 20_000); - pending.push(netChange); - shortsRows.push({ - listing_id: listingIds[l]!, - report_date: date, - known_at: reportKnownAt, - shares_short: 100_000 + l * 5_000 + Math.round(rand() * 10_000), - net_change: netChange, - pct_float: isNullCell ? null : Number((0.02 + rand() * 0.08).toFixed(4)), - source: 'ceoShorts', - }); - } - pendingByPublishIdx.set(publishIdx, pending); - } - - for (let l = 0; l < listingCount; l += 1) { - const dailyRet = -0.004 * activeNetChange[l]! + (rand() * 2 - 1) * 0.008; - prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet)); - const isPostCutoff = date >= vaultCutoffDate; - const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : Number(prices[l]!.toFixed(6)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: closeVal, - high: closeVal, - low: closeVal, - close: closeVal, - volume: 50_000, - vwap: closeVal, - knownAt: closeTs, - }); - } - } - - return { - listingIds, - allDates, - vaultCutoffDate, - vaultCutoffTs, - bars, - shortsTable: { - columns: SHORTS_COLUMNS, - rows: shortsRows, - }, - }; -} - -interface FakeStoreState { - readonly barsCalls: BarsQuery[]; - readonly shortsCalls: ShortsAsOfQuery[]; - readonly fundamentalsCalls: FundamentalsAsOfQuery[]; - readonly universeCalls: UniverseQuery[]; - readonly store: MarketDataStore; -} - -function createFakeStore(options?: { - bars?: readonly BarRecord[]; - shortsTable?: Table; - fundamentalsResolver?: (q: FundamentalsAsOfQuery) => Table | Promise
; - universeIds?: readonly number[]; - universeResolver?: (q: UniverseQuery) => number[]; - leaky?: boolean; - barsError?: Error; - shortsError?: Error; - fundamentalsError?: Error; - universeError?: Error; -}): FakeStoreState { - const barsCalls: BarsQuery[] = []; - const shortsCalls: ShortsAsOfQuery[] = []; - const fundamentalsCalls: FundamentalsAsOfQuery[] = []; - const universeCalls: UniverseQuery[] = []; - - const allBars = options?.bars ?? []; - const allShorts = options?.shortsTable ?? { columns: SHORTS_COLUMNS, rows: [] }; - const leaky = options?.leaky ?? false; - - const store: MarketDataStore = { - bars(q: BarsQuery): AsyncIterable { - barsCalls.push(q); - if (options?.barsError !== undefined) { - const err = options.barsError; - return { - [Symbol.asyncIterator]() { - return { - next() { - return Promise.reject(err); - }, - }; - }, - }; - } - - const idSet = new Set(q.listingIds); - const fromMs = Date.parse(q.from.length === 10 ? `${q.from}T00:00:00.000Z` : q.from); - const toMs = Date.parse(q.to.length === 10 ? `${q.to}T23:59:59.999Z` : q.to); - const asOfMs = - q.asOf !== undefined - ? Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf) - : Number.POSITIVE_INFINITY; - - const filtered = leaky - ? [...allBars] - : allBars.filter( - row => - idSet.has(row.listingId) && - row.ts >= fromMs && - row.ts <= toMs && - row.ts <= asOfMs && - row.knownAt <= asOfMs - ); - - return { - async *[Symbol.asyncIterator]() { - yield { rows: filtered }; - }, - }; - }, - - async shortsAsOf(q: ShortsAsOfQuery): Promise
{ - shortsCalls.push(q); - if (options?.shortsError !== undefined) { - throw options.shortsError; - } - - if (leaky) { - return { - columns: allShorts.columns, - rows: [...allShorts.rows], - }; - } - - const idSet = new Set(q.listingIds); - const fromDate = q.from.slice(0, 10); - const toDate = q.to.slice(0, 10); - const asOfMs = - q.asOf !== undefined - ? Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf) - : Number.POSITIVE_INFINITY; - - const rows = allShorts.rows.filter(row => { - const lid = row.listing_id as number; - const reportDate = row.report_date as string | undefined; - const knownAt = row.known_at as number; - const inDateRange = - reportDate === undefined || (reportDate >= fromDate && reportDate <= toDate); - return idSet.has(lid) && inDateRange && knownAt <= asOfMs; - }); - - return { - columns: allShorts.columns, - rows, - }; - }, - - async universe(q: UniverseQuery): Promise { - universeCalls.push(q); - if (options?.universeError !== undefined) { - throw options.universeError; - } - if (options?.universeResolver !== undefined) { - return options.universeResolver(q); - } - return [...(options?.universeIds ?? [])]; - }, - - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - async fundamentalsAsOf(q: FundamentalsAsOfQuery): Promise
{ - fundamentalsCalls.push(q); - if (options?.fundamentalsError !== undefined) { - throw options.fundamentalsError; - } - if (options?.fundamentalsResolver !== undefined) { - return options.fundamentalsResolver(q); - } - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - - return { barsCalls, shortsCalls, fundamentalsCalls, universeCalls, store }; -} - -async function callAnalyzeSignal(params: { - store: MarketDataStore; - ledger: TrialLedgerExecutor; - vaultCutoffTs: number; - principalId?: string; - args: Record; -}): Promise<{ - rawResponse: string; - isError: boolean; - text: string; -}> { - const tool = createAnalyzeSignalTool({ - store: params.store, - ledger: params.ledger, - vaultContext: { vaultCutoffTs: params.vaultCutoffTs }, - principalId: params.principalId ?? AGENT_PRINCIPAL, - }); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [tool], - }); - - const rawResponse = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'as-1', - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: params.args, - }, - }) - ); - - expect(rawResponse).not.toBeNull(); - const parsed = JSON.parse(rawResponse as string) as { - result: { - isError?: boolean; - content: { type: string; text: string }[]; - }; - }; - return { - rawResponse: rawResponse as string, - isError: parsed.result.isError === true, - text: parsed.result.content[0]?.text ?? '', - }; -} - -describe('MCP analyze_signal tool', () => { - test('tools/list advertises query_data and analyze_signal and omits server-controlled fields from analyze_signal schema', async () => { - const fixture = buildCeoShortsFixture({ preCutoffSessions: 20, postCutoffSessions: 5, listingCount: 6 }); - const fakeStore = createFakeStore({ bars: fixture.bars, shortsTable: fixture.shortsTable }); - const fakeLedger = createFakeTrialLedger(); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: fakeStore.store, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - }), - createAnalyzeSignalTool({ - store: fakeStore.store, - ledger: fakeLedger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - }), - ], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'list-1', - method: 'tools/list', - }) - ); - - const parsed = JSON.parse(raw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - type: string; - properties: Record }>; - required?: string[]; - additionalProperties: boolean; - }; - }[]; - }; - }; - - const names = parsed.result.tools.map(t => t.name); - expect(names).toEqual(['query_data', 'analyze_signal']); - - const analyzeTool = parsed.result.tools.find(t => t.name === 'analyze_signal'); - expect(analyzeTool).toBeDefined(); - expect(analyzeTool?.inputSchema.type).toBe('object'); - expect(analyzeTool?.inputSchema.additionalProperties).toBe(false); - expect(analyzeTool?.inputSchema.properties.signal?.additionalProperties).toBe(false); - - const propKeys = Object.keys(analyzeTool?.inputSchema.properties ?? {}); - expect(propKeys).toContain('listingIds'); - expect(propKeys).toContain('universe'); - expect(propKeys).toContain('from'); - expect(propKeys).toContain('to'); - expect(propKeys).toContain('signal'); - expect(propKeys).toContain('horizonSessions'); - expect(propKeys).toContain('universeMarket'); - expect(propKeys).toContain('horizonBucket'); - - for (const forbidden of ['scope', 'vault_evaluation_only', 'principalId', 'vaultCutoffDate']) { - expect(propKeys).not.toContain(forbidden); - expect(analyzeTool?.inputSchema.required ?? []).not.toContain(forbidden); - } - }); - - test('executes seeded ceoShorts fixture with parity to direct analyzeSignal and writes exactly one trial row under injected principal', async () => { - const fixture = buildCeoShortsFixture(); - const fakeStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - }); - const mcpLedger = createFakeTrialLedger(); - - const from = fixture.allDates[0]!; - const to = fixture.allDates[fixture.allDates.length - 1]!; - - const res = await callAnalyzeSignal({ - store: fakeStore.store, - ledger: mcpLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - principalId: AGENT_PRINCIPAL, - args: { - listingIds: fixture.listingIds, - from, - to, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - campaignId: CAMPAIGN_UUID, - hypothesisId: HYPOTHESIS_UUID, - }, - }); - - expect(res.isError).toBe(false); - const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; - expect(payload.status).toBe('ok'); - if (payload.status !== 'ok') { - return; - } - - // Run direct research pipeline on the same pre-cutoff bars/shorts with a fresh isolated ledger - const directLedger = createFakeTrialLedger(); - const preCutoffBars = fixture.bars.filter(b => b.ts < fixture.vaultCutoffTs); - const preCutoffShorts: Table = { - columns: fixture.shortsTable.columns, - rows: fixture.shortsTable.rows.filter( - r => (r.report_date as string) < fixture.vaultCutoffDate && (r.known_at as number) < fixture.vaultCutoffTs - ), - }; - const directSignals = shortsTableToSignalRows(preCutoffShorts, 'net_change'); - const directBuilt = buildForwardReturnPanel({ - bars: preCutoffBars, - signals: directSignals, - horizonSessions: 5, - vaultCutoffDate: fixture.vaultCutoffDate, - }); - const directStudy = await analyzeSignal(directLedger.executor, { - principalId: AGENT_PRINCIPAL, - campaignId: CAMPAIGN_UUID, - hypothesisId: HYPOTHESIS_UUID, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_reference', - params: { field: 'net_change', horizonSessions: 5 }, - universe: fixture.listingIds, - horizon: '5d', - }, - panel: directBuilt.panel, - vaultCutoffDate: fixture.vaultCutoffDate, - }); - - expect(directStudy.status).toBe('ok'); - if (directStudy.status !== 'ok') { - return; - } - - // Parity between MCP payload and direct research pipeline - expect(payload.scope).toBe('vault_fenced'); - expect(payload.vaultCutoffTs).toBe(fixture.vaultCutoffTs); - expect(payload.vaultCutoffDate).toBe(fixture.vaultCutoffDate); - expect(payload.panelDiagnostics).toEqual(directBuilt.diagnostics); - expect(payload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); - expect(payload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); - expect(payload.analysis.quantiles.spreadSummary).toEqual( - directStudy.analysis.quantiles.spreadSummary - ); - expect(payload.analysis.turnover.meanTopTurnover).toBe( - directStudy.analysis.turnover.meanTopTurnover - ); - expect(payload.analysis.recency).toEqual(directStudy.analysis.recency); - expect(payload.analysis.diagnostics).toEqual(directStudy.analysis.diagnostics); - expect(payload.trial.sampleStart).toBe(directStudy.trial.sampleStart); - expect(payload.trial.sampleEnd).toBe(directStudy.trial.sampleEnd); - expect(payload.trial.sampleEnd < fixture.vaultCutoffDate).toBe(true); - expect(payload.trial.nObs).toBe(directStudy.trial.nObs); - expect(payload.trial.expressionHash).toMatch(/^[0-9a-f]{64}$/); - expect(payload.deflatedSharpe).toEqual(directStudy.deflatedSharpe); - - // Bounded series preview: >100 observations truncated to latest 100 while study & ledger keep full sample - expect(payload.analysis.ledgerSeries.series).toBe('rank_ic'); - expect(payload.analysis.ledgerSeries.totalCount).toBe(directStudy.trial.nObs); - expect(payload.analysis.ledgerSeries.totalCount).toBeGreaterThan(ANALYZE_SIGNAL_MAX_SERIES_POINTS); - expect(payload.analysis.ledgerSeries.truncated).toBe(true); - expect(payload.analysis.ledgerSeries.points).toHaveLength(ANALYZE_SIGNAL_MAX_SERIES_POINTS); - const lastPoint = payload.analysis.ledgerSeries.points[ANALYZE_SIGNAL_MAX_SERIES_POINTS - 1]; - expect(lastPoint?.date).toBe(directStudy.trial.sampleEnd); - - // Exactly one trial_ledger row written with injected principalId and full daily_series - expect(mcpLedger.rows).toHaveLength(1); - const stored = mcpLedger.rows[0]!; - expect(stored.stage).toBe('signal_ic'); - expect(stored.principal_id).toBe(AGENT_PRINCIPAL); - expect(stored.campaign_id).toBe(CAMPAIGN_UUID); - expect(stored.hypothesis_id).toBe(HYPOTHESIS_UUID); - expect(stored.universe_market).toBe('CA_EQ'); - expect(stored.horizon_bucket).toBe('swing_1_10d'); - expect(stored.n_obs).toBe(directStudy.trial.nObs); - expect(stored.daily_series).toHaveLength(directStudy.trial.nObs); - }); - - test('identical requests and reordered/duplicate listingIds produce the same expressionHash; changing field, horizon, or ledgerSeries changes it', async () => { - const fixture = buildCeoShortsFixture(); - const from = fixture.allDates[0]!; - const to = fixture.allDates[fixture.allDates.length - 1]!; - - async function runWithArgs(args: Record) { - const store = createFakeStore({ bars: fixture.bars, shortsTable: fixture.shortsTable }); - const ledger = createFakeTrialLedger(); - const res = await callAnalyzeSignal({ - store: store.store, - ledger: ledger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args, - }); - expect(res.isError).toBe(false); - const payload = JSON.parse(res.text) as AnalyzeSignalResultPayload; - expect(payload.status).toBe('ok'); - if (payload.status !== 'ok') { - throw new Error('Expected ok status'); - } - return { payload, ledger }; - } - - const baseArgs = { - listingIds: fixture.listingIds, - from, - to, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; - - const run1 = await runWithArgs(baseArgs); - const run2 = await runWithArgs(baseArgs); - expect(run1.payload.trial.expressionHash).toBe(run2.payload.trial.expressionHash); - - // Reordered and duplicated listingIds canonicalize to the exact same expressionHash - const reorderedIds = [...fixture.listingIds].reverse(); - reorderedIds.push(fixture.listingIds[0]!, fixture.listingIds[3]!); - const runReordered = await runWithArgs({ ...baseArgs, listingIds: reorderedIds }); - expect(runReordered.payload.trial.expressionHash).toBe(run1.payload.trial.expressionHash); - - // Different signal.field -> different expressionHash - const runOtherField = await runWithArgs({ - ...baseArgs, - signal: { source: 'shorts', field: 'pct_float' }, - }); - expect(runOtherField.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); - - // Different horizonSessions -> different expressionHash (including position_10d_plus bucket for 11d) - const runOtherHorizon = await runWithArgs({ - ...baseArgs, - horizonSessions: 11, - horizonBucket: 'position_10d_plus', - }); - expect(runOtherHorizon.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); - expect(runOtherHorizon.ledger.rows[0]?.horizon_bucket).toBe('position_10d_plus'); - - // Equivalent date/timestamp/offset forms canonicalize to identical effective microsecond bounds & expressionHash - const midDate = fixture.allDates[120]!; - const runDateForm = await runWithArgs({ - ...baseArgs, - from, - to: midDate, - asOf: midDate, - }); - const runIsoMicrosForm = await runWithArgs({ - ...baseArgs, - from: `${from}T00:00:00.000000Z`, - to: `${midDate}T23:59:59.999999Z`, - asOf: `${midDate}T23:59:59.999999Z`, - }); - const runOffsetForm = await runWithArgs({ - ...baseArgs, - from: '2022-08-31T19:00:00.000000-05:00', - to: `${midDate}T18:59:59.999999-05:00`, - asOf: `${midDate}T18:59:59.999999-05:00`, - }); - expect(runDateForm.payload.effectiveFrom).toBe(`${from}T00:00:00.000Z`); - expect(runDateForm.payload.effectiveTo).toBe(`${midDate}T23:59:59.999999Z`); - expect(runDateForm.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999999Z`); - expect(runIsoMicrosForm.payload.effectiveFrom).toBe(runDateForm.payload.effectiveFrom); - expect(runIsoMicrosForm.payload.effectiveTo).toBe(runDateForm.payload.effectiveTo); - expect(runIsoMicrosForm.payload.effectiveAsOf).toBe(runDateForm.payload.effectiveAsOf); - expect(runIsoMicrosForm.payload.trial.expressionHash).toBe( - runDateForm.payload.trial.expressionHash - ); - expect(runOffsetForm.payload.trial.expressionHash).toBe( - runDateForm.payload.trial.expressionHash - ); - - // Distinct sub-millisecond effective bounds produce different expressionHash even with identical sampleStart/sampleEnd - const runAsOfZeroMicros = await runWithArgs({ - ...baseArgs, - from, - to: midDate, - asOf: `${midDate}T23:59:59.999000Z`, - }); - expect(runAsOfZeroMicros.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999Z`); - expect(runAsOfZeroMicros.payload.trial.sampleStart).toBe(runDateForm.payload.trial.sampleStart); - expect(runAsOfZeroMicros.payload.trial.sampleEnd).toBe(runDateForm.payload.trial.sampleEnd); - expect(runAsOfZeroMicros.payload.trial.expressionHash).not.toBe( - runDateForm.payload.trial.expressionHash - ); - - const runToZeroMicros = await runWithArgs({ - ...baseArgs, - from, - to: `${midDate}T23:59:59.999000Z`, - asOf: midDate, - }); - expect(runToZeroMicros.payload.effectiveTo).toBe(`${midDate}T23:59:59.999Z`); - expect(runToZeroMicros.payload.trial.expressionHash).not.toBe( - runDateForm.payload.trial.expressionHash - ); - - const runFromOneMicro = await runWithArgs({ - ...baseArgs, - from: `${from}T00:00:00.000001Z`, - to: midDate, - asOf: midDate, - }); - expect(runFromOneMicro.payload.effectiveFrom).toBe(`${from}T00:00:00.000001Z`); - expect(runFromOneMicro.payload.trial.expressionHash).not.toBe( - runDateForm.payload.trial.expressionHash - ); - - // quantile_spread ledgerSeries works, truncates preview to 100 while preserving full count, and hashes distinctly - const runSpread = await runWithArgs({ ...baseArgs, ledgerSeries: 'quantile_spread' }); - expect(runSpread.payload.analysis.ledgerSeries.series).toBe('quantile_spread'); - expect(runSpread.payload.analysis.ledgerSeries.totalCount).toBe(runSpread.payload.trial.nObs); - expect(runSpread.payload.analysis.ledgerSeries.truncated).toBe(true); - expect(runSpread.payload.analysis.ledgerSeries.points).toHaveLength( - ANALYZE_SIGNAL_MAX_SERIES_POINTS - ); - expect(runSpread.ledger.rows[0]?.daily_series).toHaveLength(runSpread.payload.trial.nObs); - expect(runSpread.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash); - }); - - test('clamps to/asOf strictly below midnight and intraday Vault cutoffs and blocks cutoff-day leakage from a leaky store', async () => { - const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false }); - const poisonedFixture = buildCeoShortsFixture({ poisonPostCutoff: true }); - const from = cleanFixture.allDates[0]!; - const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!; - const horizonSessions = 5; - - // 1. Clamping test with to and asOf after Vault cutoff (midnight cutoff) - const clampLedger = createFakeTrialLedger(); - const clampStore = createFakeStore({ - bars: cleanFixture.bars, - shortsTable: cleanFixture.shortsTable, - }); - const clampRes = await callAnalyzeSignal({ - store: clampStore.store, - ledger: clampLedger.executor, - vaultCutoffTs: cleanFixture.vaultCutoffTs, - args: { - listingIds: cleanFixture.listingIds, - from, - to: postCutoffDate, - asOf: postCutoffDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - - expect(clampRes.isError).toBe(false); - const clampPayload = JSON.parse(clampRes.text) as AnalyzeSignalResultPayload; - expect(clampPayload.status).toBe('ok'); - expect(clampPayload.clampedTo).toBe(true); - expect(clampPayload.clampedAsOf).toBe(true); - expect(clampPayload.toMs).toBe(cleanFixture.vaultCutoffTs - 1); - expect(clampPayload.asOfMs).toBe(cleanFixture.vaultCutoffTs - 1); - - // Store received fenced to and asOf strictly below vaultCutoffTs - expect(clampStore.barsCalls).toHaveLength(1); - expect(clampStore.barsCalls[0]?.scope).toBe('vault_fenced'); - expect(Date.parse(clampStore.barsCalls[0]?.to ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); - expect(Date.parse(clampStore.barsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); - expect(clampStore.shortsCalls).toHaveLength(1); - expect(Date.parse(clampStore.shortsCalls[0]?.to ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); - expect(Date.parse(clampStore.shortsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1); - if (clampPayload.status === 'ok') { - expect(clampPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true); - const endIdx = cleanFixture.allDates.indexOf(clampPayload.trial.sampleEnd); - const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!; - expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true); - } - - // 2. Intraday Vault cutoff (12:00 UTC on vaultCutoffDate) with asOf beyond cutoff and leaky store - // injecting rows on vaultCutoffDate before cutoff, at exact cutoff timestamp, and after cutoff. - const intradayCutoffTs = makeUtcMs(cleanFixture.vaultCutoffDate, 12); - const cleanPreCutoffBars = cleanFixture.bars.filter( - b => new Date(b.ts).toISOString().slice(0, 10) < cleanFixture.vaultCutoffDate - ); - const cleanPreCutoffShorts: Table = { - columns: cleanFixture.shortsTable.columns, - rows: cleanFixture.shortsTable.rows.filter( - r => - (r.report_date as string) < cleanFixture.vaultCutoffDate && - (r.known_at as number) < intradayCutoffTs - ), - }; - const cleanIntradayStore = createFakeStore({ - bars: cleanPreCutoffBars, - shortsTable: cleanPreCutoffShorts, - leaky: false, - }); - const leakyIntradayStore = createFakeStore({ - bars: [ - ...poisonedFixture.bars, - // Cutoff-day bars BEFORE intradayCutoffTs (10:00 UTC) for every listing - ...poisonedFixture.listingIds.map(listingId => ({ - listingId, - ts: makeUtcMs(poisonedFixture.vaultCutoffDate, 10), - open: 888_888, - high: 888_888, - low: 888_888, - close: 888_888, - volume: 100, - vwap: 888_888, - knownAt: makeUtcMs(poisonedFixture.vaultCutoffDate, 10), - })), - // Bar at EXACT intradayCutoffTs (12:00 UTC) - { - listingId: poisonedFixture.listingIds[0]!, - ts: intradayCutoffTs, - open: 777_777, - high: 777_777, - low: 777_777, - close: 777_777, - volume: 100, - vwap: 777_777, - knownAt: intradayCutoffTs, - }, - ], - shortsTable: { - columns: poisonedFixture.shortsTable.columns, - rows: [ - ...poisonedFixture.shortsTable.rows, - // Shorts row on vaultCutoffDate with known_at before intradayCutoffTs - { - listing_id: poisonedFixture.listingIds[0]!, - report_date: poisonedFixture.vaultCutoffDate, - known_at: makeUtcMs(poisonedFixture.vaultCutoffDate, 9), - shares_short: 9_999_999, - net_change: 9_999_999, - pct_float: 0.99, - source: 'ceoShorts', - }, - // Shorts row with report_date before cutoff but known_at at exact intradayCutoffTs - { - listing_id: poisonedFixture.listingIds[1]!, - report_date: cleanFixture.allDates[100]!, - known_at: intradayCutoffTs, - shares_short: 8_888_888, - net_change: 8_888_888, - pct_float: 0.88, - source: 'ceoShorts', - }, - ], - }, - leaky: true, - }); - - const cleanIntradayLedger = createFakeTrialLedger(); - const leakyIntradayLedger = createFakeTrialLedger(); - const intradayArgs = { - listingIds: cleanFixture.listingIds, - from, - to: postCutoffDate, - asOf: postCutoffDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; - - const cleanIntradayRes = await callAnalyzeSignal({ - store: cleanIntradayStore.store, - ledger: cleanIntradayLedger.executor, - vaultCutoffTs: intradayCutoffTs, - args: intradayArgs, - }); - const leakyIntradayRes = await callAnalyzeSignal({ - store: leakyIntradayStore.store, - ledger: leakyIntradayLedger.executor, - vaultCutoffTs: intradayCutoffTs, - args: intradayArgs, - }); - - expect(cleanIntradayRes.isError).toBe(false); - expect(leakyIntradayRes.isError).toBe(false); - expect(leakyIntradayRes.text).toBe(cleanIntradayRes.text); - expect(leakyIntradayLedger.rows).toEqual(cleanIntradayLedger.rows); - - const intradayPayload = JSON.parse(leakyIntradayRes.text) as AnalyzeSignalResultPayload; - expect(intradayPayload.status).toBe('ok'); - expect(intradayPayload.clampedTo).toBe(true); - expect(intradayPayload.clampedAsOf).toBe(true); - expect(intradayPayload.toMs).toBe(intradayCutoffTs - 1); - expect(intradayPayload.asOfMs).toBe(intradayCutoffTs - 1); - if (intradayPayload.status === 'ok') { - expect(intradayPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true); - const endIdx = cleanFixture.allDates.indexOf(intradayPayload.trial.sampleEnd); - const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!; - expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true); - } - }); - - test('earlier explicit asOf excludes bars with ts > asOf or knownAt > asOf independently from a leaky store and matches clean replay', async () => { - const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false }); - const from = cleanFixture.allDates[0]!; - const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!; - const horizonSessions = 5; - - // Set asOf to noon UTC on session 100 while `to` extends past cutoff - const asOfSessionIdx = 100; - const asOfDate = cleanFixture.allDates[asOfSessionIdx]!; - const asOfIso = `${asOfDate}T12:00:00.000Z`; - const asOfMs = makeUtcMs(asOfDate, 12); - - // Clean replay store filters strictly by ts <= asOfMs && knownAt <= asOfMs - const cleanStore = createFakeStore({ - bars: cleanFixture.bars, - shortsTable: cleanFixture.shortsTable, - leaky: false, - }); - - // Leaky store injects two independent bar leaks + a delayed shorts row: - // (a) Closing bars on `asOfDate` stamped at 21:00 UTC (> noon asOf) with knownAt at 00:00 UTC (<= noon asOf) and poisoned close - // (b) Delayed bars on session 95 (ts <= noon asOf) with knownAt at 15:00 UTC on `asOfDate` (> noon asOf) and poisoned close - const delayedBarDate = cleanFixture.allDates[95]!; - const leakyBars: BarRecord[] = cleanFixture.bars.map(bar => { - if (bar.ts === makeUtcMs(asOfDate, 21)) { - return { - ...bar, - open: 666_666, - high: 666_666, - low: 666_666, - close: 666_666, - vwap: 666_666, - knownAt: makeUtcMs(asOfDate, 0), // earlier than noon asOf, while ts (21:00 UTC) > noon asOf - }; - } - return bar; - }); - // Also inject a bar with ts <= asOfMs but knownAt > asOfMs for listing 0 on session 95 (replace clean bar? No, add extra listing or poisoned bar on a date not in clean? Better: inject on a date after clean or with a listing that has a delayed knownAt!) - // Specifically: take a clean bar on session 95 for listing 0 and verify a delayed-knownAt poison bar on session 100-1 (where ts <= asOfMs and knownAt > asOfMs) is dropped. - // Even stronger: add a synthetic bar on `delayedBarDate` at 10:00 UTC (ts <= asOfMs) with knownAt = 15:00 UTC on `asOfDate` (> asOfMs) and poisoned close 555_555. - // If knownAt filter regresses, buildForwardReturnPanel will throw duplicate_bar (conflicting close on delayedBarDate)! - leakyBars.push({ - listingId: cleanFixture.listingIds[0]!, - ts: makeUtcMs(delayedBarDate, 10), - open: 555_555, - high: 555_555, - low: 555_555, - close: 555_555, - volume: 100, - vwap: 555_555, - knownAt: makeUtcMs(asOfDate, 15), // > noon asOf, while ts <= noon asOf - }); - - const leakyStore = createFakeStore({ - bars: leakyBars, - shortsTable: { - columns: cleanFixture.shortsTable.columns, - rows: [ - ...cleanFixture.shortsTable.rows, - { - listing_id: cleanFixture.listingIds[1]!, - report_date: cleanFixture.allDates[50]!, - known_at: makeUtcMs(asOfDate, 15), // > noon asOf - shares_short: 7_777_777, - net_change: 7_777_777, - pct_float: 0.77, - source: 'ceoShorts', - }, - ], - }, - leaky: true, - }); - - const cleanLedger = createFakeTrialLedger(); - const leakyLedger = createFakeTrialLedger(); - const args = { - listingIds: cleanFixture.listingIds, - from, - to: postCutoffDate, - asOf: asOfIso, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; - - const cleanRes = await callAnalyzeSignal({ - store: cleanStore.store, - ledger: cleanLedger.executor, - vaultCutoffTs: cleanFixture.vaultCutoffTs, - args, - }); - const leakyRes = await callAnalyzeSignal({ - store: leakyStore.store, - ledger: leakyLedger.executor, - vaultCutoffTs: cleanFixture.vaultCutoffTs, - args, - }); - - expect(cleanRes.isError).toBe(false); - expect(leakyRes.isError).toBe(false); - expect(leakyRes.text).toBe(cleanRes.text); - expect(leakyLedger.rows).toEqual(cleanLedger.rows); - - const payload = JSON.parse(leakyRes.text) as AnalyzeSignalResultPayload; - expect(payload.status).toBe('ok'); - expect(payload.clampedAsOf).toBe(false); - expect(payload.asOfMs).toBe(asOfMs); - if (payload.status === 'ok') { - const endIdx = cleanFixture.allDates.indexOf(payload.trial.sampleEnd); - const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!; - // Closing bar on asOfDate (21:00 UTC) was excluded by ts > asOfMs, so last forward endpoint must precede asOfDate - expect(lastForwardEndpoint < asOfDate).toBe(true); - } - }); - - test('request wholly inside Vault holdout returns fixed VaultHoldoutFenceError with zero store and ledger calls', async () => { - const fixture = buildCeoShortsFixture(); - const fakeStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - }); - const fakeLedger = createFakeTrialLedger(); - - const res = await callAnalyzeSignal({ - store: fakeStore.store, - ledger: fakeLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - listingIds: fixture.listingIds, - from: fixture.vaultCutoffDate, - to: fixture.allDates[fixture.allDates.length - 1]!, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - - expect(res.isError).toBe(true); - expect(res.text).toBe( - 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.' - ); - expect(fakeStore.barsCalls).toHaveLength(0); - expect(fakeStore.shortsCalls).toHaveLength(0); - expect(fakeStore.universeCalls).toHaveLength(0); - expect(fakeLedger.insertCalls).toBe(0); - expect(fakeLedger.rows).toHaveLength(0); - }); - - test('named universe resolves strictly before study start and respects earlier/intraday asOf', async () => { - const fixture = buildCeoShortsFixture(); - const from = fixture.allDates[0]!; // 2022-09-01 - const to = fixture.allDates[fixture.allDates.length - 1]!; - - const fakeStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - universeIds: [...fixture.listingIds].reverse(), - }); - const fakeLedger = createFakeTrialLedger(); - - const res = await callAnalyzeSignal({ - store: fakeStore.store, - ledger: fakeLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - universe: 'CA_EQ', - from, - to, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - - expect(res.isError).toBe(false); - // Study starts 2022-09-01 -> universe must be resolved on 2022-08-31 (strictly before study start) - expect(fakeStore.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-31' }]); - // Sorted listingIds passed to bars and shortsAsOf - expect(fakeStore.barsCalls[0]?.listingIds).toEqual(fixture.listingIds); - expect(fakeStore.shortsCalls[0]?.listingIds).toEqual(fixture.listingIds); - - // Earlier intraday asOf (2022-08-15T12:00:00Z) -> universe resolved on completed UTC date 2022-08-14 - const earlyStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - universeIds: fixture.listingIds, - }); - const earlyLedger = createFakeTrialLedger(); - await callAnalyzeSignal({ - store: earlyStore.store, - ledger: earlyLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - universe: 'CA_EQ', - from, - to, - asOf: '2022-08-15T12:00:00Z', - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(earlyStore.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2022-08-14' }]); - }); - - test('insufficient-data cases (empty universe, empty panel, undersized panel, zero-variance series) return reason with zero ledger writes', async () => { - const cutoffDate = '2025-03-31'; - const cutoffTs = makeUtcMs(cutoffDate, 0); - - // 1. Empty resolved universe -> zero bars/shorts calls, zero ledger rows - const emptyUniStore = createFakeStore({ universeIds: [] }); - const emptyUniLedger = createFakeTrialLedger(); - const emptyUniRes = await callAnalyzeSignal({ - store: emptyUniStore.store, - ledger: emptyUniLedger.executor, - vaultCutoffTs: cutoffTs, - args: { - universe: 'CA_EQ', - from: '2025-01-01', - to: '2025-03-20', - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 1, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(emptyUniRes.isError).toBe(false); - const emptyUniPayload = JSON.parse(emptyUniRes.text) as AnalyzeSignalResultPayload; - expect(emptyUniPayload.status).toBe('insufficient_data'); - if (emptyUniPayload.status === 'insufficient_data') { - expect(emptyUniPayload.reason).toBe('too_few_observations'); - } - expect(emptyUniStore.barsCalls).toHaveLength(0); - expect(emptyUniStore.shortsCalls).toHaveLength(0); - expect(emptyUniLedger.rows).toHaveLength(0); - - // 2. Empty panel (bars exist but no shorts signals) - const dates = makeBusinessDates('2025-01-02', 6); - const barsForSixDays: BarRecord[] = []; - for (let d = 0; d < dates.length; d += 1) { - const ts = makeUtcMs(dates[d]!, 21); - for (let id = 1; id <= 6; id += 1) { - barsForSixDays.push({ - listingId: id, - ts, - open: 100 + d, - high: 101 + d, - low: 99 + d, - close: 100 + d + id * 0.1, - volume: 1000, - vwap: 100 + d, - knownAt: ts, - }); - } - } - const emptyPanelStore = createFakeStore({ - bars: barsForSixDays, - shortsTable: { columns: SHORTS_COLUMNS, rows: [] }, - }); - const emptyPanelLedger = createFakeTrialLedger(); - const emptyPanelRes = await callAnalyzeSignal({ - store: emptyPanelStore.store, - ledger: emptyPanelLedger.executor, - vaultCutoffTs: cutoffTs, - args: { - listingIds: [1, 2, 3, 4, 5, 6], - from: dates[0]!, - to: dates[dates.length - 1]!, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(emptyPanelRes.isError).toBe(false); - const emptyPanelPayload = JSON.parse(emptyPanelRes.text) as AnalyzeSignalResultPayload; - expect(emptyPanelPayload.status).toBe('insufficient_data'); - if (emptyPanelPayload.status === 'insufficient_data') { - expect(emptyPanelPayload.reason).toBe('too_few_observations'); - } - expect(emptyPanelLedger.rows).toHaveLength(0); - - // 3. Undersized non-empty panel (only 1 date with forward return -> too_few_observations) - const twoDayBars = barsForSixDays.filter(b => b.ts <= makeUtcMs(dates[1]!, 21)); - const singleSignalRows: TableRow[] = [1, 2, 3, 4, 5, 6].map(id => ({ - listing_id: id, - report_date: dates[0]!, - known_at: makeUtcMs(dates[0]!, 10), - shares_short: 1000 * id, - net_change: 100 * id, - pct_float: 0.01 * id, - source: 'ceoShorts', - })); - const undersizedStore = createFakeStore({ - bars: twoDayBars, - shortsTable: { columns: SHORTS_COLUMNS, rows: singleSignalRows }, - }); - const undersizedLedger = createFakeTrialLedger(); - const undersizedRes = await callAnalyzeSignal({ - store: undersizedStore.store, - ledger: undersizedLedger.executor, - vaultCutoffTs: cutoffTs, - args: { - listingIds: [1, 2, 3, 4, 5, 6], - from: dates[0]!, - to: dates[1]!, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(undersizedRes.isError).toBe(false); - const undersizedPayload = JSON.parse(undersizedRes.text) as AnalyzeSignalResultPayload; - expect(undersizedPayload.status).toBe('insufficient_data'); - if (undersizedPayload.status === 'insufficient_data') { - expect(undersizedPayload.reason).toBe('too_few_observations'); - } - expect(undersizedLedger.rows).toHaveLength(0); - - // 4. Zero-variance rank_ic series (identical strictly monotone rank ordering every day -> rank_ic = 1.0 on every date) - const monotoneBars: BarRecord[] = []; - for (let d = 0; d < dates.length; d += 1) { - const ts = makeUtcMs(dates[d]!, 21); - for (let id = 1; id <= 6; id += 1) { - const close = 100 * Math.pow(1 + 0.01 * id, d); - monotoneBars.push({ - listingId: id, - ts, - open: close, - high: close, - low: close, - close, - volume: 1000, - vwap: close, - knownAt: ts, - }); - } - } - const zeroVarStore = createFakeStore({ - bars: monotoneBars, - shortsTable: { columns: SHORTS_COLUMNS, rows: singleSignalRows }, - }); - const zeroVarLedger = createFakeTrialLedger(); - const zeroVarRes = await callAnalyzeSignal({ - store: zeroVarStore.store, - ledger: zeroVarLedger.executor, - vaultCutoffTs: cutoffTs, - args: { - listingIds: [1, 2, 3, 4, 5, 6], - from: dates[0]!, - to: dates[dates.length - 1]!, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(zeroVarRes.isError).toBe(false); - const zeroVarPayload = JSON.parse(zeroVarRes.text) as AnalyzeSignalResultPayload; - expect(zeroVarPayload.status).toBe('insufficient_data'); - if (zeroVarPayload.status === 'insufficient_data') { - expect(zeroVarPayload.reason).toBe('zero_variance_series'); - } - expect(zeroVarLedger.rows).toHaveLength(0); - }); - - test('strict schema rejects forbidden keys, unknown keys, bad selectors, invalid dates/UUIDs, INT32/limit/horizon violations with zero store or ledger calls', async () => { - const cutoffTs = makeUtcMs('2025-03-31', 0); - const validBase = { - listingIds: [101, 102], - from: '2025-01-02', - to: '2025-03-20', - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; - - const invalidCases: readonly [string, Record][] = [ - ['scope vault_evaluation_only', { ...validBase, scope: 'vault_evaluation_only' }], - ['scope vault_fenced', { ...validBase, scope: 'vault_fenced' }], - ['vault_evaluation_only flag', { ...validBase, vault_evaluation_only: true }], - ['principalId override', { ...validBase, principalId: 'operator' }], - ['vaultCutoffDate override', { ...validBase, vaultCutoffDate: '2026-01-01' }], - ['unknown top-level key', { ...validBase, extraFlag: true }], - [ - 'unknown nested signal key', - { ...validBase, signal: { source: 'shorts', field: 'net_change', extra: 1 } }, - ], - ['both listingIds and universe', { ...validBase, universe: 'CA_EQ' }], - [ - 'neither listingIds nor universe', - { - from: validBase.from, - to: validBase.to, - signal: validBase.signal, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - ], - ['unknown signal.source', { ...validBase, signal: { source: 'fundamentals', field: 'net_change' } }], - ['unknown signal.field', { ...validBase, signal: { source: 'shorts', field: 'unknown_col' } }], - ['invalid calendar date from', { ...validBase, from: '2025-02-30' }], - ['invalid string date to', { ...validBase, to: 'not-a-date' }], - ['naive timestamp without offset in asOf', { ...validBase, asOf: '2025-02-01T12:00:00' }], - ['invalid campaignId UUID', { ...validBase, campaignId: 'not-a-uuid' }], - ['invalid hypothesisId UUID', { ...validBase, hypothesisId: '12345' }], - ['INT32 overflow listingId', { ...validBase, listingIds: [2_147_483_648] }], - ['INT32 underflow listingId', { ...validBase, listingIds: [-2_147_483_649] }], - ['non-integer listingId', { ...validBase, listingIds: [101.5] }], - ['empty listingIds', { ...validBase, listingIds: [] }], - [ - 'more than 500 explicit listingIds', - { - ...validBase, - listingIds: Array.from({ length: ANALYZE_SIGNAL_MAX_LISTING_IDS + 1 }, (_, i) => i + 1), - }, - ], - ['horizonSessions 0', { ...validBase, horizonSessions: 0 }], - ['horizonSessions negative', { ...validBase, horizonSessions: -3 }], - [ - 'horizonSessions above max', - { ...validBase, horizonSessions: ANALYZE_SIGNAL_MAX_HORIZON_SESSIONS + 1 }, - ], - ['horizonSessions float', { ...validBase, horizonSessions: 2.5 }], - ['negative maxSignalAgeSessions', { ...validBase, maxSignalAgeSessions: -1 }], - ['mismatched horizonBucket intraday for 5d daily horizon', { ...validBase, horizonSessions: 5, horizonBucket: 'intraday' }], - [ - 'mismatched horizonBucket position_10d_plus for 5d daily horizon', - { ...validBase, horizonSessions: 5, horizonBucket: 'position_10d_plus' }, - ], - [ - 'mismatched horizonBucket swing_1_10d for 11d daily horizon', - { ...validBase, horizonSessions: 11, horizonBucket: 'swing_1_10d' }, - ], - [ - 'mismatched horizonBucket intraday for 15d daily horizon', - { ...validBase, horizonSessions: 15, horizonBucket: 'intraday' }, - ], - [ - 'named universe CA_EQ with mismatched universeMarket FX', - { - from: validBase.from, - to: validBase.to, - signal: validBase.signal, - horizonSessions: 5, - universe: 'CA_EQ', - universeMarket: 'FX', - horizonBucket: 'swing_1_10d', - }, - ], - [ - 'named universe CA_EQ with mismatched universeMarket US_EQ', - { - from: validBase.from, - to: validBase.to, - signal: validBase.signal, - horizonSessions: 5, - universe: 'CA_EQ', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - ], - [ - 'named universe US_CA_EQ with mismatched universeMarket US_EQ', - { - from: validBase.from, - to: validBase.to, - signal: validBase.signal, - horizonSessions: 5, - universe: 'US_CA_EQ', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - ], - ['shorts study with FX universeMarket and listingIds', { ...validBase, universeMarket: 'FX' }], - ]; - - for (const [_label, args] of invalidCases) { - const fakeStore = createFakeStore(); - const fakeLedger = createFakeTrialLedger(); - const res = await callAnalyzeSignal({ - store: fakeStore.store, - ledger: fakeLedger.executor, - vaultCutoffTs: cutoffTs, - args, - }); - - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "analyze_signal":'); - expect(fakeStore.barsCalls).toHaveLength(0); - expect(fakeStore.shortsCalls).toHaveLength(0); - expect(fakeStore.universeCalls).toHaveLength(0); - expect(fakeLedger.insertCalls).toBe(0); - } - - // Raw JSON own __proto__ key rejected with zero store or ledger calls - const protoStore = createFakeStore(); - const protoLedger = createFakeTrialLedger(); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createAnalyzeSignalTool({ - store: protoStore.store, - ledger: protoLedger.executor, - vaultContext: { vaultCutoffTs: cutoffTs }, - principalId: AGENT_PRINCIPAL, - }), - ], - }); - const rawProto = - '{"jsonrpc":"2.0","id":"proto-1","method":"tools/call","params":{"name":"analyze_signal","arguments":{"listingIds":[101],"from":"2025-01-02","to":"2025-03-20","signal":{"source":"shorts","field":"net_change"},"horizonSessions":5,"universeMarket":"CA_EQ","horizonBucket":"swing_1_10d","__proto__":{"principalId":"operator"}}}}'; - const protoResp = JSON.parse((await server.handleMessage(rawProto)) as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(protoResp.result.isError).toBe(true); - expect(protoStore.barsCalls).toHaveLength(0); - expect(protoLedger.insertCalls).toBe(0); - }); - - test('sanitizes store, panel, ledger insert, and DSR read failures without leaking SQL, paths, or connection URIs', async () => { - const fixture = buildCeoShortsFixture(); - const from = fixture.allDates[0]!; - const to = fixture.allDates[fixture.allDates.length - 1]!; - const validArgs = { - listingIds: fixture.listingIds, - from, - to, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }; - - const sensitiveDetail = - 'SELECT * FROM trial_ledger WHERE secret=1 at /mnt/data/stockbot/curated/shorts/part.parquet via postgres://user:pass@host:5432/trading_bot'; - - function assertNoLeak(rawResponse: string): void { - expect(rawResponse).not.toContain('SELECT * FROM trial_ledger'); - expect(rawResponse).not.toContain('/mnt/data/stockbot'); - expect(rawResponse).not.toContain('part.parquet'); - expect(rawResponse).not.toContain('postgres://user:pass@host'); - } - - // 1. Store domain & unexpected errors - const storeErrors: readonly [Error, string][] = [ - [new VaultScopeNotAuthorizedError(sensitiveDetail), 'VaultScopeNotAuthorizedError'], - [new MarketDataStoreValidationError(sensitiveDetail, 'curatedRoot'), 'MarketDataStoreValidationError'], - [new MarketDataStoreNotImplementedError('shortsAsOf', sensitiveDetail), 'MarketDataStoreNotImplementedError'], - [new Error(sensitiveDetail), 'Error: Tool execution failed.'], - ]; - for (const [err, expectedSnippet] of storeErrors) { - const store = createFakeStore({ shortsError: err, bars: fixture.bars }); - const ledger = createFakeTrialLedger(); - const res = await callAnalyzeSignal({ - store: store.store, - ledger: ledger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: validArgs, - }); - expect(res.isError).toBe(true); - expect(res.text).toContain(expectedSnippet); - assertNoLeak(res.rawResponse); - expect(ledger.rows).toHaveLength(0); - } - - // 2. Malformed shorts table -> SignalPanelError mapped cleanly - const badTableStore = createFakeStore({ - bars: fixture.bars, - shortsTable: { columns: ['listing_id'], rows: [] }, - }); - const badTableLedger = createFakeTrialLedger(); - const badTableRes = await callAnalyzeSignal({ - store: badTableStore.store, - ledger: badTableLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: validArgs, - }); - expect(badTableRes.isError).toBe(true); - expect(badTableRes.text).toContain('SignalPanelError:'); - expect(badTableLedger.rows).toHaveLength(0); - - // 3. Ledger INSERT failure -> isError: true, no leak, zero trial rows written - const insertFailStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - }); - const insertFailLedger = createFakeTrialLedger({ - insertError: new Error(sensitiveDetail), - }); - const insertFailRes = await callAnalyzeSignal({ - store: insertFailStore.store, - ledger: insertFailLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: validArgs, - }); - expect(insertFailRes.isError).toBe(true); - expect(insertFailRes.text).toBe('Error: Tool execution failed.'); - assertNoLeak(insertFailRes.rawResponse); - expect(insertFailLedger.insertCalls).toBe(1); - expect(insertFailLedger.rows).toHaveLength(0); - - // 4. DSR read failure after INSERT -> isError: true, fixed SignalStudyError, no leak, exactly 1 insert (never retried) - const dsrFailStore = createFakeStore({ - bars: fixture.bars, - shortsTable: fixture.shortsTable, - }); - const dsrFailLedger = createFakeTrialLedger({ - dsrReadError: new Error(sensitiveDetail), - }); - const dsrFailRes = await callAnalyzeSignal({ - store: dsrFailStore.store, - ledger: dsrFailLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: validArgs, - }); - expect(dsrFailRes.isError).toBe(true); - expect(dsrFailRes.text).toBe( - 'SignalStudyError: Trial was recorded, but cluster deflated Sharpe evaluation failed.' - ); - assertNoLeak(dsrFailRes.rawResponse); - expect(dsrFailLedger.insertCalls).toBe(1); - expect(dsrFailLedger.rows).toHaveLength(1); - }); -}); - -interface FundamentalsPitFixtureRow { - readonly listing_id: number; - readonly effective_known_at: number; - readonly known_at_source: string; - readonly has_estimated_lag: boolean; - readonly period_end: string; - readonly fiscal_period: string; - readonly currency: string; - readonly period_known_at: number; - readonly revenue: number | null; - readonly net_income: number | null; - readonly operating_cash_flow: number | null; - readonly total_assets: number | null; - readonly total_equity: number | null; - readonly shares_outstanding: number | null; - readonly ttm_revenue: number | null; - readonly ttm_net_income: number | null; - readonly ttm_operating_cash_flow: number | null; - readonly ttm_period_end: string | null; - readonly ttm_currency: string | null; - readonly ttm_has_estimated_lag: boolean; -} - -const FUNDAMENTALS_TTM_FIELDS = new Set([ - 'ttm_revenue', - 'ttm_net_income', - 'ttm_operating_cash_flow', -]); - -function queryFundamentalsFixtureRows( - rows: readonly FundamentalsPitFixtureRow[], - q: FundamentalsAsOfQuery -): Table { - const idSet = new Set(q.listingIds); - const asOfMs = Date.parse(q.asOf.length === 10 ? `${q.asOf}T23:59:59.999Z` : q.asOf); - const allowEstimatedLag = q.allowEstimatedLag ?? false; - - const latestByListing = new Map(); - for (const row of rows) { - if (!idSet.has(row.listing_id) || row.effective_known_at > asOfMs) { - continue; - } - const prev = latestByListing.get(row.listing_id); - if (prev === undefined || row.effective_known_at > prev.effective_known_at) { - latestByListing.set(row.listing_id, row); - } - } - - const hasTtm = q.fields.some(f => FUNDAMENTALS_TTM_FIELDS.has(f)); - const columns: string[] = [ - 'listing_id', - 'effective_known_at', - 'known_at_source', - 'has_estimated_lag', - 'period_end', - 'fiscal_period', - 'currency', - 'period_known_at', - ...q.fields, - ...(hasTtm ? ['ttm_period_end', 'ttm_currency', 'ttm_has_estimated_lag'] : []), - ]; - - const outRows: TableRow[] = []; - const sortedIds = [...latestByListing.keys()].sort((a, b) => a - b); - for (const lid of sortedIds) { - const selected = latestByListing.get(lid)!; - if (!allowEstimatedLag && selected.has_estimated_lag) { - continue; - } - const projected: Record = { - listing_id: selected.listing_id, - effective_known_at: selected.effective_known_at, - known_at_source: selected.known_at_source, - has_estimated_lag: selected.has_estimated_lag, - period_end: selected.period_end, - fiscal_period: selected.fiscal_period, - currency: selected.currency, - period_known_at: selected.period_known_at, - }; - for (const field of q.fields) { - const val = selected[field as keyof FundamentalsPitFixtureRow] as number | null; - if (FUNDAMENTALS_TTM_FIELDS.has(field)) { - projected[field] = allowEstimatedLag || !selected.ttm_has_estimated_lag ? val : null; - } else { - projected[field] = val; - } - } - if (hasTtm) { - projected.ttm_period_end = - allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_period_end : null; - projected.ttm_currency = - allowEstimatedLag || !selected.ttm_has_estimated_lag ? selected.ttm_currency : null; - projected.ttm_has_estimated_lag = selected.ttm_has_estimated_lag; - } - outRows.push(projected); - } - - return { columns, rows: outRows }; -} - -function makeFundamentalsRow(params: { - listingId: number; - effectiveKnownAt: number; - periodEnd: string; - fiscalPeriod: string; - revenue: number; - ttmRevenue: number; - hasEstimatedLag?: boolean; - ttmHasEstimatedLag?: boolean; -}): FundamentalsPitFixtureRow { - const hasEstimatedLag = params.hasEstimatedLag ?? false; - const ttmHasEstimatedLag = params.ttmHasEstimatedLag ?? false; - return { - listing_id: params.listingId, - effective_known_at: params.effectiveKnownAt, - known_at_source: hasEstimatedLag ? 'estimated_lag' : 'sec_edgar_filing', - has_estimated_lag: hasEstimatedLag, - period_end: params.periodEnd, - fiscal_period: params.fiscalPeriod, - currency: 'USD', - period_known_at: params.effectiveKnownAt, - revenue: params.revenue, - net_income: Number((params.revenue * 0.15).toFixed(2)), - operating_cash_flow: Number((params.revenue * 0.2).toFixed(2)), - total_assets: Number((params.revenue * 4.0).toFixed(2)), - total_equity: Number((params.revenue * 1.8).toFixed(2)), - shares_outstanding: 10_000_000, - ttm_revenue: params.ttmRevenue, - ttm_net_income: Number((params.ttmRevenue * 0.15).toFixed(2)), - ttm_operating_cash_flow: Number((params.ttmRevenue * 0.2).toFixed(2)), - ttm_period_end: params.periodEnd, - ttm_currency: 'USD', - ttm_has_estimated_lag: ttmHasEstimatedLag, - }; -} - -// Seeded fundamentals study fixture metadata (pinned for reproducibility): -// - Dataset ID: `synthetic:mcp-analyze-signal-fundamentals:seed-20261202:v1` -// - Tool version: `mcp:analyze_signal:v1` -// - Seed: `20261202` (Mulberry32 PRNG) -// - Universe: 12 synthetic US equity listings (`70001..70012`, USD, 21:00 UTC close) -// - Pre-Vault window: 2023-01-02..2023-06-30 (130 business sessions), Vault cutoff: 2023-07-03T00:00:00.000Z -// - Adjustment: `raw`, horizon: `5` sessions, modeled execution/transaction costs: `0` -// - Ownership: Quant research owns evidence; Director owns adoption. -const FUNDAMENTALS_FIXTURE_SEED = 20261202; - -function buildFundamentalsStudyFixture(): { - readonly listingIds: number[]; - readonly allDates: string[]; - readonly preCutoffSessions: number; - readonly vaultCutoffDate: string; - readonly vaultCutoffTs: number; - readonly bars: BarRecord[]; - readonly fundamentalsRows: FundamentalsPitFixtureRow[]; -} { - const rand = createSeededRng(FUNDAMENTALS_FIXTURE_SEED); - const listingCount = 12; - const preCutoffSessions = 130; - const postCutoffSessions = 10; - const allDates = makeBusinessDates('2023-01-02', preCutoffSessions + postCutoffSessions); - const vaultCutoffDate = allDates[preCutoffSessions]!; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - const listingIds = Array.from({ length: listingCount }, (_, i) => 70_001 + i); - - const fundamentalsRows: FundamentalsPitFixtureRow[] = []; - // Monthly PIT releases across 6 pre-cutoff months + 1 post-cutoff release - const releaseDates = [ - { date: '2023-01-10', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' }, - { date: '2023-02-15', periodEnd: '2022-12-31', fiscalPeriod: 'Q4' }, - { date: '2023-04-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' }, - { date: '2023-05-18', periodEnd: '2023-03-31', fiscalPeriod: 'Q1' }, - { date: vaultCutoffDate, periodEnd: '2023-06-30', fiscalPeriod: 'Q2' }, - ]; - - const activeScore = new Float64Array(listingCount); - for (let rIdx = 0; rIdx < releaseDates.length; rIdx += 1) { - const rel = releaseDates[rIdx]!; - const knownAt = makeUtcMs(rel.date, 13); // 08:00 ET pre-close - for (let l = 0; l < listingCount; l += 1) { - const rev = 100 + l * 25 + rIdx * 10 + Math.round((rand() * 2 - 1) * 40); - const ttm = rev * 4 + (l % 3) * 15; - fundamentalsRows.push( - makeFundamentalsRow({ - listingId: listingIds[l]!, - effectiveKnownAt: knownAt, - periodEnd: rel.periodEnd, - fiscalPeriod: rel.fiscalPeriod, - revenue: rev, - ttmRevenue: ttm, - }) - ); - } - } - - const prices = new Float64Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - prices[l] = 20 + l * 3; - } - - const bars: BarRecord[] = []; - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); - for (let l = 0; l < listingCount; l += 1) { - activeScore[l] = (l - listingCount / 2) / listingCount; - const dailyRet = 0.002 * activeScore[l]! + (rand() * 2 - 1) * 0.01; - prices[l] = Math.max(1.0, prices[l]! * (1 + dailyRet)); - const close = Number(prices[l]!.toFixed(6)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 80_000, - vwap: close, - knownAt: closeTs, - }); - } - } - - return { - listingIds, - allDates, - preCutoffSessions, - vaultCutoffDate, - vaultCutoffTs, - bars, - fundamentalsRows, - }; -} - -describe('MCP analyze_signal tool — fundamentals source', () => { - test('tools/list advertises strict signal discriminated branches and rejects invalid fundamentals inputs with zero store/ledger calls', async () => { - const cutoffTs = makeUtcMs('2025-03-31', 0); - const fakeStore = createFakeStore(); - const fakeLedger = createFakeTrialLedger(); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createAnalyzeSignalTool({ - store: fakeStore.store, - ledger: fakeLedger.executor, - vaultContext: { vaultCutoffTs: cutoffTs }, - principalId: AGENT_PRINCIPAL, - }), - ], - }); - - const listRaw = await server.handleMessage( - JSON.stringify({ jsonrpc: '2.0', id: 'list-fund', method: 'tools/list' }) - ); - const listParsed = JSON.parse(listRaw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - properties: { - signal: { - type: string; - additionalProperties: boolean; - properties: Record; - anyOf: { - additionalProperties: boolean; - properties: Record; - }[]; - }; - }; - }; - }[]; - }; - }; - - const tool = listParsed.result.tools[0]!; - expect(tool.description).toContain('fundamentals'); - expect(tool.description).toContain('short-interest'); - - const signalSchema = tool.inputSchema.properties.signal; - expect(signalSchema.type).toBe('object'); - expect(signalSchema.additionalProperties).toBe(false); - expect(Object.keys(signalSchema.properties).sort()).toEqual([ - 'allowEstimatedLag', - 'field', - 'source', - ]); - expect(signalSchema.anyOf).toHaveLength(2); - expect(signalSchema.anyOf[0]?.additionalProperties).toBe(false); - expect(signalSchema.anyOf[0]?.properties.source?.const).toBe('shorts'); - expect(signalSchema.anyOf[1]?.additionalProperties).toBe(false); - expect(signalSchema.anyOf[1]?.properties.source?.const).toBe('fundamentals'); - expect(signalSchema.anyOf[1]?.properties.field?.enum).toEqual([...FUNDAMENTALS_PIT_VALUE_FIELDS]); - expect(signalSchema.anyOf[1]?.properties.allowEstimatedLag?.default).toBe(false); - - const validBase = { - listingIds: [70_001, 70_002], - from: '2023-01-02', - to: '2023-06-30', - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - const invalidCases: readonly [string, Record][] = [ - ['unknown fundamentals field', { ...validBase, signal: { source: 'fundamentals', field: 'ebitda_fake' } }], - ['shorts field on fundamentals source', { ...validBase, signal: { source: 'fundamentals', field: 'net_change' } }], - ['fundamentals field on shorts source', { ...validBase, signal: { source: 'shorts', field: 'ttm_revenue' } }], - ['unknown signal.source', { ...validBase, signal: { source: 'macro', field: 'ttm_revenue' } }], - [ - 'unknown nested key in fundamentals signal', - { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', extraKey: true } }, - ], - [ - 'allowEstimatedLag on shorts source', - { ...validBase, signal: { source: 'shorts', field: 'net_change', allowEstimatedLag: false } }, - ], - [ - 'non-boolean allowEstimatedLag string', - { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 'true' } }, - ], - [ - 'non-boolean allowEstimatedLag number', - { ...validBase, signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: 1 } }, - ], - ['fundamentals study with FX universeMarket', { ...validBase, universeMarket: 'FX' }], - ]; - - for (const [_label, args] of invalidCases) { - const store = createFakeStore(); - const ledger = createFakeTrialLedger(); - const res = await callAnalyzeSignal({ - store: store.store, - ledger: ledger.executor, - vaultCutoffTs: cutoffTs, - args, - }); - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "analyze_signal":'); - expect(store.barsCalls).toHaveLength(0); - expect(store.shortsCalls).toHaveLength(0); - expect(store.fundamentalsCalls).toHaveLength(0); - expect(store.universeCalls).toHaveLength(0); - expect(ledger.insertCalls).toBe(0); - } - }); - - test('executes fundamentals study, records canonical fundamentals expressionHash, forwards allowEstimatedLag verbatim, and preserves identity on append-only retry', async () => { - const fixture = buildFundamentalsStudyFixture(); - const from = fixture.allDates[0]!; - const to = fixture.allDates[fixture.preCutoffSessions - 1]!; - - const store = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), - }); - const sharedLedger = createFakeTrialLedger(); - - const baseArgs = { - listingIds: fixture.listingIds, - from, - to, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - campaignId: CAMPAIGN_UUID, - hypothesisId: HYPOTHESIS_UUID, - }; - - const res1 = await callAnalyzeSignal({ - store: store.store, - ledger: sharedLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - principalId: AGENT_PRINCIPAL, - args: baseArgs, - }); - expect(res1.isError).toBe(false); - const payload1 = JSON.parse(res1.text) as AnalyzeSignalResultPayload; - expect(payload1.status).toBe('ok'); - if (payload1.status !== 'ok') { - return; - } - - expect(payload1.signal).toEqual({ - source: 'fundamentals', - field: 'ttm_revenue', - allowEstimatedLag: false, - }); - expect(sharedLedger.rows).toHaveLength(1); - expect(sharedLedger.rows[0]?.stage).toBe('signal_ic'); - expect(sharedLedger.rows[0]?.principal_id).toBe(AGENT_PRINCIPAL); - - // Verify canonical expression prefix `mcp:analyze_signal:v1:fundamentals:` via canonicalExpressionHash - const expectedHash = canonicalExpressionHash({ - expression: 'mcp:analyze_signal:v1:fundamentals:ttm_revenue', - params: { - version: 1, - signalSource: 'fundamentals', - signalField: 'ttm_revenue', - allowEstimatedLag: false, - horizonSessions: 5, - maxSignalAgeSessions: null, - adjustment: 'raw', - ledgerSeries: 'rank_ic', - effectiveFrom: payload1.effectiveFrom, - effectiveTo: payload1.effectiveTo, - effectiveAsOf: payload1.effectiveAsOf, - }, - universe: { - kind: 'listingIds', - listingIds: fixture.listingIds, - }, - horizon: '5d', - sampleStart: payload1.trial.sampleStart, - sampleEnd: payload1.trial.sampleEnd, - }); - expect(payload1.trial.expressionHash).toBe(expectedHash); - expect(sharedLedger.rows[0]?.expression_hash).toBe(expectedHash); - - // Default allowEstimatedLag === false forwarded verbatim to every fundamentalsAsOf call - expect(store.fundamentalsCalls.length).toBeGreaterThan(0); - expect(store.shortsCalls).toHaveLength(0); - for (const call of store.fundamentalsCalls) { - expect(call.fields).toEqual(['ttm_revenue']); - expect(call.allowEstimatedLag).toBe(false); - } - - // Re-running identical request against the SAME ledger appends under append-only rules with one distinct expression_hash - const res2 = await callAnalyzeSignal({ - store: store.store, - ledger: sharedLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - principalId: AGENT_PRINCIPAL, - args: baseArgs, - }); - expect(res2.isError).toBe(false); - const payload2 = JSON.parse(res2.text) as AnalyzeSignalResultPayload; - expect(payload2.status).toBe('ok'); - if (payload2.status !== 'ok') { - return; - } - expect(payload2.trial.expressionHash).toBe(payload1.trial.expressionHash); - expect(new Set(sharedLedger.rows.map(r => r.expression_hash)).size).toBe(1); - - // Explicit allowEstimatedLag: false and reordered/duplicated listingIds preserve identity - const explicitFalseStore = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), - }); - const explicitFalseLedger = createFakeTrialLedger(); - const reorderedIds = [...fixture.listingIds].reverse(); - reorderedIds.push(fixture.listingIds[0]!, fixture.listingIds[2]!); - const resExplicitFalse = await callAnalyzeSignal({ - store: explicitFalseStore.store, - ledger: explicitFalseLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - ...baseArgs, - listingIds: reorderedIds, - signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: false }, - }, - }); - const payloadExplicitFalse = JSON.parse(resExplicitFalse.text) as AnalyzeSignalResultPayload; - expect(payloadExplicitFalse.status).toBe('ok'); - if (payloadExplicitFalse.status === 'ok') { - expect(payloadExplicitFalse.trial.expressionHash).toBe(payload1.trial.expressionHash); - } - expect(explicitFalseStore.fundamentalsCalls.every(c => c.allowEstimatedLag === false)).toBe(true); - - // allowEstimatedLag: true forwards true verbatim and changes expressionHash - const lagTrueStore = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), - }); - const lagTrueLedger = createFakeTrialLedger(); - const resLagTrue = await callAnalyzeSignal({ - store: lagTrueStore.store, - ledger: lagTrueLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - ...baseArgs, - signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, - }, - }); - const payloadLagTrue = JSON.parse(resLagTrue.text) as AnalyzeSignalResultPayload; - expect(payloadLagTrue.status).toBe('ok'); - if (payloadLagTrue.status === 'ok') { - expect(payloadLagTrue.signal).toEqual({ - source: 'fundamentals', - field: 'ttm_revenue', - allowEstimatedLag: true, - }); - expect(payloadLagTrue.trial.expressionHash).not.toBe(payload1.trial.expressionHash); - } - expect(lagTrueStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); - - // Different field changes expressionHash - const otherFieldStore = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), - }); - const otherFieldLedger = createFakeTrialLedger(); - const resOtherField = await callAnalyzeSignal({ - store: otherFieldStore.store, - ledger: otherFieldLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - ...baseArgs, - signal: { source: 'fundamentals', field: 'revenue' }, - }, - }); - const payloadOtherField = JSON.parse(resOtherField.text) as AnalyzeSignalResultPayload; - expect(payloadOtherField.status).toBe('ok'); - if (payloadOtherField.status === 'ok') { - expect(payloadOtherField.trial.expressionHash).not.toBe(payload1.trial.expressionHash); - } - - // Shorts study over the same window/listings produces a distinct expressionHash - const shortsRows: TableRow[] = fixture.listingIds.map((lid, i) => ({ - listing_id: lid, - report_date: from, - known_at: makeUtcMs(from, 12), - shares_short: 100_000 + i * 5_000, - net_change: (i - 5) * 1_000, - pct_float: 0.03 + i * 0.005, - source: 'ceoShorts', - })); - const shortsStore = createFakeStore({ - bars: fixture.bars, - shortsTable: { columns: SHORTS_COLUMNS, rows: shortsRows }, - }); - const shortsLedger = createFakeTrialLedger(); - const resShorts = await callAnalyzeSignal({ - store: shortsStore.store, - ledger: shortsLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args: { - ...baseArgs, - signal: { source: 'shorts', field: 'net_change' }, - }, - }); - const payloadShorts = JSON.parse(resShorts.text) as AnalyzeSignalResultPayload; - expect(payloadShorts.status).toBe('ok'); - if (payloadShorts.status === 'ok') { - expect(payloadShorts.trial.expressionHash).not.toBe(payload1.trial.expressionHash); - } - }); - - test('queries month-end snapshots in ascending order from unsorted bars, preserves earlier explicit asOf, enforces 120-snapshot cap, and handles empty bars', async () => { - // 1. Unsorted bars spanning 3 UTC months (2 full + 1 partial final month) with earlier intraday asOf - const janDates = ['2023-01-10', '2023-01-31']; - const febDates = ['2023-02-14', '2023-02-28']; - const marDates = ['2023-03-08', '2023-03-15']; - const unsortedDates = [...marDates, ...janDates, ...febDates].reverse(); - const bars: BarRecord[] = []; - for (const date of unsortedDates) { - const ts = makeUtcMs(date, 21); - for (const lid of [101, 102]) { - bars.push({ - listingId: lid, - ts, - open: 10, - high: 10, - low: 10, - close: 10, - volume: 100, - vwap: 10, - knownAt: ts, - }); - } - } - - const cutoffTs = makeUtcMs('2023-04-01', 0); - const preWindowKnownAt = makeUtcMs('2022-12-15', 13); - const storeOrder = createFakeStore({ - bars, - fundamentalsResolver: q => ({ - columns: ['listing_id', 'effective_known_at', 'revenue'], - rows: q.listingIds.map(lid => ({ - listing_id: lid, - effective_known_at: preWindowKnownAt, - revenue: 100, - })), - }), - }); - const ledgerOrder = createFakeTrialLedger(); - - // Earlier explicit asOf on 2023-03-15T22:30:00.123456Z (after 21:00 bar close, before day end) - const explicitAsOf = '2023-03-15T22:30:00.123456Z'; - const orderRes = await callAnalyzeSignal({ - store: storeOrder.store, - ledger: ledgerOrder.executor, - vaultCutoffTs: cutoffTs, - args: { - listingIds: [102, 101], - from: '2023-01-01', - to: '2023-03-31', - asOf: explicitAsOf, - signal: { source: 'fundamentals', field: 'revenue' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(orderRes.isError).toBe(false); - expect(storeOrder.fundamentalsCalls.map(c => c.asOf)).toEqual([ - '2023-01-31T23:59:59.999999Z', - '2023-02-28T23:59:59.999999Z', - explicitAsOf, - ]); - expect(storeOrder.fundamentalsCalls.every(c => c.listingIds[0] === 101 && c.listingIds[1] === 102)).toBe(true); - - // 2. Empty eligible bar sample -> 0 fundamentalsAsOf calls, insufficient_data, 0 ledger writes - const emptyBarsStore = createFakeStore({ - bars: [], - fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), - }); - const emptyBarsLedger = createFakeTrialLedger(); - const emptyRes = await callAnalyzeSignal({ - store: emptyBarsStore.store, - ledger: emptyBarsLedger.executor, - vaultCutoffTs: cutoffTs, - args: { - listingIds: [101, 102], - from: '2023-01-01', - to: '2023-03-31', - signal: { source: 'fundamentals', field: 'revenue' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(emptyRes.isError).toBe(false); - const emptyPayload = JSON.parse(emptyRes.text) as AnalyzeSignalResultPayload; - expect(emptyPayload.status).toBe('insufficient_data'); - if (emptyPayload.status === 'insufficient_data') { - expect(emptyPayload.reason).toBe('too_few_observations'); - } - expect(emptyBarsStore.fundamentalsCalls).toHaveLength(0); - expect(emptyBarsLedger.rows).toHaveLength(0); - - // 3. Exactly 120 eligible UTC months is accepted; 121 is rejected with 0 fundamentals calls and 0 ledger inserts - function makeMonthlyBars(monthCount: number): BarRecord[] { - const out: BarRecord[] = []; - for (let m = 0; m < monthCount; m += 1) { - const year = 2010 + Math.floor(m / 12); - const month = (m % 12) + 1; - const date = `${year}-${String(month).padStart(2, '0')}-15`; - const ts = makeUtcMs(date, 21); - out.push({ - listingId: 101, - ts, - open: 10, - high: 10, - low: 10, - close: 10, - volume: 100, - vwap: 10, - knownAt: ts, - }); - } - return out; - } - - const capCutoffTs = makeUtcMs('2025-01-01', 0); - const capPreWindowKnownAt = makeUtcMs('2009-12-15', 13); - const exactCapStore = createFakeStore({ - bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS), - fundamentalsResolver: q => ({ - columns: ['listing_id', 'effective_known_at', 'revenue'], - rows: q.listingIds.map(lid => ({ - listing_id: lid, - effective_known_at: capPreWindowKnownAt, - revenue: 100, - })), - }), - }); - const exactCapLedger = createFakeTrialLedger(); - const exactCapRes = await callAnalyzeSignal({ - store: exactCapStore.store, - ledger: exactCapLedger.executor, - vaultCutoffTs: capCutoffTs, - args: { - listingIds: [101], - from: '2010-01-01', - to: '2024-12-31', - signal: { source: 'fundamentals', field: 'revenue' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(exactCapRes.isError).toBe(false); - expect(exactCapStore.fundamentalsCalls).toHaveLength(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS); - - const overCapStore = createFakeStore({ - bars: makeMonthlyBars(ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS + 1), - fundamentalsResolver: () => ({ columns: ['listing_id', 'effective_known_at', 'revenue'], rows: [] }), - }); - const overCapLedger = createFakeTrialLedger(); - const overCapRes = await callAnalyzeSignal({ - store: overCapStore.store, - ledger: overCapLedger.executor, - vaultCutoffTs: capCutoffTs, - args: { - listingIds: [101], - from: '2010-01-01', - to: '2024-12-31', - signal: { source: 'fundamentals', field: 'revenue' }, - horizonSessions: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(overCapRes.isError).toBe(true); - expect(overCapRes.text).toBe( - `Invalid arguments for tool "analyze_signal": Fundamentals study exceeds maximum of ${ANALYZE_SIGNAL_MAX_FUNDAMENTAL_SNAPSHOTS} month-end snapshots.` - ); - expect(overCapStore.fundamentalsCalls).toHaveLength(0); - expect(overCapLedger.insertCalls).toBe(0); - expect(overCapLedger.rows).toHaveLength(0); - }); - - test('restatement replay prevents look-ahead: dates before Q1 restatement use originally known values and appending a future revision leaves prior output unchanged', async () => { - // Explicit deterministic restatement fixture: - // - 6 listings across 2023-01-02..2023-05-31 (108 sessions), Vault cutoff 2023-06-01T00:00:00Z - // - Original Q1 known 2023-01-12T13:00Z (period_end 2022-12-31) - // - Original Q2 known 2023-02-15T13:00Z (period_end 2023-01-31) - // - Q1 restatement known 2023-04-12T13:00Z (AFTER Q2!): period_end stays 2023-01-31 (Q2), - // while ttm_revenue flips cross-sectional ordering for listings 0..5. - // - Unchanged months (March, May) re-emit identical (listing_id, effective_known_at) -> deduped cleanly. - const listingIds = [80_001, 80_002, 80_003, 80_004, 80_005, 80_006]; - const allDates = makeBusinessDates('2023-01-02', 112); - const preCutoffDates = allDates.filter(d => d < '2023-06-01'); - const vaultCutoffDate = '2023-06-01'; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - - const q1KnownAt = makeUtcMs('2023-01-12', 13); - const q2KnownAt = makeUtcMs('2023-02-15', 13); - const q1RestatedKnownAt = makeUtcMs('2023-04-12', 13); - const futureRevisionKnownAt = makeUtcMs('2023-06-15', 13); // post-cutoff - - const rand = createSeededRng(20261203); - const bars: BarRecord[] = []; - const prices = new Float64Array(listingIds.length).fill(50); - for (let t = 0; t < preCutoffDates.length; t += 1) { - const date = preCutoffDates[t]!; - const closeTs = makeUtcMs(date, 21); - for (let l = 0; l < listingIds.length; l += 1) { - const ret = (l - 2.5) * 0.0015 + (rand() * 2 - 1) * 0.008; - prices[l] = Math.max(1, prices[l]! * (1 + ret)); - const close = Number(prices[l]!.toFixed(6)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 25_000, - vwap: close, - knownAt: closeTs, - }); - } - } - - const basePitRows: FundamentalsPitFixtureRow[] = []; - const expectedDirectObs: SignalObservation[] = []; - - for (let l = 0; l < listingIds.length; l += 1) { - const lid = listingIds[l]!; - const q1Val = 100 + l * 20; - const q2Val = 120 + l * 25; - // Restatement reverses cross-sectional rank ordering after 2023-04-12 - const restatedVal = 300 - l * 30; - - basePitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: q1KnownAt, - periodEnd: '2022-12-31', - fiscalPeriod: 'Q1', - revenue: q1Val / 4, - ttmRevenue: q1Val, - }), - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: q2KnownAt, - periodEnd: '2023-01-31', - fiscalPeriod: 'Q2', - revenue: q2Val / 4, - ttmRevenue: q2Val, - }), - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: q1RestatedKnownAt, - periodEnd: '2023-01-31', - fiscalPeriod: 'Q2', - revenue: q2Val / 4, - ttmRevenue: restatedVal, - }) - ); - - expectedDirectObs.push( - { listingId: lid, knownAt: q1KnownAt, value: q1Val }, - { listingId: lid, knownAt: q2KnownAt, value: q2Val }, - { listingId: lid, knownAt: q1RestatedKnownAt, value: restatedVal } - ); - } - - // 1. Direct baseline using independently specified eligible observations - const directLedger = createFakeTrialLedger(); - const directBuilt = buildForwardReturnPanel({ - bars, - signals: expectedDirectObs, - horizonSessions: 5, - vaultCutoffDate, - }); - const directStudy = await analyzeSignal(directLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_restatement_baseline', - params: { field: 'ttm_revenue', horizonSessions: 5 }, - universe: listingIds, - horizon: '5d', - }, - panel: directBuilt.panel, - vaultCutoffDate, - }); - expect(directStudy.status).toBe('ok'); - if (directStudy.status !== 'ok') { - return; - } - - // 2. MCP handler run on base rows (before future revision is appended) - const args = { - listingIds, - from: preCutoffDates[0]!, - to: preCutoffDates[preCutoffDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - const mcpStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(basePitRows, q), - }); - const mcpLedger = createFakeTrialLedger(); - const mcpRes = await callAnalyzeSignal({ - store: mcpStore.store, - ledger: mcpLedger.executor, - vaultCutoffTs, - args, - }); - expect(mcpRes.isError).toBe(false); - const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; - expect(mcpPayload.status).toBe('ok'); - if (mcpPayload.status !== 'ok') { - return; - } - - // Exact parity between MCP handler and direct baseline (dates, rankIc, ledger daily_series) - expect(mcpPayload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); - expect(mcpPayload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); - expect(mcpLedger.rows[0]?.daily_series).toEqual(directLedger.rows[0]?.daily_series); - expect(mcpPayload.trial.sampleStart).toBe(directStudy.trial.sampleStart); - expect(mcpPayload.trial.sampleEnd).toBe(directStudy.trial.sampleEnd); - // Forward return endpoint remains strictly before vaultCutoffDate - const sampleEndIdx = preCutoffDates.indexOf(mcpPayload.trial.sampleEnd); - expect(sampleEndIdx).toBeGreaterThanOrEqual(0); - expect(sampleEndIdx + 5).toBeLessThan(preCutoffDates.length); - expect(preCutoffDates[sampleEndIdx + 5]! < vaultCutoffDate).toBe(true); - - // Confirm pre-restatement dates (between 2023-02-15 and 2023-04-11) actually differ from a look-ahead study - // that wrongly substitutes the restated values onto Q2's earlier known_at! - const lookAheadObs = expectedDirectObs.map(o => - o.knownAt === q2KnownAt - ? { ...o, value: 300 - (o.listingId - 80_001) * 30 } - : o - ); - const lookAheadBuilt = buildForwardReturnPanel({ - bars, - signals: lookAheadObs, - horizonSessions: 5, - vaultCutoffDate, - }); - const lookAheadLedger = createFakeTrialLedger(); - const lookAheadStudy = await analyzeSignal(lookAheadLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'look_ahead_counterfactual', - params: { field: 'ttm_revenue', horizonSessions: 5 }, - universe: listingIds, - horizon: '5d', - }, - panel: lookAheadBuilt.panel, - vaultCutoffDate, - }); - expect(lookAheadStudy.status).toBe('ok'); - expect(mcpLedger.rows[0]?.daily_series).not.toEqual(lookAheadLedger.rows[0]?.daily_series); - - // 3. Append a future revision (post-cutoff) and verify all prior dated outputs & ledger rows remain bit-identical - const rowsWithFutureRevision: FundamentalsPitFixtureRow[] = [ - ...basePitRows, - ...listingIds.map((lid, l) => - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: futureRevisionKnownAt, - periodEnd: '2023-01-31', - fiscalPeriod: 'Q2', - revenue: 999, - ttmRevenue: 9_999 + l, - }) - ), - ]; - const futureStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(rowsWithFutureRevision, q), - }); - const futureLedger = createFakeTrialLedger(); - const futureRes = await callAnalyzeSignal({ - store: futureStore.store, - ledger: futureLedger.executor, - vaultCutoffTs, - args, - }); - expect(futureRes.isError).toBe(false); - expect(futureRes.text).toBe(mcpRes.text); - expect(futureLedger.rows).toEqual(mcpLedger.rows); - }); - - test('same-month restatement replay retains earlier intra-month vintage through the day before the amendment', async () => { - // Regression fixture for intra-month superseded vintages: - // - Dataset ID: `synthetic:mcp-analyze-signal-same-month-restatement:seed-20261204:v1` - // - 6 listings across 2023-03-01..2023-05-12 (53 sessions), Vault cutoff 2023-05-15T00:00:00Z - // - March 10: initial Q1 release (listings 0..4 only; listing 5 has NO prior release before April 5) - // - April 5: Q2 release for all 6 listings (strictly ascending ttm_revenue across listings) - // - April 18: Q1 restatement (SAME month as Q2!) keeping Q2 as latest period while reversing - // ttm_revenue cross-sectional ordering. - // Under latest-only month-end reads, the April 30 snapshot returns only the April 18 vintage - // and erases April 5 from April 5..17 (falling back to March for listings 0..4 and dropping - // listing 5 completely). With intra-month backfill, April 5..17 uses the original April 5 Q2 - // values and April 18+ uses the restated values. - const listingIds = [81_001, 81_002, 81_003, 81_004, 81_005, 81_006]; - const allDates = makeBusinessDates('2023-03-01', 53); - const vaultCutoffDate = '2023-05-15'; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - - const marKnownAt = makeUtcMs('2023-03-10', 13); - const aprQ2KnownAt = makeUtcMs('2023-04-05', 13); - const aprRestatedKnownAt = makeUtcMs('2023-04-18', 13); - - const rand = createSeededRng(20261204); - const bars: BarRecord[] = []; - const prices = new Float64Array(listingIds.length).fill(40); - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); - for (let l = 0; l < listingIds.length; l += 1) { - const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; - prices[l] = Math.max(1, prices[l]! * (1 + ret)); - const close = Number(prices[l]!.toFixed(6)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 30_000, - vwap: close, - knownAt: closeTs, - }); - } - } - - const pitRows: FundamentalsPitFixtureRow[] = []; - const expectedAllVintagesObs: SignalObservation[] = []; - const brokenMonthEndOnlyObs: SignalObservation[] = []; - - for (let l = 0; l < listingIds.length; l += 1) { - const lid = listingIds[l]!; - // March ordering: alternating/scrambled; April 5 Q2: strictly ascending; April 18 restated: strictly descending - const marVal = 200 + ((l * 3) % listingIds.length) * 25; - const aprQ2Val = 100 + l * 40; - const aprRestatedVal = 400 - l * 45; - - if (l < 5) { - pitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: marKnownAt, - periodEnd: '2022-12-31', - fiscalPeriod: 'Q1', - revenue: marVal / 4, - ttmRevenue: marVal, - }) - ); - expectedAllVintagesObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); - brokenMonthEndOnlyObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); - } - - pitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: aprQ2KnownAt, - periodEnd: '2023-03-31', - fiscalPeriod: 'Q2', - revenue: aprQ2Val / 4, - ttmRevenue: aprQ2Val, - }), - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: aprRestatedKnownAt, - periodEnd: '2023-03-31', - fiscalPeriod: 'Q2', - revenue: aprQ2Val / 4, - ttmRevenue: aprRestatedVal, - }) - ); - - expectedAllVintagesObs.push( - { listingId: lid, knownAt: aprQ2KnownAt, value: aprQ2Val }, - { listingId: lid, knownAt: aprRestatedKnownAt, value: aprRestatedVal } - ); - // Month-end-only baseline misses the April 5 vintage completely - brokenMonthEndOnlyObs.push({ listingId: lid, knownAt: aprRestatedKnownAt, value: aprRestatedVal }); - } - - // 1. Direct baseline with all eligible vintages (including April 5 Q2) - const directBuilt = buildForwardReturnPanel({ - bars, - signals: expectedAllVintagesObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const directLedger = createFakeTrialLedger(); - const directStudy = await analyzeSignal(directLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_same_month_baseline', - params: { field: 'ttm_revenue', horizonSessions: 3 }, - universe: listingIds, - horizon: '3d', - }, - panel: directBuilt.panel, - vaultCutoffDate, - }); - expect(directStudy.status).toBe('ok'); - if (directStudy.status !== 'ok') { - return; - } - - // 2. Broken month-end-only counterfactual (omits April 5 Q2) - const brokenBuilt = buildForwardReturnPanel({ - bars, - signals: brokenMonthEndOnlyObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const brokenLedger = createFakeTrialLedger(); - const brokenStudy = await analyzeSignal(brokenLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'broken_month_end_only_counterfactual', - params: { field: 'ttm_revenue', horizonSessions: 3 }, - universe: listingIds, - horizon: '3d', - }, - panel: brokenBuilt.panel, - vaultCutoffDate, - }); - expect(brokenStudy.status).toBe('ok'); - - // 3. MCP handler over multi-month window (March..May) - const mcpStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), - }); - const mcpLedger = createFakeTrialLedger(); - const mcpRes = await callAnalyzeSignal({ - store: mcpStore.store, - ledger: mcpLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: allDates[0]!, - to: allDates[allDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(mcpRes.isError).toBe(false); - const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; - expect(mcpPayload.status).toBe('ok'); - if (mcpPayload.status !== 'ok') { - return; - } - - // Exact parity with the full-vintage direct baseline across all dates (including April 5..17) - expect(mcpPayload.analysis.rankIc).toEqual(directStudy.analysis.rankIc); - expect(mcpPayload.analysis.pearsonIc).toEqual(directStudy.analysis.pearsonIc); - expect(mcpLedger.rows[0]?.daily_series).toEqual(directLedger.rows[0]?.daily_series); - - // Specifically verify April 5..17 dated points match direct baseline and differ from month-end-only - const aprilPreAmendmentDates = mcpPayload.analysis.ledgerSeries.points - .filter(p => p.date >= '2023-04-05' && p.date <= '2023-04-17') - .map(p => p.date); - expect(aprilPreAmendmentDates.length).toBeGreaterThan(0); - expect(aprilPreAmendmentDates[0]).toBe('2023-04-05'); - expect(aprilPreAmendmentDates[aprilPreAmendmentDates.length - 1]).toBe('2023-04-17'); - - const mcpByDate = new Map(mcpPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value])); - const brokenByDate = new Map( - brokenStudy.analysis.dates.map((d, idx) => [d, brokenStudy.analysis.rankIcSeries[idx]!]) - ); - let aprilDiffCount = 0; - for (const d of aprilPreAmendmentDates) { - if (mcpByDate.get(d) !== brokenByDate.get(d)) { - aprilDiffCount += 1; - } - } - expect(aprilDiffCount).toBeGreaterThan(0); - - // Every fundamentalsAsOf call (month-end + backfill) stays strictly below Vault cutoff and forwards allowEstimatedLag - for (const call of mcpStore.fundamentalsCalls) { - expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); - expect(call.allowEstimatedLag).toBe(false); - } - - // 4. Single-month window starting in April (2023-04-03..2023-04-28): - // must retain March prior (for Apr 3..4), April 5 Q2 (for Apr 5..17), and April 18 restatement (Apr 18..28). - const aprilOnlyBars = bars.filter(b => b.ts >= makeUtcMs('2023-04-03', 0) && b.ts <= makeUtcMs('2023-04-28', 23)); - const aprilDirectBuilt = buildForwardReturnPanel({ - bars: aprilOnlyBars, - signals: expectedAllVintagesObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const aprilDirectLedger = createFakeTrialLedger(); - const aprilDirectStudy = await analyzeSignal(aprilDirectLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_april_only_baseline', - params: { field: 'ttm_revenue', horizonSessions: 3 }, - universe: listingIds, - horizon: '3d', - }, - panel: aprilDirectBuilt.panel, - vaultCutoffDate, - }); - expect(aprilDirectStudy.status).toBe('ok'); - - const aprilMcpStore = createFakeStore({ - bars: aprilOnlyBars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), - }); - const aprilMcpLedger = createFakeTrialLedger(); - const aprilMcpRes = await callAnalyzeSignal({ - store: aprilMcpStore.store, - ledger: aprilMcpLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: '2023-04-03', - to: '2023-04-28', - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(aprilMcpRes.isError).toBe(false); - const aprilMcpPayload = JSON.parse(aprilMcpRes.text) as AnalyzeSignalResultPayload; - expect(aprilMcpPayload.status).toBe('ok'); - if (aprilMcpPayload.status === 'ok' && aprilDirectStudy.status === 'ok') { - expect(aprilMcpPayload.analysis.rankIc).toEqual(aprilDirectStudy.analysis.rankIc); - expect(aprilMcpLedger.rows[0]?.daily_series).toEqual(aprilDirectLedger.rows[0]?.daily_series); - expect(aprilMcpPayload.trial.sampleStart).toBe('2023-04-03'); - } - }); - - test('estimated-lag omission backfill recovers earlier verified intra-month vintages when allowEstimatedLag is false', async () => { - // Regression fixture for DuckDB estimated-lag omission under allowEstimatedLag: false: - // - Dataset ID: `synthetic:mcp-analyze-signal-estimated-lag-omission:seed-20261205:v1` - // - 6 listings across 2023-03-01..2023-05-12 (53 sessions), Vault cutoff 2023-05-15T00:00:00Z - // - March 10: verified Q1 release (listings 0..4 only; listing 5 has no March prior) - // - April 5: verified Q2 release (`has_estimated_lag: false`) for all 6 listings - // - April 18: estimated-lag update (`has_estimated_lag: true`) for all 6 listings, so - // DuckDB's `fundamentalsAsOf(..., allowEstimatedLag: false)` omits listings 1..5 - // at April month-end and omits listing 0 at intermediate backfill probes. - // - April 25: verified update (`has_estimated_lag: false`) for listing 0 only (exercises - // sandwiched omission during backfill after a later verified release). - const listingIds = [82_001, 82_002, 82_003, 82_004, 82_005, 82_006]; - const allDates = makeBusinessDates('2023-03-01', 53); - const vaultCutoffDate = '2023-05-15'; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - - const marKnownAt = makeUtcMs('2023-03-10', 13); - const aprVerifiedKnownAt = makeUtcMs('2023-04-05', 13); - const aprEstimatedLagKnownAt = makeUtcMs('2023-04-18', 13); - const aprLateVerifiedKnownAt = makeUtcMs('2023-04-25', 13); - - const rand = createSeededRng(20261205); - const bars: BarRecord[] = []; - const prices = new Float64Array(listingIds.length).fill(45); - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); - for (let l = 0; l < listingIds.length; l += 1) { - const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; - prices[l] = Math.max(1, prices[l]! * (1 + ret)); - const close = Number(prices[l]!.toFixed(6)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 30_000, - vwap: close, - knownAt: closeTs, - }); - } - } - - const pitRows: FundamentalsPitFixtureRow[] = []; - const expectedVerifiedObs: SignalObservation[] = []; - const expectedAllowLagObs: SignalObservation[] = []; - const brokenOmittedAprilObs: SignalObservation[] = []; - - for (let l = 0; l < listingIds.length; l += 1) { - const lid = listingIds[l]!; - const marVal = 200 + ((l * 3) % listingIds.length) * 25; - const aprVerifiedVal = 100 + l * 40; - const aprEstimatedVal = 400 - l * 45; - const aprLateVerifiedVal = 150; - - if (l < 5) { - pitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: marKnownAt, - periodEnd: '2022-12-31', - fiscalPeriod: 'Q1', - revenue: marVal / 4, - ttmRevenue: marVal, - hasEstimatedLag: false, - }) - ); - expectedVerifiedObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); - expectedAllowLagObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); - brokenOmittedAprilObs.push({ listingId: lid, knownAt: marKnownAt, value: marVal }); - } - - pitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: aprVerifiedKnownAt, - periodEnd: '2023-03-31', - fiscalPeriod: 'Q2', - revenue: aprVerifiedVal / 4, - ttmRevenue: aprVerifiedVal, - hasEstimatedLag: false, - }), - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: aprEstimatedLagKnownAt, - periodEnd: '2023-03-31', - fiscalPeriod: 'Q2', - revenue: aprEstimatedVal / 4, - ttmRevenue: aprEstimatedVal, - hasEstimatedLag: true, - }) - ); - - expectedVerifiedObs.push({ - listingId: lid, - knownAt: aprVerifiedKnownAt, - value: aprVerifiedVal, - }); - expectedAllowLagObs.push( - { listingId: lid, knownAt: aprVerifiedKnownAt, value: aprVerifiedVal }, - { listingId: lid, knownAt: aprEstimatedLagKnownAt, value: aprEstimatedVal } - ); - - if (l === 0) { - pitRows.push( - makeFundamentalsRow({ - listingId: lid, - effectiveKnownAt: aprLateVerifiedKnownAt, - periodEnd: '2023-03-31', - fiscalPeriod: 'Q2', - revenue: aprLateVerifiedVal / 4, - ttmRevenue: aprLateVerifiedVal, - hasEstimatedLag: false, - }) - ); - expectedVerifiedObs.push({ - listingId: lid, - knownAt: aprLateVerifiedKnownAt, - value: aprLateVerifiedVal, - }); - expectedAllowLagObs.push({ - listingId: lid, - knownAt: aprLateVerifiedKnownAt, - value: aprLateVerifiedVal, - }); - brokenOmittedAprilObs.push({ - listingId: lid, - knownAt: aprLateVerifiedKnownAt, - value: aprLateVerifiedVal, - }); - } - } - - // 1. Direct verified-only baseline (includes April 5 verified release; excludes April 18 estimated lag) - const directVerifiedBuilt = buildForwardReturnPanel({ - bars, - signals: expectedVerifiedObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const directVerifiedLedger = createFakeTrialLedger(); - const directVerifiedStudy = await analyzeSignal(directVerifiedLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_estimated_lag_omission_verified_baseline', - params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, - universe: listingIds, - horizon: '3d', - }, - panel: directVerifiedBuilt.panel, - vaultCutoffDate, - }); - expect(directVerifiedStudy.status).toBe('ok'); - if (directVerifiedStudy.status !== 'ok') { - return; - } - - // 2. Broken counterfactual without omission backfill (loses April 5 for all omitted listings) - const brokenBuilt = buildForwardReturnPanel({ - bars, - signals: brokenOmittedAprilObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const brokenLedger = createFakeTrialLedger(); - const brokenStudy = await analyzeSignal(brokenLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'broken_estimated_lag_omission_counterfactual', - params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, - universe: listingIds, - horizon: '3d', - }, - panel: brokenBuilt.panel, - vaultCutoffDate, - }); - expect(brokenStudy.status).toBe('ok'); - - // 3. MCP handler with allowEstimatedLag: false (default) over March..May - const mcpStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), - }); - const mcpLedger = createFakeTrialLedger(); - const mcpRes = await callAnalyzeSignal({ - store: mcpStore.store, - ledger: mcpLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: allDates[0]!, - to: allDates[allDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(mcpRes.isError).toBe(false); - const mcpPayload = JSON.parse(mcpRes.text) as AnalyzeSignalResultPayload; - expect(mcpPayload.status).toBe('ok'); - if (mcpPayload.status !== 'ok') { - return; - } - - // Exact parity with the verified-only direct baseline across all dates (including April 5..17) - expect(mcpPayload.analysis.rankIc).toEqual(directVerifiedStudy.analysis.rankIc); - expect(mcpPayload.analysis.pearsonIc).toEqual(directVerifiedStudy.analysis.pearsonIc); - expect(mcpLedger.rows[0]?.daily_series).toEqual(directVerifiedLedger.rows[0]?.daily_series); - - const aprilPreEstimatedDates = mcpPayload.analysis.ledgerSeries.points - .filter(p => p.date >= '2023-04-05' && p.date <= '2023-04-17') - .map(p => p.date); - expect(aprilPreEstimatedDates[0]).toBe('2023-04-05'); - expect(aprilPreEstimatedDates[aprilPreEstimatedDates.length - 1]).toBe('2023-04-17'); - - const mcpByDate = new Map(mcpPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value])); - const brokenByDate = new Map( - brokenStudy.analysis.dates.map((d, idx) => [d, brokenStudy.analysis.rankIcSeries[idx]!]) - ); - let aprilDiffCount = 0; - for (const d of aprilPreEstimatedDates) { - if (mcpByDate.get(d) !== brokenByDate.get(d)) { - aprilDiffCount += 1; - } - } - expect(aprilDiffCount).toBeGreaterThan(0); - - // Every fundamentalsAsOf call stays strictly below Vault cutoff and forwards allowEstimatedLag: false - for (const call of mcpStore.fundamentalsCalls) { - expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); - expect(call.allowEstimatedLag).toBe(false); - } - - // 4. Single-month April-only window (2023-04-03..2023-04-28) with allowEstimatedLag: false - const aprilOnlyBars = bars.filter( - b => b.ts >= makeUtcMs('2023-04-03', 0) && b.ts <= makeUtcMs('2023-04-28', 23) - ); - const aprilDirectBuilt = buildForwardReturnPanel({ - bars: aprilOnlyBars, - signals: expectedVerifiedObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const aprilDirectLedger = createFakeTrialLedger(); - const aprilDirectStudy = await analyzeSignal(aprilDirectLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_estimated_lag_april_only_baseline', - params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: false }, - universe: listingIds, - horizon: '3d', - }, - panel: aprilDirectBuilt.panel, - vaultCutoffDate, - }); - expect(aprilDirectStudy.status).toBe('ok'); - - const aprilMcpStore = createFakeStore({ - bars: aprilOnlyBars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), - }); - const aprilMcpLedger = createFakeTrialLedger(); - const aprilMcpRes = await callAnalyzeSignal({ - store: aprilMcpStore.store, - ledger: aprilMcpLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: '2023-04-03', - to: '2023-04-28', - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(aprilMcpRes.isError).toBe(false); - const aprilMcpPayload = JSON.parse(aprilMcpRes.text) as AnalyzeSignalResultPayload; - expect(aprilMcpPayload.status).toBe('ok'); - if (aprilMcpPayload.status === 'ok' && aprilDirectStudy.status === 'ok') { - expect(aprilMcpPayload.analysis.rankIc).toEqual(aprilDirectStudy.analysis.rankIc); - expect(aprilMcpLedger.rows[0]?.daily_series).toEqual(aprilDirectLedger.rows[0]?.daily_series); - } - - // 5. With allowEstimatedLag: true, April 18 estimated-lag update is included alongside April 5 - const allowLagDirectBuilt = buildForwardReturnPanel({ - bars, - signals: expectedAllowLagObs, - horizonSessions: 3, - vaultCutoffDate, - }); - const allowLagDirectLedger = createFakeTrialLedger(); - const allowLagDirectStudy = await analyzeSignal(allowLagDirectLedger.executor, { - principalId: AGENT_PRINCIPAL, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'direct_estimated_lag_allowed_baseline', - params: { field: 'ttm_revenue', horizonSessions: 3, allowEstimatedLag: true }, - universe: listingIds, - horizon: '3d', - }, - panel: allowLagDirectBuilt.panel, - vaultCutoffDate, - }); - expect(allowLagDirectStudy.status).toBe('ok'); - - const allowLagStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(pitRows, q), - }); - const allowLagLedger = createFakeTrialLedger(); - const allowLagRes = await callAnalyzeSignal({ - store: allowLagStore.store, - ledger: allowLagLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: allDates[0]!, - to: allDates[allDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(allowLagRes.isError).toBe(false); - const allowLagPayload = JSON.parse(allowLagRes.text) as AnalyzeSignalResultPayload; - expect(allowLagPayload.status).toBe('ok'); - if (allowLagPayload.status === 'ok' && allowLagDirectStudy.status === 'ok') { - expect(allowLagPayload.analysis.rankIc).toEqual(allowLagDirectStudy.analysis.rankIc); - expect(allowLagLedger.rows[0]?.daily_series).toEqual( - allowLagDirectLedger.rows[0]?.daily_series - ); - expect(allowLagLedger.rows[0]?.daily_series).not.toEqual(mcpLedger.rows[0]?.daily_series); - } - expect(allowLagStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true); - - // 6. Stale March null row for an omitted listing must not suppress April omission backfill; - // exact payload and ledger rows must match the clean run. - const staleNullKnownAt = makeUtcMs('2023-03-20', 13); - const staleNullStore = createFakeStore({ - bars, - fundamentalsResolver: q => { - const cleanTable = queryFundamentalsFixtureRows(pitRows, q); - const returnedIds = new Set(cleanTable.rows.map(r => r.listing_id)); - const injected: TableRow[] = []; - for (const omittedTarget of [listingIds[1]!, listingIds[5]!]) { - if (q.listingIds.includes(omittedTarget) && !returnedIds.has(omittedTarget)) { - injected.push({ - listing_id: omittedTarget, - effective_known_at: staleNullKnownAt, - known_at_source: 'sec_edgar_filing', - has_estimated_lag: false, - period_end: '2022-12-31', - fiscal_period: 'Q1', - currency: 'USD', - period_known_at: staleNullKnownAt, - ttm_revenue: null, - ttm_period_end: null, - ttm_currency: null, - ttm_has_estimated_lag: false, - }); - } - } - return { - columns: cleanTable.columns, - rows: [...cleanTable.rows, ...injected], - }; - }, - }); - const staleNullLedger = createFakeTrialLedger(); - const staleNullRes = await callAnalyzeSignal({ - store: staleNullStore.store, - ledger: staleNullLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: allDates[0]!, - to: allDates[allDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(staleNullRes.isError).toBe(false); - expect(staleNullRes.text).toBe(mcpRes.text); - expect(staleNullLedger.rows).toEqual(mcpLedger.rows); - for (const call of staleNullStore.fundamentalsCalls) { - expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); - expect(call.allowEstimatedLag).toBe(false); - } - - // 7. Genuinely null latest field with allowEstimatedLag: true must still probe earlier - // eligible closes and recover the valid April 5 release. - const nullLatestPitRows: FundamentalsPitFixtureRow[] = pitRows.map(row => - row.effective_known_at === aprEstimatedLagKnownAt ? { ...row, ttm_revenue: null } : row - ); - const nullLatestAllowLagStore = createFakeStore({ - bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(nullLatestPitRows, q), - }); - const nullLatestAllowLagLedger = createFakeTrialLedger(); - const nullLatestAllowLagRes = await callAnalyzeSignal({ - store: nullLatestAllowLagStore.store, - ledger: nullLatestAllowLagLedger.executor, - vaultCutoffTs, - args: { - listingIds, - from: allDates[0]!, - to: allDates[allDates.length - 1]!, - signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true }, - horizonSessions: 3, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }); - expect(nullLatestAllowLagRes.isError).toBe(false); - const nullLatestAllowLagPayload = JSON.parse( - nullLatestAllowLagRes.text - ) as AnalyzeSignalResultPayload; - expect(nullLatestAllowLagPayload.status).toBe('ok'); - if (nullLatestAllowLagPayload.status === 'ok') { - expect(nullLatestAllowLagPayload.analysis.rankIc).toEqual( - directVerifiedStudy.analysis.rankIc - ); - expect(nullLatestAllowLagPayload.analysis.pearsonIc).toEqual( - directVerifiedStudy.analysis.pearsonIc - ); - expect(nullLatestAllowLagLedger.rows[0]?.daily_series).toEqual( - directVerifiedLedger.rows[0]?.daily_series - ); - const recoveredByDate = new Map( - nullLatestAllowLagPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value]) - ); - let recoveredAprilDiffCount = 0; - for (const d of aprilPreEstimatedDates) { - if (recoveredByDate.get(d) !== brokenByDate.get(d)) { - recoveredAprilDiffCount += 1; - } - } - expect(recoveredAprilDiffCount).toBeGreaterThan(0); - } - expect(nullLatestAllowLagStore.fundamentalsCalls.length).toBeGreaterThan(0); - for (const call of nullLatestAllowLagStore.fundamentalsCalls) { - expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs); - expect(call.allowEstimatedLag).toBe(true); - } - }); - - test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => { - const fixture = buildFundamentalsStudyFixture(); - const from = fixture.allDates[0]!; - const postCutoffDate = fixture.allDates[fixture.allDates.length - 1]!; - - const cleanStore = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: q => queryFundamentalsFixtureRows(fixture.fundamentalsRows, q), - }); - const leakyStore = createFakeStore({ - bars: fixture.bars, - leaky: true, - fundamentalsResolver: q => { - const cleanTable = queryFundamentalsFixtureRows(fixture.fundamentalsRows, q); - const snapAsOfMs = Date.parse(q.asOf); - const poisonedRows: TableRow[] = [ - // 1. effective_known_at strictly after individual snapshot asOf (but before vaultCutoffTs) - { - listing_id: fixture.listingIds[0]!, - effective_known_at: snapAsOfMs + 60_000, - ttm_revenue: 999_999, - }, - // 2. effective_known_at at exact vaultCutoffTs - { - listing_id: fixture.listingIds[1]!, - effective_known_at: fixture.vaultCutoffTs, - ttm_revenue: 888_888, - }, - // 3. effective_known_at after vaultCutoffTs - { - listing_id: fixture.listingIds[2]!, - effective_known_at: fixture.vaultCutoffTs + 86_400_000, - ttm_revenue: 777_777, - }, - // 4. unrequested listing_id - { - listing_id: 999_999, - effective_known_at: makeUtcMs(from, 12), - ttm_revenue: 666_666, - }, - // 5. non-safe-integer effective_known_at (float & NaN) - { - listing_id: fixture.listingIds[3]!, - effective_known_at: makeUtcMs(from, 12) + 0.5, - ttm_revenue: 555_555, - }, - { - listing_id: fixture.listingIds[3]!, - effective_known_at: Number.NaN, - ttm_revenue: 555_555, - }, - // 6. null, NaN, and Infinity field values - { - listing_id: fixture.listingIds[4]!, - effective_known_at: makeUtcMs(from, 12), - ttm_revenue: null, - }, - { - listing_id: fixture.listingIds[4]!, - effective_known_at: makeUtcMs(from, 12) + 1_000, - ttm_revenue: Number.NaN, - }, - { - listing_id: fixture.listingIds[4]!, - effective_known_at: makeUtcMs(from, 12) + 2_000, - ttm_revenue: Number.POSITIVE_INFINITY, - }, - ]; - return { - columns: cleanTable.columns, - rows: [...cleanTable.rows, ...poisonedRows], - }; - }, - }); - - const cleanLedger = createFakeTrialLedger(); - const leakyLedger = createFakeTrialLedger(); - const args = { - listingIds: fixture.listingIds, - from, - to: postCutoffDate, - asOf: postCutoffDate, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - const cleanRes = await callAnalyzeSignal({ - store: cleanStore.store, - ledger: cleanLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args, - }); - const leakyRes = await callAnalyzeSignal({ - store: leakyStore.store, - ledger: leakyLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args, - }); - - expect(cleanRes.isError).toBe(false); - expect(leakyRes.isError).toBe(false); - expect(leakyRes.text).toBe(cleanRes.text); - expect(leakyLedger.rows).toEqual(cleanLedger.rows); - - // Every fundamentalsAsOf call's asOf is strictly before vaultCutoffTs - expect(cleanStore.fundamentalsCalls.length).toBeGreaterThan(0); - for (const call of [...cleanStore.fundamentalsCalls, ...leakyStore.fundamentalsCalls]) { - expect(Date.parse(call.asOf)).toBeLessThan(fixture.vaultCutoffTs); - } - - // Malformed fundamentals table -> sanitized SignalPanelError with zero ledger writes - const badTableStore = createFakeStore({ - bars: fixture.bars, - fundamentalsResolver: () => ({ columns: null, rows: null } as unknown as Table), - }); - const badTableLedger = createFakeTrialLedger(); - const badTableRes = await callAnalyzeSignal({ - store: badTableStore.store, - ledger: badTableLedger.executor, - vaultCutoffTs: fixture.vaultCutoffTs, - args, - }); - expect(badTableRes.isError).toBe(true); - expect(badTableRes.text).toBe('SignalPanelError: Invalid signal panel input.'); - expect(badTableLedger.rows).toHaveLength(0); - }); -}); diff --git a/libs/research/test/mcp-copilot-server-qa.test.ts b/libs/research/test/mcp-copilot-server-qa.test.ts deleted file mode 100644 index 893c62ec..00000000 --- a/libs/research/test/mcp-copilot-server-qa.test.ts +++ /dev/null @@ -1,740 +0,0 @@ -import { describe, expect, spyOn, test } from 'bun:test'; -import type { EventStudyExchangeCalendars } from '../src/event-panel'; -import type { - BarBatch, - BarRecord, - BarsQuery, - EventsQuery, - MarketDataStore, - ShortsAsOfQuery, - Table, - TableRow, -} from '../src/market-data-store'; -import { EVENTS_COLUMNS, MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; -import { - type AnalyzeSignalResultPayload, - type EventStudyResultPayload, - type FileFindingResultPayload, - type FiledFindingRecord, - type FindingWritePort, - type KnowledgePort, - type McpServer, - RESEARCH_COPILOT_TOOL_NAMES, - type ReadKnowledgeResultPayload, - type ResearchCopilotMcpServerOptions, - type SearchSymbolsResultPayload, - type StdioOutput, - areFiledFindingPayloadsEqual, - createResearchCopilotMcpServer, - runStdioServer, -} from '../src/mcp/index'; -import * as analyzeSignalToolModule from '../src/mcp/tools/analyze-signal'; -import * as queryDataToolModule from '../src/mcp/tools/query-data'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; - -// QA fixture for T-144 (composed research copilot MCP server), pinned for reproducibility: -// - Dataset ID: `synthetic:mcp-copilot-qa:seed-424242:v1` (Mulberry32 seed 424242) -// - Universe: 12 synthetic XNYS listings (`60001..60012`), daily bars at 21:00 UTC -// - Sessions: 60 pre-cutoff + 6 post-cutoff weekdays starting 2023-01-02; -// vault cutoff = 00:00 UTC on session index 60 -// - Shorts reported every 5 sessions (indices 0,5,...), known_at = 22:00 UTC on report+3, -// so the first actionable signal session is index 4 (first close strictly after known_at) -// - Study assumptions: raw close-to-close returns, zero modeled costs, 5-session horizon, -// event_study equal-weight benchmark on 8-K filings -const FIXTURE_DATASET_ID = 'synthetic:mcp-copilot-qa:seed-424242:v1'; -const SEED = 424242; -const LISTING_COUNT = 12; -const PRE_CUTOFF_SESSIONS = 60; -const POST_CUTOFF_SESSIONS = 6; -const HORIZON = 5; -const AGENT_PRINCIPAL = 'agent:aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; -const FIXED_NOW_MS = Date.parse('2024-07-01T09:00:00.000Z'); - -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): number { - return Date.parse(`${date}T${String(hour).padStart(2, '0')}:00:00.000Z`); -} - -/** Parses store bound strings (date-only, ms or µs ISO) to epoch ms, truncating sub-ms digits. */ -function boundMs(raw: string, endOfDay: boolean): number { - if (raw.length === 10) { - return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); - } - const m = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?Z$/.exec(raw); - if (m === null) { - throw new Error(`Unparseable bound: ${raw}`); - } - const frac = (m[2] ?? '').padEnd(3, '0').slice(0, 3); - return Date.parse(`${m[1]}.${frac}Z`); -} - -interface Fixture { - readonly listingIds: readonly number[]; - readonly dates: readonly string[]; - readonly cutoffDate: string; - readonly cutoffTs: number; - readonly lastPreDate: string; - readonly lastDate: string; - readonly bars: readonly BarRecord[]; - readonly shorts: Table; - readonly events: Table; - readonly calendars: EventStudyExchangeCalendars; -} - -function buildFixture(): Fixture { - const rand = createSeededRng(SEED); - const dates = makeBusinessDates('2023-01-02', PRE_CUTOFF_SESSIONS + POST_CUTOFF_SESSIONS); - const listingIds = Array.from({ length: LISTING_COUNT }, (_, i) => 60_001 + i); - const cutoffDate = dates[PRE_CUTOFF_SESSIONS]!; - const bars: BarRecord[] = []; - const shortsRows: TableRow[] = []; - const eventRows: TableRow[] = []; - - const eventDays = [10, 18, 26, 34, 42, 50, 62]; - const eventKey = new Set(); - eventDays.forEach((t, e) => { - const ts = utcMs(dates[t]!, 14); - for (let k = 0; k < 2; k += 1) { - const l = (e * 2 + k) % LISTING_COUNT; - eventKey.add(`${t}:${l}`); - eventRows.push({ - listing_id: listingIds[l]!, - ts, - known_at: ts, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }); - } - }); - - const prices = listingIds.map((_, l) => 20 + l * 3); - for (let t = 0; t < dates.length; t += 1) { - const date = dates[t]!; - if (t % 5 === 0 && t + 3 < dates.length) { - for (let l = 0; l < LISTING_COUNT; l += 1) { - shortsRows.push({ - listing_id: listingIds[l]!, - report_date: date, - known_at: utcMs(dates[t + 3]!, 22), - shares_short: 200_000 + l * 1_000 + Math.round(rand() * 5_000), - net_change: Math.round((rand() * 2 - 1) * 15_000), - pct_float: Number((0.01 + rand() * 0.05).toFixed(4)), - source: 'ceoShorts', - }); - } - } - const closeTs = utcMs(date, 21); - for (let l = 0; l < LISTING_COUNT; l += 1) { - const drift = eventKey.has(`${t}:${l}`) || eventKey.has(`${t - 1}:${l}`) ? 0.008 : 0; - prices[l] = Math.max(1, prices[l]! * (1 + drift + (rand() * 2 - 1) * 0.01)); - const close = Number(prices[l]!.toFixed(4)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 10_000 + t, - vwap: close, - knownAt: closeTs, - }); - } - } - - return { - listingIds, - dates, - cutoffDate, - cutoffTs: utcMs(cutoffDate, 0), - lastPreDate: dates[PRE_CUTOFF_SESSIONS - 1]!, - lastDate: dates[dates.length - 1]!, - bars, - shorts: { - columns: [ - 'listing_id', - 'report_date', - 'known_at', - 'shares_short', - 'net_change', - 'pct_float', - 'source', - ], - rows: shortsRows, - }, - events: { columns: [...EVENTS_COLUMNS], rows: eventRows }, - calendars: { - calendars: { XNYS: dates.map(date => ({ date, closeTs: utcMs(date, 21) })) }, - listingCalendarId: new Map(listingIds.map(id => [id, 'XNYS'])), - }, - }; -} - -interface RecordingStore { - readonly store: MarketDataStore; - readonly barsQueries: BarsQuery[]; - readonly shortsQueries: ShortsAsOfQuery[]; - readonly eventsQueries: EventsQuery[]; -} - -/** Honest in-memory store that records every query it receives. */ -function createRecordingStore(fx: Fixture): RecordingStore { - const barsQueries: BarsQuery[] = []; - const shortsQueries: ShortsAsOfQuery[] = []; - const eventsQueries: EventsQuery[] = []; - const store: MarketDataStore = { - bars(q): AsyncIterable { - barsQueries.push(q); - const ids = new Set(q.listingIds); - const from = boundMs(q.from, false); - const to = boundMs(q.to, true); - const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - const rows = fx.bars.filter( - r => ids.has(r.listingId) && r.ts >= from && r.ts <= to && r.knownAt <= asOf - ); - return { - async *[Symbol.asyncIterator]() { - yield { rows }; - }, - }; - }, - async universe() { - return [...fx.listingIds]; - }, - async shortsAsOf(q) { - shortsQueries.push(q); - const ids = new Set(q.listingIds); - const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - const from = q.from.slice(0, 10); - const to = q.to.slice(0, 10); - return { - columns: fx.shorts.columns, - rows: fx.shorts.rows.filter( - r => - ids.has(r.listing_id as number) && - (r.report_date as string) >= from && - (r.report_date as string) <= to && - (r.known_at as number) <= asOf - ), - }; - }, - async events(q) { - eventsQueries.push(q); - const ids = q.listingIds !== undefined ? new Set(q.listingIds) : null; - const from = boundMs(q.from, false); - const to = boundMs(q.to, true); - const asOf = q.asOf !== undefined ? boundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - return { - columns: fx.events.columns, - rows: fx.events.rows.filter( - r => - (ids === null || ids.has(r.listing_id as number)) && - q.kinds.includes(r.kind as never) && - (r.ts as number) >= from && - (r.ts as number) <= to && - (r.known_at as number) <= asOf - ), - }; - }, - async crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - async fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - async macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - async fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - return { store, barsQueries, shortsQueries, eventsQueries }; -} - -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(): { readonly executor: TrialLedgerExecutor; readonly rows: LedgerRow[] } { - const rows: LedgerRow[] = []; - const executor: TrialLedgerExecutor = { - async query>(text: string, params?: readonly unknown[]) { - const p = params ?? []; - if (text.trimStart().startsWith('INSERT INTO trial_ledger')) { - const id = rows.length + 1; - const row: LedgerRow = { - trial_id: String(id), - created_at: new Date(Date.UTC(2024, 6, 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 (text.includes('WHERE trial_id = $1::bigint')) { - const m = rows.filter(r => r.trial_id === String(p[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 === p[0] && r.horizon_bucket === p[1]); - return { rows: m as unknown as Row[], rowCount: m.length }; - } - return { rows: [], rowCount: 0 }; - }, - }; - return { executor, rows }; -} - -interface Harness { - readonly options: ResearchCopilotMcpServerOptions; - readonly store: RecordingStore; - readonly ledger: ReturnType; - readonly stored: FiledFindingRecord[]; - readonly appendCalls: () => number; -} - -function buildHarness(fx: Fixture): Harness { - const store = createRecordingStore(fx); - const ledger = createLedger(); - const stored: FiledFindingRecord[] = []; - const byKey = new Map(); - let appends = 0; - let nextFinding = 1; - - const writePort: FindingWritePort = { - async appendFinding(record, key) { - appends += 1; - if (key !== undefined) { - const prior = byKey.get(key); - if (prior !== undefined) { - return areFiledFindingPayloadsEqual(prior, record) - ? { status: 'replayed', id: prior.id, createdAt: prior.createdAt } - : { status: 'conflict' }; - } - } - const copy = { ...record, trialRefs: [...record.trialRefs], evidenceRefs: [...record.evidenceRefs] }; - stored.push(copy); - if (key !== undefined) { - byKey.set(key, copy); - } - return { status: 'created', id: copy.id, createdAt: copy.createdAt }; - }, - }; - - const knowledge: KnowledgePort = { - async listLibraryCards() { - return []; - }, - async listFindings() { - return stored; - }, - async listProviderCaveats() { - return []; - }, - }; - - const options: ResearchCopilotMcpServerOptions = { - name: 'copilot-qa', - version: '0.0.1', - store: store.store, - vaultContext: { vaultCutoffTs: fx.cutoffTs }, - ledger: ledger.executor, - principalId: AGENT_PRINCIPAL, - searchSymbols: { - port: { - async searchSymbols() { - return fx.listingIds.map((listingId, i) => ({ - listingId, - instrumentId: 90_000 + i, - ticker: i === 0 ? 'QAQA' : `QA${i}`, - classSuffix: null, - name: `QA Equity ${i}`, - mic: 'XNYS', - currency: 'USD', - isin: null, - firstBarDate: fx.dates[0]!, - lastBarDate: fx.lastDate, - delistedAt: null, - })); - }, - }, - }, - eventStudy: { resolveExchangeCalendars: () => fx.calendars }, - fileFinding: { - port: writePort, - trialLookup: { - hasResearchVisibleTrial: ref => - ledger.rows.some(r => r.trial_id === ref && r.sample_end < fx.cutoffDate), - }, - newId: () => `finding-qa-${nextFinding++}`, - now: () => FIXED_NOW_MS, - }, - readKnowledge: { port: knowledge }, - }; - - return { options, store, ledger, stored, appendCalls: () => appends }; -} - -interface ToolEnvelope { - readonly content: readonly { readonly text: string }[]; - readonly isError?: boolean; -} - -async function callTool( - server: McpServer, - name: string, - args: Record -): Promise { - const raw = await server.handleMessage( - JSON.stringify({ jsonrpc: '2.0', id: name, method: 'tools/call', params: { name, arguments: args } }) - ); - const parsed = JSON.parse(raw!) as { result?: ToolEnvelope; error?: unknown }; - expect(parsed.error).toBeUndefined(); - return parsed.result!; -} - -function okJson(env: ToolEnvelope): T { - expect(env.isError).not.toBe(true); - return JSON.parse(env.content[0]!.text) as T; -} - -function signalArgs(fx: Fixture, overrides: Record = {}): Record { - return { - listingIds: [...fx.listingIds], - from: fx.dates[0]!, - to: fx.lastPreDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: HORIZON, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - adjustment: 'raw', - ...overrides, - }; -} - -function eventArgs(fx: Fixture, overrides: Record = {}): Record { - return { - listingIds: [...fx.listingIds], - from: fx.dates[0]!, - to: fx.lastPreDate, - event: { kinds: ['filing'], subtypes: ['8-K'] }, - preDays: 2, - postDays: 5, - benchmark: 'equal_weight', - adjustment: 'raw', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - ...overrides, - }; -} - -describe('createResearchCopilotMcpServer QA', () => { - test('straddling query_data, analyze_signal and event_study send only clamped pre-cutoff bounds to the store', async () => { - const fx = buildFixture(); - const h = buildHarness(fx); - const server = createResearchCopilotMcpServer(h.options); - - await callTool(server, 'query_data', { - listingIds: [fx.listingIds[0]!], - from: fx.dates[0]!, - to: fx.lastDate, - asOf: fx.lastDate, - timeframe: '1d', - adjustment: 'raw', - }); - const sig = okJson( - await callTool(server, 'analyze_signal', signalArgs(fx, { to: fx.lastDate, asOf: fx.lastDate })) - ); - const ev = okJson( - await callTool(server, 'event_study', eventArgs(fx, { to: fx.lastDate, asOf: fx.lastDate })) - ); - - expect(sig.status).toBe('ok'); - expect(ev.status).toBe('ok'); - expect(ev.clampedTo).toBe(true); - expect(ev.toMs).toBe(fx.cutoffTs - 1); - - // query_data + analyze_signal + event_study each read bars once. - expect(h.store.barsQueries).toHaveLength(3); - expect(h.store.shortsQueries).toHaveLength(1); - expect(h.store.eventsQueries).toHaveLength(1); - const all: { readonly to: string; readonly asOf?: string }[] = [ - ...h.store.barsQueries, - ...h.store.shortsQueries, - ...h.store.eventsQueries, - ]; - for (const q of all) { - expect(q.to.startsWith(new Date(fx.cutoffTs - 1).toISOString().slice(0, 19))).toBe(true); - expect(boundMs(q.to, true)).toBe(fx.cutoffTs - 1); - expect(q.asOf).toBeDefined(); - expect(boundMs(q.asOf!, true)).toBe(fx.cutoffTs - 1); - } - for (const q of h.store.barsQueries) { - expect(q.scope).toBe('vault_fenced'); - } - // Event-study trial stays pre-cutoff too. - expect(h.ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'event_study']); - for (const row of h.ledger.rows) { - expect(row.sample_end < fx.cutoffDate).toBe(true); - } - }); - - test('analyze_signal trial covers the exact pinned formation window (first actionable session through cutoff minus horizon)', async () => { - const fx = buildFixture(); - const h = buildHarness(fx); - const server = createResearchCopilotMcpServer(h.options); - - const sig = okJson( - await callTool(server, 'analyze_signal', signalArgs(fx, { to: fx.lastDate })) - ); - expect(sig.status).toBe('ok'); - if (sig.status !== 'ok') { - throw new Error('expected ok'); - } - - // First report (index 0) becomes known 22:00 UTC on index 3, after that day's 21:00 close, - // so the first eligible formation session is index 4. The last formation session whose - // 5-session forward endpoint is still pre-cutoff is index 59 - 5 = 54. - const expectedStart = fx.dates[4]!; - const expectedEnd = fx.dates[PRE_CUTOFF_SESSIONS - 1 - HORIZON]!; - expect(fx.dates[PRE_CUTOFF_SESSIONS - 1 - HORIZON + HORIZON]).toBe(fx.lastPreDate); - - expect(h.ledger.rows).toHaveLength(1); - const row = h.ledger.rows[0]!; - expect(row.trial_id).toBe(String(sig.trial.trialId)); - expect(row.principal_id).toBe(AGENT_PRINCIPAL); - expect(row.sample_start).toBe(expectedStart); - expect(row.sample_end).toBe(expectedEnd); - // One daily IC observation per formation session, none dropped. - expect(row.daily_series).toHaveLength(PRE_CUTOFF_SESSIONS - HORIZON - 4); - expect(row.n_obs).toBe(row.daily_series.length); - }); - - test('a replay on fresh servers with the same inputs produces an identical stdio transcript and ledger', async () => { - const fx = buildFixture(); - - async function runSession(): Promise<{ readonly lines: string[]; readonly ledger: LedgerRow[] }> { - const h = buildHarness(fx); - const server = createResearchCopilotMcpServer(h.options); - const lines: string[] = []; - let buf = ''; - const output: StdioOutput = { - write(chunk: string) { - buf += chunk; - let i = buf.indexOf('\n'); - while (i !== -1) { - lines.push(buf.slice(0, i)); - buf = buf.slice(i + 1); - i = buf.indexOf('\n'); - } - return true; - }, - }; - async function* input(): AsyncGenerator { - const calls: [string, Record][] = [ - ['analyze_signal', signalArgs(fx)], - ['event_study', eventArgs(fx)], - ]; - let id = 1; - for (const [name, args] of calls) { - yield `${JSON.stringify({ jsonrpc: '2.0', id: id++, method: 'tools/call', params: { name, arguments: args } })}\n`; - } - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: id++, - method: 'tools/call', - params: { - name: 'file_finding', - arguments: { - kind: 'finding', - title: 'Replay finding', - summary: `Dataset ${FIXTURE_DATASET_ID}, pre-Vault only.`, - trialRefs: ['1'], - evidenceRefs: [FIXTURE_DATASET_ID], - }, - }, - })}\n`; - } - await runStdioServer(server, { input: input(), output }); - return { lines, ledger: h.ledger.rows }; - } - - const a = await runSession(); - const b = await runSession(); - expect(a.lines).toHaveLength(3); - expect(b.lines).toEqual(a.lines); - expect(b.ledger).toEqual(a.ledger); - expect(JSON.parse(a.lines[2]!).result.isError).not.toBe(true); - }); - - test('file_finding through the composed server rejects unknown trial refs, replays idempotent retries, and read_knowledge reads the filed record back', async () => { - const fx = buildFixture(); - const h = buildHarness(fx); - const server = createResearchCopilotMcpServer(h.options); - - const unknown = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'No trial yet', - summary: 'Should be rejected.', - trialRefs: ['999'], - }); - expect(unknown.isError).toBe(true); - expect(h.appendCalls()).toBe(0); - - const sig = okJson(await callTool(server, 'analyze_signal', signalArgs(fx))); - if (sig.status !== 'ok') { - throw new Error('expected ok'); - } - const args = { - kind: 'finding', - title: 'Shorts net_change IC', - summary: `Dataset ${FIXTURE_DATASET_ID}.`, - trialRefs: [String(sig.trial.trialId)], - evidenceRefs: [FIXTURE_DATASET_ID], - idempotencyKey: 'qa-key-1', - }; - const first = okJson(await callTool(server, 'file_finding', args)); - const retry = okJson(await callTool(server, 'file_finding', args)); - expect(first.created).toBe(true); - expect(retry).toEqual({ id: first.id, createdAt: first.createdAt, created: false }); - expect(h.stored).toHaveLength(1); - - const conflict = await callTool(server, 'file_finding', { ...args, title: 'Different title' }); - expect(conflict.isError).toBe(true); - expect(h.stored).toHaveLength(1); - - const read = okJson( - await callTool(server, 'read_knowledge', { source: 'findings', id: first.id }) - ); - expect(read.rowCount).toBe(1); - expect(read.rows[0]?.id).toBe(first.id); - }); - - test('shared vaultContext and store stay authoritative over stray per-tool overrides', async () => { - const fx = buildFixture(); - const h = buildHarness(fx); - const throwingStore = new Proxy( - {}, - { - get() { - throw new Error('per-tool store override must not be used'); - }, - } - ); - const options = { - ...h.options, - // Runtime callers can bypass the Omit/Pick types; the composed server must ignore these. - searchSymbols: { - ...h.options.searchSymbols, - vaultContext: { vaultCutoffTs: utcMs(fx.lastDate, 23) + 86_400_000 }, - }, - eventStudy: { ...h.options.eventStudy, store: throwingStore, vaultContext: { vaultCutoffTs: 8.64e15 } }, - } as unknown as ResearchCopilotMcpServerOptions; - const server = createResearchCopilotMcpServer(options); - - const search = okJson( - await callTool(server, 'search_symbols', { query: 'QAQA', limit: 5 }) - ); - expect(search.rows[0]?.lastBarDate).toBe(fx.cutoffDate); - - const ev = okJson( - await callTool(server, 'event_study', eventArgs(fx, { to: fx.lastDate })) - ); - expect(ev.status).toBe('ok'); - expect(ev.toMs).toBe(fx.cutoffTs - 1); - expect(h.store.eventsQueries).toHaveLength(1); - }); - - test('rejects invalid option objects and out-of-order tool registration', () => { - const fx = buildFixture(); - const h = buildHarness(fx); - - expect(() => createResearchCopilotMcpServer(null as never)).toThrow(/Invalid `options`/); - expect(() => - createResearchCopilotMcpServer({ ...h.options, searchSymbols: null } as never) - ).toThrow(/Invalid `searchSymbols`/); - expect(() => - createResearchCopilotMcpServer({ ...h.options, eventStudy: undefined } as never) - ).toThrow(/Invalid `eventStudy`/); - - const realQuery = queryDataToolModule.createQueryDataTool(h.options); - const realSignal = analyzeSignalToolModule.createAnalyzeSignalTool(h.options); - const qSpy = spyOn(queryDataToolModule, 'createQueryDataTool').mockImplementation(() => realSignal); - const sSpy = spyOn(analyzeSignalToolModule, 'createAnalyzeSignalTool').mockImplementation( - () => realQuery - ); - try { - expect(() => createResearchCopilotMcpServer(h.options)).toThrow( - /index 1: expected "query_data", got "analyze_signal"/ - ); - } finally { - qSpy.mockRestore(); - sSpy.mockRestore(); - } - - // Restored spies: composition succeeds again with the fixed order. - const server = createResearchCopilotMcpServer(h.options); - expect(server.listTools().map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); - }); - - test('is importable through the @stock-bot/research/mcp package subpath', async () => { - const mod = await import('@stock-bot/research/mcp'); - expect(mod.createResearchCopilotMcpServer).toBe(createResearchCopilotMcpServer); - expect(mod.RESEARCH_COPILOT_TOOL_NAMES).toBe(RESEARCH_COPILOT_TOOL_NAMES); - }); -}); diff --git a/libs/research/test/mcp-copilot-server.test.ts b/libs/research/test/mcp-copilot-server.test.ts deleted file mode 100644 index 8bd18a11..00000000 --- a/libs/research/test/mcp-copilot-server.test.ts +++ /dev/null @@ -1,1354 +0,0 @@ -import { describe, expect, spyOn, test } from 'bun:test'; -import type { EventStudyExchangeCalendars } from '../src/event-panel'; -import { - type BarBatch, - type BarRecord, - type EventKind, - type MarketDataStore, - type Table, - type TableRow, -} from '../src/market-data-store'; -import { - EVENTS_COLUMNS, - MarketDataStoreNotImplementedError, -} from '../src/market-data-store-duckdb'; -import { - type AnalyzeSignalResultPayload, - type AppendFindingResult, - type EventStudyResultPayload, - type FileFindingResultPayload, - type FiledFindingRecord, - type FindingWritePort, - JSON_RPC_ERROR_CODES, - type KnowledgePort, - type McpToolDescriptor, - type QueryDataResultPayload, - RESEARCH_COPILOT_TOOL_NAMES, - type ReadKnowledgeResultPayload, - type ResearchCopilotMcpServerOptions, - type SearchSymbolsResultPayload, - type StdioOutput, - type SymbolSearchPort, - type SymbolSearchRow, - areFiledFindingPayloadsEqual, - createResearchCopilotMcpServer, - runStdioServer, -} from '../src/mcp/index'; -import * as queryDataToolModule from '../src/mcp/tools/query-data'; -import * as readKnowledgeToolModule from '../src/mcp/tools/read-knowledge'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; - -// Synthetic headless-study fixture metadata (pinned for reproducibility): -// - Dataset ID: `synthetic:mcp-copilot-e2e:seed-20261201:v1` -// - Seed: `20261201` (Mulberry32 PRNG) -// - Universe: 16 synthetic US equity listings (`50001..50016`, XNYS, USD, 21:00 UTC close) -// - Sessions: 80 pre-cutoff + 8 post-cutoff business sessions starting `2022-11-01` -// - Cutoff: `vaultCutoffDate` = `allDates[80]` (`vaultCutoffTs = Date.UTC(..., 0, 0, 0)`) -// - Economic assumptions: daily raw close-to-close returns, zero modeled execution/transaction -// costs; `event_study` uses `benchmark: 'equal_weight'` over eligible listing returns. -// - Ownership: Quant research role owns the economic specification; `AGENT_PRINCIPAL` owns -// the recorded `trial_ledger` rows. -const FIXTURE_DATASET_ID = 'synthetic:mcp-copilot-e2e:seed-20261201:v1'; -const SEED = 20261201; -const SERVER_NAME = 'stock-bot-research-copilot'; -const SERVER_VERSION = '0.1.0'; -const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const FIXED_FINDING_ID = 'finding-copilot-e2e-001'; -const FIXED_NOW_ISO = '2024-06-01T15:30:00.000Z'; -const FIXED_NOW_MS = Date.parse(FIXED_NOW_ISO); - -const EXPECTED_TOOL_NAMES = [ - 'search_symbols', - 'query_data', - 'analyze_signal', - 'event_study', - 'file_finding', - 'read_knowledge', -] as const; - -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[] = new Array(count); - const current = new Date(`${startDate}T00:00:00.000Z`); - let written = 0; - while (written < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out[written] = current.toISOString().slice(0, 10); - written += 1; - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, 0); -} - -function parseBoundMs(raw: string, endOfDay: boolean): number { - if (raw.length === 10) { - return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); - } - return Date.parse(raw); -} - -interface StoredTrialRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -function createFakeTrialLedger(): { - readonly executor: TrialLedgerExecutor; - readonly rows: StoredTrialRow[]; - readonly getInsertCalls: () => number; - readonly getSelectCalls: () => number; -} { - const rows: StoredTrialRow[] = []; - let nextTrialId = 1; - let insertCalls = 0; - let selectCalls = 0; - - const executor: TrialLedgerExecutor = { - async query>(text: string, params?: readonly unknown[]) { - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - insertCalls += 1; - const p = params ?? []; - const trialId = nextTrialId++; - const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); - const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); - const stored: StoredTrialRow = { - trial_id: String(trialId), - created_at: createdAt, - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: dailySeries, - }; - rows.push(stored); - return { - rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], - rowCount: 1, - }; - } - - if (trimmed.startsWith('SELECT')) { - selectCalls += 1; - if (text.includes('WHERE trial_id = $1::bigint')) { - const targetId = String(params?.[0]); - const matched = rows.filter(r => r.trial_id === targetId); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const market = params?.[0] as string; - const bucket = params?.[1] as string; - const matched = rows.filter( - r => r.universe_market === market && r.horizon_bucket === bucket - ); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - } - - return { rows: [], rowCount: 0 }; - }, - }; - - return { - executor, - rows, - getInsertCalls: () => insertCalls, - getSelectCalls: () => selectCalls, - }; -} - -interface CopilotStudyFixture { - readonly listingIds: readonly number[]; - readonly allDates: readonly string[]; - readonly preCutoffSessions: number; - readonly firstDate: string; - readonly lastPreCutoffDate: string; - readonly vaultCutoffDate: string; - readonly vaultCutoffTs: number; - readonly postCutoffDate: string; - readonly bars: readonly BarRecord[]; - readonly shortsTable: Table; - readonly fundamentalsRows: readonly TableRow[]; - readonly eventsTable: Table; - readonly symbols: readonly SymbolSearchRow[]; - readonly exchangeCalendars: EventStudyExchangeCalendars; -} - -function buildCopilotStudyFixture(): CopilotStudyFixture { - const rand = createSeededRng(SEED); - const listingCount = 16; - const preCutoffSessions = 80; - const postCutoffSessions = 8; - - const allDates = makeBusinessDates('2022-11-01', preCutoffSessions + postCutoffSessions); - const firstDate = allDates[0]!; - const lastPreCutoffDate = allDates[preCutoffSessions - 1]!; - const vaultCutoffDate = allDates[preCutoffSessions]!; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - const postCutoffDate = allDates[allDates.length - 1]!; - - const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i); - const bars: BarRecord[] = []; - const shortsRows: TableRow[] = []; - const fundamentalsRows: TableRow[] = []; - const eventRows: TableRow[] = []; - - const fundamentalReleaseIndices = [0, 22, 44, 64]; - for (let rIdx = 0; rIdx < fundamentalReleaseIndices.length; rIdx += 1) { - const t = fundamentalReleaseIndices[rIdx]!; - const relDate = allDates[t]!; - const effectiveKnownAt = makeUtcMs(relDate, 13); // 08:00 ET pre-close - for (let l = 0; l < listingCount; l += 1) { - const revenue = 250 + ((l * 7 + rIdx * 5) % listingCount) * 40 + rIdx * 15; - const ttmRevenue = revenue * 4 + ((l + rIdx) % 4) * 25; - fundamentalsRows.push({ - listing_id: listingIds[l]!, - effective_known_at: effectiveKnownAt, - known_at_source: 'sec_edgar_filing', - has_estimated_lag: false, - period_end: relDate, - fiscal_period: `Q${(rIdx % 4) + 1}`, - currency: 'USD', - period_known_at: effectiveKnownAt, - revenue, - net_income: Number((revenue * 0.14).toFixed(2)), - operating_cash_flow: Number((revenue * 0.19).toFixed(2)), - total_assets: Number((revenue * 3.8).toFixed(2)), - total_equity: Number((revenue * 1.7).toFixed(2)), - shares_outstanding: 10_000_000, - ttm_revenue: ttmRevenue, - ttm_net_income: Number((ttmRevenue * 0.14).toFixed(2)), - ttm_operating_cash_flow: Number((ttmRevenue * 0.19).toFixed(2)), - ttm_period_end: relDate, - ttm_currency: 'USD', - ttm_has_estimated_lag: false, - }); - } - } - - const eventDayIndices = [12, 20, 28, 38, 48, 58]; - const eventSet = new Set(); - for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) { - const t = eventDayIndices[eIdx]!; - const date = allDates[t]!; - const ts = makeUtcMs(date, 14); // 09:00 ET intraday filing -> anchors on same session - for (let k = 0; k < 2; k += 1) { - const l = (eIdx * 2 + k) % listingCount; - eventSet.add(`${t}:${l}`); - const kind: EventKind = 'filing'; - eventRows.push({ - listing_id: listingIds[l]!, - ts, - known_at: ts, - known_at_source: 'exact', - kind, - subtype: '8-K', - payload_json: '{}', - }); - } - } - - const publicationLagSessions = 3; - const activeSignal = new Float64Array(listingCount); - const pendingByPublishIdx = new Map(); - const prices = new Float64Array(listingCount); - for (let l = 0; l < listingCount; l += 1) { - prices[l] = 15 + l * 2.5; - } - - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); // 16:00 ET close - - const released = pendingByPublishIdx.get(t - 1); - if (released !== undefined) { - for (let l = 0; l < listingCount; l += 1) { - activeSignal[l] = (released[l] ?? 0) / 20_000; - } - } - - const publishIdx = t + publicationLagSessions; - if (t % 5 === 0 && publishIdx < allDates.length) { - const reportKnownAt = makeUtcMs(allDates[publishIdx]!, 22); // 17:00 ET on T+3 - const pending: number[] = []; - for (let l = 0; l < listingCount; l += 1) { - const netChange = Math.round((rand() * 2 - 1) * 20_000); - pending.push(netChange); - shortsRows.push({ - listing_id: listingIds[l]!, - report_date: date, - known_at: reportKnownAt, - shares_short: 100_000 + l * 4_000 + Math.round(rand() * 10_000), - net_change: netChange, - pct_float: Number((0.02 + rand() * 0.08).toFixed(4)), - source: 'ceoShorts', - }); - } - pendingByPublishIdx.set(publishIdx, pending); - } - - for (let l = 0; l < listingCount; l += 1) { - let eventDrift = 0; - for (let offset = 0; offset <= 3; offset += 1) { - if (eventSet.has(`${t - offset}:${l}`)) { - eventDrift += 0.006 * (1 + ((l + t) % 3) * 0.25); - } - } - const dailyRet = -0.004 * activeSignal[l]! + eventDrift + (rand() * 2 - 1) * 0.009; - prices[l] = Math.max(1.0, prices[l]! * (1 + dailyRet)); - const close = Number(prices[l]!.toFixed(4)); - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: Number((close * 0.995).toFixed(4)), - high: Number((close * 1.01).toFixed(4)), - low: Number((close * 0.99).toFixed(4)), - close, - volume: 50_000 + l * 1_500 + t * 100, - vwap: close, - knownAt: closeTs, - }); - } - } - - const symbols: SymbolSearchRow[] = listingIds.map((listingId, idx) => ({ - listingId, - instrumentId: 80_001 + idx, - ticker: idx === 0 ? 'ACME' : `SYN${idx}`, - classSuffix: null, - name: idx === 0 ? 'Acme Synthetic Corp' : `Synthetic Equity ${idx}`, - mic: 'XNYS', - currency: 'USD', - isin: `US000000${String(idx).padStart(4, '0')}`, - firstBarDate: firstDate, - lastBarDate: postCutoffDate, - delistedAt: null, - })); - - const xnysSessions = allDates.map(date => ({ - date, - closeTs: makeUtcMs(date, 21), - })); - const listingCalendarId = new Map(); - for (const id of listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - - return { - listingIds, - allDates, - preCutoffSessions, - firstDate, - lastPreCutoffDate, - vaultCutoffDate, - vaultCutoffTs, - postCutoffDate, - bars, - shortsTable: { - columns: [...SHORTS_COLUMNS], - rows: shortsRows, - }, - fundamentalsRows, - eventsTable: { - columns: [...EVENTS_COLUMNS], - rows: eventRows, - }, - symbols, - exchangeCalendars: { - calendars: { XNYS: xnysSessions }, - listingCalendarId, - }, - }; -} - -interface FakeMarketDataStoreHandle { - readonly store: MarketDataStore; - readonly getBarsCalls: () => number; - readonly getShortsCalls: () => number; - readonly getFundamentalsCalls: () => number; - readonly getEventsCalls: () => number; - readonly getUniverseCalls: () => number; -} - -function createFakeMarketDataStore( - fixture: CopilotStudyFixture, - options?: { - readonly leakyVaultRows?: boolean; - } -): FakeMarketDataStoreHandle { - const leaky = options?.leakyVaultRows ?? false; - let barsCalls = 0; - let shortsCalls = 0; - let fundamentalsCalls = 0; - let eventsCalls = 0; - let universeCalls = 0; - - // Deliberately leaky rows: - // 1) Bar at exact vaultCutoffTs and after vaultCutoffTs (by ts) - // 2) Bar with pre-cutoff ts (early observation) but late knownAt >= vaultCutoffTs - // 3) Short row with pre-cutoff report_date but late known_at >= vaultCutoffTs - const leakyBars: BarRecord[] = [ - { - listingId: fixture.listingIds[0]!, - ts: fixture.vaultCutoffTs, - open: 999, - high: 999, - low: 999, - close: 999, - volume: 1000, - vwap: 999, - knownAt: fixture.vaultCutoffTs, - }, - { - listingId: fixture.listingIds[1]!, - ts: makeUtcMs(fixture.postCutoffDate, 21), - open: 888, - high: 888, - low: 888, - close: 888, - volume: 1000, - vwap: 888, - knownAt: makeUtcMs(fixture.postCutoffDate, 21), - }, - { - listingId: fixture.listingIds[0]!, - ts: makeUtcMs(fixture.lastPreCutoffDate, 21), - open: 777, - high: 777, - low: 777, - close: 777, - volume: 1000, - vwap: 777, - knownAt: fixture.vaultCutoffTs + 60_000, - }, - ]; - - const leakyShortsRows: TableRow[] = [ - { - listing_id: fixture.listingIds[0]!, - report_date: fixture.lastPreCutoffDate, - known_at: fixture.vaultCutoffTs + 120_000, - shares_short: 999_999, - net_change: 500_000, - pct_float: 0.99, - source: 'ceoShorts', - }, - { - listing_id: fixture.listingIds[1]!, - report_date: fixture.vaultCutoffDate, - known_at: fixture.vaultCutoffTs, - shares_short: 888_888, - net_change: -500_000, - pct_float: 0.88, - source: 'ceoShorts', - }, - ]; - - const store: MarketDataStore = { - bars(q): AsyncIterable { - barsCalls += 1; - const idSet = new Set(q.listingIds); - const fromMs = parseBoundMs(q.from, false); - const toMs = parseBoundMs(q.to, true); - const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - - const filtered = fixture.bars.filter( - row => - idSet.has(row.listingId) && - row.ts >= fromMs && - row.ts <= toMs && - row.knownAt <= asOfMs - ); - const out = leaky ? [...filtered, ...leakyBars] : filtered; - - return { - async *[Symbol.asyncIterator]() { - yield { rows: out }; - }, - }; - }, - - async universe() { - universeCalls += 1; - return [...fixture.listingIds]; - }, - - async shortsAsOf(q): Promise
{ - shortsCalls += 1; - const idSet = new Set(q.listingIds); - const fromDate = q.from.slice(0, 10); - const toDate = q.to.slice(0, 10); - const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - - const filtered = fixture.shortsTable.rows.filter(row => { - const listingId = row.listing_id as number; - const reportDate = row.report_date as string; - const knownAt = row.known_at as number; - return ( - idSet.has(listingId) && - reportDate >= fromDate && - reportDate <= toDate && - knownAt <= asOfMs - ); - }); - - return { - columns: fixture.shortsTable.columns, - rows: leaky ? [...filtered, ...leakyShortsRows] : filtered, - }; - }, - - async events(q): Promise
{ - eventsCalls += 1; - const idSet = q.listingIds !== undefined ? new Set(q.listingIds) : null; - const kindSet = new Set(q.kinds); - const fromMs = parseBoundMs(q.from, false); - const toMs = parseBoundMs(q.to, true); - const asOfMs = q.asOf !== undefined ? parseBoundMs(q.asOf, true) : Number.POSITIVE_INFINITY; - - const filtered = fixture.eventsTable.rows.filter(row => { - const listingId = row.listing_id as number; - const kind = row.kind as EventKind; - const ts = row.ts as number; - const knownAt = row.known_at as number; - if (idSet !== null && !idSet.has(listingId)) { - return false; - } - return kindSet.has(kind) && ts >= fromMs && ts <= toMs && knownAt <= asOfMs; - }); - - return { - columns: fixture.eventsTable.columns, - rows: filtered, - }; - }, - - async crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - async fundamentalsAsOf(q): Promise
{ - fundamentalsCalls += 1; - const idSet = new Set(q.listingIds); - const asOfMs = parseBoundMs(q.asOf, true); - const allowEstimatedLag = q.allowEstimatedLag ?? false; - const latestByListing = new Map(); - - for (const row of fixture.fundamentalsRows) { - const listingId = row.listing_id as number; - const knownAt = row.effective_known_at as number; - if (!idSet.has(listingId) || knownAt > asOfMs) { - continue; - } - const prev = latestByListing.get(listingId); - if (prev === undefined || knownAt > (prev.effective_known_at as number)) { - latestByListing.set(listingId, row); - } - } - - const rows: TableRow[] = []; - for (const lid of [...latestByListing.keys()].sort((a, b) => a - b)) { - const row = latestByListing.get(lid)!; - if (!allowEstimatedLag && row.has_estimated_lag === true) { - continue; - } - rows.push(row); - } - - if (leaky) { - rows.push({ - listing_id: fixture.listingIds[0]!, - effective_known_at: fixture.vaultCutoffTs, - known_at_source: 'sec_edgar_filing', - has_estimated_lag: false, - period_end: fixture.vaultCutoffDate, - fiscal_period: 'Q4', - currency: 'USD', - period_known_at: fixture.vaultCutoffTs, - revenue: 999_999, - ttm_revenue: 999_999, - }); - } - - return { - columns: [ - 'listing_id', - 'effective_known_at', - 'known_at_source', - 'has_estimated_lag', - 'period_end', - 'fiscal_period', - 'currency', - 'period_known_at', - ...q.fields, - ], - rows, - }; - }, - async macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - async fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - - return { - store, - getBarsCalls: () => barsCalls, - getShortsCalls: () => shortsCalls, - getFundamentalsCalls: () => fundamentalsCalls, - getEventsCalls: () => eventsCalls, - getUniverseCalls: () => universeCalls, - }; -} - -interface FakeFindingStore { - readonly stored: FiledFindingRecord[]; - readonly appendCalls: { - readonly record: FiledFindingRecord; - readonly idempotencyKey?: string; - }[]; - readonly writePort: FindingWritePort; -} - -function createFakeFindingStore(): FakeFindingStore { - const stored: FiledFindingRecord[] = []; - const byIdempotencyKey = new Map(); - const appendCalls: { readonly record: FiledFindingRecord; readonly idempotencyKey?: string }[] = - []; - - const writePort: FindingWritePort = { - async appendFinding( - record: FiledFindingRecord, - idempotencyKey?: string - ): Promise { - appendCalls.push({ record, idempotencyKey }); - if (idempotencyKey !== undefined) { - const existing = byIdempotencyKey.get(idempotencyKey); - if (existing !== undefined) { - if (areFiledFindingPayloadsEqual(existing, record)) { - return { status: 'replayed', id: existing.id, createdAt: existing.createdAt }; - } - return { status: 'conflict' }; - } - } - const copy: FiledFindingRecord = { - ...record, - trialRefs: [...record.trialRefs], - evidenceRefs: [...record.evidenceRefs], - }; - stored.push(copy); - if (idempotencyKey !== undefined) { - byIdempotencyKey.set(idempotencyKey, copy); - } - return { status: 'created', id: copy.id, createdAt: copy.createdAt }; - }, - }; - - return { stored, appendCalls, writePort }; -} - -function createMemoryOutput(): { - readonly output: StdioOutput; - readonly lines: string[]; - readonly text: () => string; -} { - const chunks: string[] = []; - const lines: string[] = []; - let pending = ''; - - const output: StdioOutput = { - write(chunk: string): boolean { - chunks.push(chunk); - pending += chunk; - while (true) { - const idx = pending.indexOf('\n'); - if (idx === -1) { - break; - } - lines.push(pending.slice(0, idx)); - pending = pending.slice(idx + 1); - } - return true; - }, - }; - - return { - output, - lines, - text: () => chunks.join(''), - }; -} - -interface JsonRpcResponseEnvelope { - readonly jsonrpc: '2.0'; - readonly id: number | string | null; - readonly result?: unknown; - readonly error?: { - readonly code: number; - readonly message: string; - }; -} - -interface ToolCallEnvelope { - readonly content: readonly { readonly type: 'text'; readonly text: string }[]; - readonly isError?: boolean; -} - -function buildComposedServerOptions( - fixture: CopilotStudyFixture, - options?: { readonly leakyVaultRows?: boolean } -): { - readonly serverOptions: ResearchCopilotMcpServerOptions; - readonly storeHandle: FakeMarketDataStoreHandle; - readonly ledger: ReturnType; - readonly findings: FakeFindingStore; -} { - const storeHandle = createFakeMarketDataStore(fixture, { - leakyVaultRows: options?.leakyVaultRows, - }); - const ledger = createFakeTrialLedger(); - const findings = createFakeFindingStore(); - - const symbolSearchPort: SymbolSearchPort = { - async searchSymbols() { - return fixture.symbols; - }, - }; - - const knowledgePort: KnowledgePort = { - async listLibraryCards() { - return [ - { - id: 'card-dsr-01', - title: 'Deflated Sharpe & Effective Trials', - tags: ['dsr', 'rigor'], - summary: 'Adjust Sharpe ratios for multiple testing across relatedness clusters.', - body: 'Use clusterDeflatedSharpe with pre-Vault series and record every trial.', - }, - ]; - }, - async listFindings() { - return findings.stored; - }, - async listProviderCaveats() { - return [ - { - id: 'caveat-shorts-01', - provider: 'ceoShorts', - dataset: 'shorts', - caveat: 'Short-interest reports carry a multi-session publication lag.', - createdAt: '2024-01-15T00:00:00.000Z', - }, - ]; - }, - }; - - const serverOptions: ResearchCopilotMcpServerOptions = { - name: SERVER_NAME, - version: SERVER_VERSION, - store: storeHandle.store, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - ledger: ledger.executor, - principalId: AGENT_PRINCIPAL, - searchSymbols: { port: symbolSearchPort }, - eventStudy: { - resolveExchangeCalendars: () => fixture.exchangeCalendars, - }, - fileFinding: { - port: findings.writePort, - trialLookup: { - hasResearchVisibleTrial(ref: string): boolean { - return ledger.rows.some( - row => row.trial_id === ref && row.sample_end < fixture.vaultCutoffDate - ); - }, - }, - newId: () => FIXED_FINDING_ID, - now: () => FIXED_NOW_MS, - }, - readKnowledge: { port: knowledgePort }, - }; - - return { serverOptions, storeHandle, ledger, findings }; -} - -function decodeToolJson(response: JsonRpcResponseEnvelope): T { - expect(response.error).toBeUndefined(); - const result = response.result as ToolCallEnvelope; - expect(result.isError).not.toBe(true); - expect(result.content).toHaveLength(1); - return JSON.parse(result.content[0]!.text) as T; -} - -describe('createResearchCopilotMcpServer', () => { - test('tools/list returns the six literal expected tool names in fixed order with object inputSchemas', async () => { - const fixture = buildCopilotStudyFixture(); - const { serverOptions } = buildComposedServerOptions(fixture); - const server = createResearchCopilotMcpServer(serverOptions); - - expect(Object.isFrozen(RESEARCH_COPILOT_TOOL_NAMES)).toBe(true); - expect([...RESEARCH_COPILOT_TOOL_NAMES]).toEqual([...EXPECTED_TOOL_NAMES]); - - const rawResponse = await server.handleMessage( - JSON.stringify({ jsonrpc: '2.0', id: 'list-1', method: 'tools/list' }) - ); - expect(rawResponse).not.toBeNull(); - const parsed = JSON.parse(rawResponse!) as JsonRpcResponseEnvelope; - expect(parsed.error).toBeUndefined(); - const tools = (parsed.result as { tools: readonly McpToolDescriptor[] }).tools; - - expect(tools.map(t => t.name)).toEqual([...EXPECTED_TOOL_NAMES]); - expect(tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]); - - for (const tool of tools) { - expect(tool.inputSchema.type).toBe('object'); - expect(typeof tool.inputSchema.properties).toBe('object'); - expect(tool.inputSchema.properties).not.toBeNull(); - } - }); - - test('runs initialize -> tools/list -> search_symbols -> query_data -> analyze_signal (shorts + fundamentals) -> event_study -> read_knowledge -> file_finding in one stdio session', async () => { - const fixture = buildCopilotStudyFixture(); - const { serverOptions, storeHandle, ledger, findings } = buildComposedServerOptions(fixture); - const server = createResearchCopilotMcpServer(serverOptions); - const sink = createMemoryOutput(); - - let shortsTrialRef = ''; - let fundamentalsTrialRef = ''; - - async function* requestStream(): AsyncGenerator { - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: '2024-11-05', - capabilities: {}, - clientInfo: { name: 'headless-copilot-test', version: '1.0.0' }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 2, - method: 'tools/list', - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 3, - method: 'tools/call', - params: { - name: 'search_symbols', - arguments: { query: 'ACME', country: 'US', limit: 5 }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 4, - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [fixture.listingIds[0]!], - from: fixture.firstDate, - to: fixture.lastPreCutoffDate, - timeframe: '1d', - adjustment: 'raw', - limit: 10, - }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 5, - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: { - listingIds: [...fixture.listingIds], - from: fixture.firstDate, - to: fixture.lastPreCutoffDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - adjustment: 'raw', - }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 6, - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: { - listingIds: [...fixture.listingIds], - from: fixture.firstDate, - to: fixture.lastPreCutoffDate, - signal: { source: 'fundamentals', field: 'ttm_revenue' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - adjustment: 'raw', - }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 7, - method: 'tools/call', - params: { - name: 'event_study', - arguments: { - listingIds: [...fixture.listingIds], - from: fixture.firstDate, - to: fixture.lastPreCutoffDate, - event: { kinds: ['filing'], subtypes: ['8-K'] }, - preDays: 2, - postDays: 5, - benchmark: 'equal_weight', - adjustment: 'raw', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, - }, - })}\n`; - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 8, - method: 'tools/call', - params: { - name: 'read_knowledge', - arguments: { source: 'all', query: 'sharpe', limit: 5 }, - }, - })}\n`; - - // Decode both earlier analyze_signal responses written by runStdioServer before - // constructing the file_finding call so both trialRefs are dynamically linked. - expect(sink.lines.length).toBeGreaterThanOrEqual(6); - const shortsResp = JSON.parse(sink.lines[4]!) as JsonRpcResponseEnvelope; - const shortsPayload = decodeToolJson(shortsResp); - expect(shortsPayload.status).toBe('ok'); - if (shortsPayload.status !== 'ok') { - throw new Error('Expected shorts analyze_signal status to be ok.'); - } - shortsTrialRef = String(shortsPayload.trial.trialId); - - const fundamentalsResp = JSON.parse(sink.lines[5]!) as JsonRpcResponseEnvelope; - const fundamentalsPayload = decodeToolJson(fundamentalsResp); - expect(fundamentalsPayload.status).toBe('ok'); - if (fundamentalsPayload.status !== 'ok') { - throw new Error('Expected fundamentals analyze_signal status to be ok.'); - } - fundamentalsTrialRef = String(fundamentalsPayload.trial.trialId); - - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 9, - method: 'tools/call', - params: { - name: 'file_finding', - arguments: { - kind: 'finding', - title: 'Short-interest and fundamentals signal studies on synthetic US_EQ panel', - summary: `Dataset ${FIXTURE_DATASET_ID}, raw close-to-close returns, zero modeled costs, pre-Vault window ${fixture.firstDate}..${fixture.lastPreCutoffDate}.`, - trialRefs: [shortsTrialRef, fundamentalsTrialRef], - evidenceRefs: [FIXTURE_DATASET_ID], - idempotencyKey: 'copilot-e2e-finding-1', - }, - }, - })}\n`; - } - - await runStdioServer(server, { input: requestStream(), output: sink.output }); - - const rawOut = sink.text(); - expect(rawOut.endsWith('\n')).toBe(true); - expect(sink.lines).toHaveLength(9); - - const responses = sink.lines.map(line => JSON.parse(line) as JsonRpcResponseEnvelope); - expect(responses.map(r => r.id)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]); - for (const resp of responses) { - expect(resp.error).toBeUndefined(); - } - - // 1. initialize - const initResult = responses[0]!.result as { - serverInfo: { name: string; version: string }; - capabilities: { tools: Record }; - }; - expect(initResult.serverInfo).toEqual({ name: SERVER_NAME, version: SERVER_VERSION }); - expect(initResult.capabilities.tools).toEqual({}); - - // 2. tools/list - const listResult = responses[1]!.result as { tools: readonly McpToolDescriptor[] }; - expect(listResult.tools.map(t => t.name)).toEqual([...EXPECTED_TOOL_NAMES]); - - // 3. search_symbols - const searchPayload = decodeToolJson(responses[2]!); - expect(searchPayload.scope).toBe('vault_fenced'); - expect(searchPayload.rowCount).toBe(1); - expect(searchPayload.rows[0]?.ticker).toBe('ACME'); - expect(searchPayload.rows[0]?.listingId).toBe(fixture.listingIds[0]); - - // 4. query_data - const queryPayload = decodeToolJson(responses[3]!); - expect(queryPayload.scope).toBe('vault_fenced'); - expect(queryPayload.rowCount).toBe(10); - expect(queryPayload.truncated).toBe(true); - expect(queryPayload.rows.every(r => r.ts < fixture.vaultCutoffTs)).toBe(true); - - // 5. analyze_signal (shorts) - const shortsSignalPayload = decodeToolJson(responses[4]!); - expect(shortsSignalPayload.status).toBe('ok'); - if (shortsSignalPayload.status !== 'ok') { - throw new Error('Expected shorts analyze_signal status to be ok.'); - } - expect(shortsSignalPayload.signal).toEqual({ source: 'shorts', field: 'net_change' }); - expect(String(shortsSignalPayload.trial.trialId)).toBe(shortsTrialRef); - - // 6. analyze_signal (fundamentals) - const fundamentalsSignalPayload = decodeToolJson(responses[5]!); - expect(fundamentalsSignalPayload.status).toBe('ok'); - if (fundamentalsSignalPayload.status !== 'ok') { - throw new Error('Expected fundamentals analyze_signal status to be ok.'); - } - expect(fundamentalsSignalPayload.signal).toEqual({ - source: 'fundamentals', - field: 'ttm_revenue', - allowEstimatedLag: false, - }); - expect(String(fundamentalsSignalPayload.trial.trialId)).toBe(fundamentalsTrialRef); - expect(fundamentalsSignalPayload.trial.expressionHash).not.toBe( - shortsSignalPayload.trial.expressionHash - ); - expect(storeHandle.getFundamentalsCalls()).toBeGreaterThan(0); - - // 7. event_study - const eventPayload = decodeToolJson(responses[6]!); - expect(eventPayload.status).toBe('ok'); - if (eventPayload.status !== 'ok') { - throw new Error('Expected event_study status to be ok.'); - } - expect(eventPayload.benchmark).toBe('equal_weight'); - expect(eventPayload.study.hasBenchmark).toBe(true); - - // 8. read_knowledge - const knowledgePayload = decodeToolJson(responses[7]!); - expect(knowledgePayload.rowCount).toBe(1); - expect(knowledgePayload.rows[0]?.id).toBe('card-dsr-01'); - - // 9. file_finding - const findingPayload = decodeToolJson(responses[8]!); - expect(findingPayload).toEqual({ - id: FIXED_FINDING_ID, - createdAt: FIXED_NOW_ISO, - created: true, - }); - - // Verify trial_ledger recorded both signal_ic trials (distinct hashes) and event_study under AGENT_PRINCIPAL. - expect(ledger.rows).toHaveLength(3); - expect(ledger.rows.map(r => r.stage)).toEqual(['signal_ic', 'signal_ic', 'event_study']); - expect(ledger.rows.every(r => r.principal_id === AGENT_PRINCIPAL)).toBe(true); - expect(ledger.rows[0]?.trial_id).toBe(String(shortsSignalPayload.trial.trialId)); - expect(ledger.rows[1]?.trial_id).toBe(String(fundamentalsSignalPayload.trial.trialId)); - expect(ledger.rows[2]?.trial_id).toBe(String(eventPayload.trial.trialId)); - expect(ledger.rows[0]?.expression_hash).not.toBe(ledger.rows[1]?.expression_hash); - - // Verify FindingWritePort recorded exactly one pending_review finding referencing both signal trials. - expect(findings.appendCalls).toHaveLength(1); - expect(findings.stored).toHaveLength(1); - expect(findings.stored[0]).toMatchObject({ - id: findingPayload.id, - createdAt: findingPayload.createdAt, - kind: 'finding', - status: 'pending_review', - trialRefs: [shortsTrialRef, fundamentalsTrialRef], - evidenceRefs: [FIXTURE_DATASET_ID], - }); - }); - - test('enforces the Vault fence on straddling and post-cutoff query_data and analyze_signal calls (clean vs leaky store)', async () => { - const fixture = buildCopilotStudyFixture(); - const clean = buildComposedServerOptions(fixture, { leakyVaultRows: false }); - const leaky = buildComposedServerOptions(fixture, { leakyVaultRows: true }); - - const cleanServer = createResearchCopilotMcpServer(clean.serverOptions); - const leakyServer = createResearchCopilotMcpServer(leaky.serverOptions); - - // Straddling query_data: ends after vaultCutoffDate with explicit post-cutoff asOf - const straddlingQueryReq = JSON.stringify({ - jsonrpc: '2.0', - id: 'q-straddle', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [fixture.listingIds[0]!, fixture.listingIds[1]!], - from: fixture.firstDate, - to: fixture.postCutoffDate, - asOf: fixture.postCutoffDate, - timeframe: '1d', - adjustment: 'raw', - limit: 500, - }, - }, - }); - - const cleanQueryPayload = decodeToolJson( - JSON.parse((await cleanServer.handleMessage(straddlingQueryReq))!) as JsonRpcResponseEnvelope - ); - const leakyQueryPayload = decodeToolJson( - JSON.parse((await leakyServer.handleMessage(straddlingQueryReq))!) as JsonRpcResponseEnvelope - ); - - for (const payload of [cleanQueryPayload, leakyQueryPayload]) { - expect(payload.scope).toBe('vault_fenced'); - expect(payload.clampedTo).toBe(true); - expect(payload.clampedAsOf).toBe(true); - expect(payload.toMs).toBe(fixture.vaultCutoffTs - 1); - expect(payload.asOfMs).toBe(fixture.vaultCutoffTs - 1); - expect(payload.rows.every(r => r.ts < fixture.vaultCutoffTs && r.knownAt < fixture.vaultCutoffTs)).toBe( - true - ); - } - expect(leakyQueryPayload.rows).toEqual(cleanQueryPayload.rows); - - // Straddling analyze_signal: clean vs deliberately leaky store must produce identical payload & trial row - const straddlingSignalReq = JSON.stringify({ - jsonrpc: '2.0', - id: 'sig-straddle', - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: { - listingIds: [...fixture.listingIds], - from: fixture.firstDate, - to: fixture.postCutoffDate, - asOf: fixture.postCutoffDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - adjustment: 'raw', - }, - }, - }); - - const cleanSignalPayload = decodeToolJson( - JSON.parse((await cleanServer.handleMessage(straddlingSignalReq))!) as JsonRpcResponseEnvelope - ); - const leakySignalPayload = decodeToolJson( - JSON.parse((await leakyServer.handleMessage(straddlingSignalReq))!) as JsonRpcResponseEnvelope - ); - - expect(cleanSignalPayload.status).toBe('ok'); - expect(leakySignalPayload.status).toBe('ok'); - expect(leakySignalPayload).toEqual(cleanSignalPayload); - expect(leakySignalPayload.scope).toBe('vault_fenced'); - expect(leakySignalPayload.clampedTo).toBe(true); - expect(leakySignalPayload.clampedAsOf).toBe(true); - expect(leakySignalPayload.toMs).toBe(fixture.vaultCutoffTs - 1); - expect(leakySignalPayload.asOfMs).toBe(fixture.vaultCutoffTs - 1); - - expect(clean.ledger.rows).toHaveLength(1); - expect(leaky.ledger.rows).toHaveLength(1); - expect(leaky.ledger.rows[0]).toEqual(clean.ledger.rows[0]); - - // Last forward-return endpoint must remain strictly before vaultCutoffDate. - const lastSampleEnd = leaky.ledger.rows[0]!.sample_end; - const lastSampleIdx = fixture.allDates.indexOf(lastSampleEnd); - expect(lastSampleIdx).toBeGreaterThanOrEqual(0); - expect(lastSampleIdx + 5).toBeLessThan(fixture.preCutoffSessions); - expect(fixture.allDates[lastSampleIdx + 5]! < fixture.vaultCutoffDate).toBe(true); - - // Wholly post-cutoff range must return VaultHoldoutFenceError with zero store reads and zero ledger writes. - const postCutoffCheck = buildComposedServerOptions(fixture); - const postCutoffServer = createResearchCopilotMcpServer(postCutoffCheck.serverOptions); - - const postQueryResp = JSON.parse( - (await postCutoffServer.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'q-post', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [fixture.listingIds[0]!], - from: fixture.vaultCutoffDate, - to: fixture.postCutoffDate, - timeframe: '1d', - adjustment: 'raw', - }, - }, - }) - ))! - ) as JsonRpcResponseEnvelope; - const postQueryTool = postQueryResp.result as ToolCallEnvelope; - expect(postQueryTool.isError).toBe(true); - expect(postQueryTool.content[0]?.text).toContain('VaultHoldoutFenceError'); - - const postSignalResp = JSON.parse( - (await postCutoffServer.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'sig-post', - method: 'tools/call', - params: { - name: 'analyze_signal', - arguments: { - listingIds: [...fixture.listingIds], - from: fixture.vaultCutoffDate, - to: fixture.postCutoffDate, - signal: { source: 'shorts', field: 'net_change' }, - horizonSessions: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - adjustment: 'raw', - }, - }, - }) - ))! - ) as JsonRpcResponseEnvelope; - const postSignalTool = postSignalResp.result as ToolCallEnvelope; - expect(postSignalTool.isError).toBe(true); - expect(postSignalTool.content[0]?.text).toContain('VaultHoldoutFenceError'); - - expect(postCutoffCheck.storeHandle.getBarsCalls()).toBe(0); - expect(postCutoffCheck.storeHandle.getShortsCalls()).toBe(0); - expect(postCutoffCheck.storeHandle.getUniverseCalls()).toBe(0); - expect(postCutoffCheck.ledger.getInsertCalls()).toBe(0); - }); - - test('returns INVALID_PARAMS for unknown tool in stdio session and continues processing ping', async () => { - const fixture = buildCopilotStudyFixture(); - const { serverOptions } = buildComposedServerOptions(fixture); - const server = createResearchCopilotMcpServer(serverOptions); - const sink = createMemoryOutput(); - - async function* input(): AsyncGenerator { - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 'bad-tool', - method: 'tools/call', - params: { name: 'nonexistent_tool', arguments: {} }, - })}\n`; - yield `${JSON.stringify({ - jsonrpc: '2.0', - id: 'keep-alive', - method: 'ping', - })}\n`; - } - - await runStdioServer(server, { input: input(), output: sink.output }); - - expect(sink.lines).toHaveLength(2); - const errResp = JSON.parse(sink.lines[0]!) as JsonRpcResponseEnvelope; - const pingResp = JSON.parse(sink.lines[1]!) as JsonRpcResponseEnvelope; - - expect(errResp.id).toBe('bad-tool'); - expect(errResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); - expect(errResp.error?.message).toBe('Unknown tool: "nonexistent_tool".'); - - expect(pingResp.id).toBe('keep-alive'); - expect(pingResp.error).toBeUndefined(); - expect(pingResp.result).toEqual({}); - }); - - test('throws on duplicate or missing/unexpected tool name during server composition', () => { - const fixture = buildCopilotStudyFixture(); - const { serverOptions } = buildComposedServerOptions(fixture); - - const dupSpy = spyOn(queryDataToolModule, 'createQueryDataTool').mockImplementation(() => ({ - name: 'search_symbols', - description: 'Duplicate name entry', - inputSchema: { type: 'object', properties: {}, additionalProperties: false }, - async execute() { - return { content: [{ type: 'text', text: '{}' }] }; - }, - })); - try { - expect(() => createResearchCopilotMcpServer(serverOptions)).toThrow( - /Duplicate MCP tool name/ - ); - } finally { - dupSpy.mockRestore(); - } - - const missingSpy = spyOn(readKnowledgeToolModule, 'createReadKnowledgeTool').mockImplementation( - () => ({ - name: 'unexpected_tool', - description: 'Unexpected name entry leaving read_knowledge missing', - inputSchema: { type: 'object', properties: {}, additionalProperties: false }, - async execute() { - return { content: [{ type: 'text', text: '{}' }] }; - }, - }) - ); - try { - expect(() => createResearchCopilotMcpServer(serverOptions)).toThrow( - /expected "read_knowledge", got "unexpected_tool"/ - ); - } finally { - missingSpy.mockRestore(); - } - }); -}); diff --git a/libs/research/test/mcp-edge-cases.test.ts b/libs/research/test/mcp-edge-cases.test.ts deleted file mode 100644 index c20ec3c5..00000000 --- a/libs/research/test/mcp-edge-cases.test.ts +++ /dev/null @@ -1,595 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { z } from 'zod'; -import { - type BarBatch, - type BarRecord, - type MarketDataStore, - VaultHoldoutFenceError, -} from '../src/market-data-store'; -import { - type BarsQuery, - MarketDataStoreNotImplementedError, - type UniverseQuery, -} from '../src/market-data-store-duckdb'; -import { - JSON_RPC_ERROR_CODES, - type JsonSchemaObject, - QUERY_DATA_MAX_LISTING_IDS, - type QueryDataResultPayload, - type StdioOutput, - createMcpServer, - createQueryDataTool, - defineMcpTool, - runStdioServer, - zodObjectToJsonSchema, -} from '../src/mcp/index'; - -// QA edge cases for T-129 (M2.1a MCP core) not covered by the programmer's suites. - -const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); - -interface ToolResult { - isError?: boolean; - content: { type: string; text: string }[]; -} - -interface RpcResponse { - id: string | number | null; - result?: unknown; - error?: { code: number; message: string }; -} - -function rpc(id: string | number, method: string, params?: unknown): string { - return JSON.stringify( - params === undefined ? { jsonrpc: '2.0', id, method } : { jsonrpc: '2.0', id, method, params } - ); -} - -function parse(raw: string | null): RpcResponse { - expect(raw).not.toBeNull(); - return JSON.parse(raw as string) as RpcResponse; -} - -function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord { - return { - listingId, - ts, - open: close, - high: close, - low: close, - close, - volume: 1, - vwap: close, - knownAt, - }; -} - -interface RecordingStore { - readonly store: MarketDataStore; - readonly barsCalls: BarsQuery[]; - readonly universeCalls: UniverseQuery[]; - readonly iteratorClosed: () => boolean; -} - -function createRecordingStore(options: { - batches?: readonly BarBatch[]; - universeIds?: readonly number[]; - universeError?: Error; -}): RecordingStore { - const barsCalls: BarsQuery[] = []; - const universeCalls: UniverseQuery[] = []; - let closed = false; - const store: MarketDataStore = { - bars(q: BarsQuery): AsyncIterable { - barsCalls.push(q); - const batches = options.batches ?? []; - return { - async *[Symbol.asyncIterator]() { - try { - for (const batch of batches) { - yield batch; - } - } finally { - closed = true; - } - }, - }; - }, - async universe(q: UniverseQuery): Promise { - universeCalls.push(q); - if (options.universeError !== undefined) { - throw options.universeError; - } - return [...(options.universeIds ?? [])]; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - return { store, barsCalls, universeCalls, iteratorClosed: () => closed }; -} - -async function callQueryData( - rec: RecordingStore, - args: Record, - vaultCutoffTs = VAULT_CUTOFF_TS -): Promise<{ isError: boolean; text: string }> { - const server = createMcpServer({ - name: 'qa', - version: '0.0.0', - tools: [createQueryDataTool({ store: rec.store, vaultContext: { vaultCutoffTs } })], - }); - const resp = parse( - await server.handleMessage(rpc('q', 'tools/call', { name: 'query_data', arguments: args })) - ); - expect(resp.error).toBeUndefined(); - const result = resp.result as ToolResult; - return { isError: result.isError === true, text: result.content[0]?.text ?? '' }; -} - -function memoryOutput(): { output: StdioOutput; chunks: string[] } { - const chunks: string[] = []; - return { - chunks, - output: { - write(chunk: string): boolean { - chunks.push(chunk); - return true; - }, - }, - }; -} - -async function* chunksOf(chunks: readonly (string | Uint8Array)[]): AsyncGenerator { - for (const c of chunks) { - yield c; - } -} - -describe('MCP server edge cases (QA)', () => { - test('tools/call sent as a notification returns null and never runs the handler', async () => { - let calls = 0; - const tool = defineMcpTool({ - name: 'side_effect', - description: 'Counts invocations.', - inputSchema: z.object({}).strict(), - handler() { - calls += 1; - return { content: [{ type: 'text', text: 'ran' }] }; - }, - }); - const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - method: 'tools/call', - params: { name: 'side_effect', arguments: {} }, - }) - ); - - expect(raw).toBeNull(); - expect(calls).toBe(0); - }); - - test('tools/call with missing or array params returns -32602 echoing the id', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - for (const [id, params] of [ - [7, undefined], - ['arr', [{ name: 'x' }]], - [8, { arguments: {} }], - [9, { name: 'x', arguments: [1, 2] }], - ] as const) { - const resp = parse(await server.handleMessage(rpc(id, 'tools/call', params))); - expect(resp.id).toBe(id); - expect(resp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); - } - }); - - test('initialize with invalid params returns -32602 and does not crash', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const resp = parse( - await server.handleMessage(rpc('init', 'initialize', { clientInfo: { name: 5 } })) - ); - expect(resp.id).toBe('init'); - expect(resp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); - }); - - test('non-Error throws and errors with unsafe names are sanitized to a fixed message', async () => { - const throwString = defineMcpTool({ - name: 'throw_string', - description: 'Throws a string.', - inputSchema: z.object({}).strict(), - handler() { - throw '/srv/secret/path leaked'; - }, - }); - const throwBadName = defineMcpTool({ - name: 'throw_bad_name', - description: 'Throws an error whose name contains a path.', - inputSchema: z.object({}).strict(), - async handler() { - const err = new Error('boom /srv/secret/x.ts'); - err.name = '/srv/secret/x.ts'; - throw err; - }, - }); - const server = createMcpServer({ - name: 'qa', - version: '0.0.0', - tools: [throwString, throwBadName], - }); - - for (const [name, expected] of [ - ['throw_string', 'Error: Tool execution failed.'], - ['throw_bad_name', 'Error: Tool execution failed.'], - ] as const) { - const resp = parse(await server.handleMessage(rpc(name, 'tools/call', { name, arguments: {} }))); - const result = resp.result as ToolResult; - expect(result.isError).toBe(true); - expect(result.content[0]?.text).toBe(expected); - expect(result.content[0]?.text).not.toContain('/srv/secret'); - } - }); - - test('responses are single-line JSON even when tool text contains newlines', async () => { - const tool = defineMcpTool({ - name: 'multiline', - description: 'Returns multi-line text.', - inputSchema: z.object({}).strict(), - handler: () => ({ content: [{ type: 'text', text: 'line1\nline2\r\nline3' }] }), - }); - const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); - const raw = await server.handleMessage( - rpc(1, 'tools/call', { name: 'multiline', arguments: {} }) - ); - expect(raw).not.toContain('\n'); - expect(raw).not.toContain('\r'); - expect((parse(raw).result as ToolResult).content[0]?.text).toBe('line1\nline2\r\nline3'); - }); - - test('explicit jsonSchema override is emitted verbatim by tools/list', async () => { - const override: JsonSchemaObject = { - type: 'object', - properties: { q: { type: 'string', description: 'custom' } }, - required: ['q'], - additionalProperties: false, - }; - const tool = defineMcpTool({ - name: 'with_override', - description: 'Has a hand-written schema.', - inputSchema: z.object({ q: z.string() }).strict(), - jsonSchema: override, - handler: () => ({ content: [{ type: 'text', text: 'ok' }] }), - }); - const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [tool] }); - const resp = parse(await server.handleMessage(rpc(1, 'tools/list'))); - const tools = (resp.result as { tools: { inputSchema: unknown }[] }).tools; - expect(tools[0]?.inputSchema).toEqual(override); - }); - - test('zod converter maps nullable, union, literal, exclusive bounds, defaults, arrays and refinements', () => { - const schema = z - .object({ - n: z.number().gt(0).lt(10).describe('open interval'), - s: z.string().length(3), - maybe: z.string().nullable(), - either: z.union([z.string(), z.number().int()]), - lit: z.literal('fixed'), - flag: z.boolean().default(false), - tags: z.array(z.string()).min(1).max(4).optional(), - }) - .strict() - .refine(() => true) - .describe('root'); - - const json = zodObjectToJsonSchema(schema); - - expect(json.type).toBe('object'); - expect(json.additionalProperties).toBe(false); - expect(json.description).toBe('root'); - expect(json.required).toEqual(['n', 's', 'maybe', 'either', 'lit']); - expect(json.properties.n).toEqual({ - type: 'number', - description: 'open interval', - exclusiveMinimum: 0, - exclusiveMaximum: 10, - }); - expect(json.properties.s).toEqual({ type: 'string', minLength: 3, maxLength: 3 }); - expect(json.properties.maybe).toEqual({ anyOf: [{ type: 'string' }, { type: 'null' }] }); - expect(json.properties.either).toEqual({ - anyOf: [{ type: 'string' }, { type: 'integer' }], - }); - expect(json.properties.lit).toEqual({ type: 'string', const: 'fixed' }); - expect(json.properties.flag).toEqual({ type: 'boolean', default: false }); - expect(json.properties.tags).toEqual({ - type: 'array', - items: { type: 'string' }, - minItems: 1, - maxItems: 4, - }); - - expect(() => zodObjectToJsonSchema(z.string())).toThrow(/must be a ZodObject/); - }); - - test('defineMcpTool and createMcpServer reject empty names/descriptions/versions', () => { - const base = { - inputSchema: z.object({}).strict(), - handler: () => ({ content: [{ type: 'text' as const, text: '' }] }), - }; - expect(() => defineMcpTool({ ...base, name: ' ', description: 'd' })).toThrow(); - expect(() => defineMcpTool({ ...base, name: 'n', description: '' })).toThrow(); - expect(() => createMcpServer({ name: '', version: '1' })).toThrow(); - expect(() => createMcpServer({ name: 'n', version: ' ' })).toThrow(); - }); -}); - -describe('MCP stdio edge cases (QA)', () => { - test('oversized frame spread across many chunks yields exactly one -32700 and recovers', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const pad = 'x'.repeat(100); - const sink = memoryOutput(); - - await runStdioServer(server, { - input: chunksOf([ - `{"jsonrpc":"2.0","id":1,"method":"ping","pad":"${pad}`, - pad, - pad, - `${pad}"}\n${rpc(2, 'ping')}\n`, - ]), - output: sink.output, - maxLineBytes: 64, - }); - - const lines = sink.chunks.join('').trimEnd().split('\n'); - expect(lines).toHaveLength(2); - const first = JSON.parse(lines[0] ?? '') as RpcResponse; - const second = JSON.parse(lines[1] ?? '') as RpcResponse; - expect(first.id).toBeNull(); - expect(first.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); - expect(second.id).toBe(2); - expect(second.result).toEqual({}); - }); - - test('oversized unterminated tail at EOF yields one -32700 and never dispatches it', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const sink = memoryOutput(); - await runStdioServer(server, { - input: chunksOf([`${rpc(1, 'ping')}\n`, `{"jsonrpc":"2.0","id":2,"method":"ping","p":"${'y'.repeat(200)}"}`]), - output: sink.output, - maxLineBytes: 128, - }); - const lines = sink.chunks.join('').trimEnd().split('\n'); - expect(lines).toHaveLength(2); - expect((JSON.parse(lines[0] ?? '') as RpcResponse).id).toBe(1); - const err = JSON.parse(lines[1] ?? '') as RpcResponse; - expect(err.id).toBeNull(); - expect(err.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); - }); - - test('malformed line between valid requests yields -32700 and processing continues in order', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const sink = memoryOutput(); - await runStdioServer(server, { - input: chunksOf([`${rpc('a', 'ping')}\n{oops\n${rpc('b', 'ping')}\n`]), - output: sink.output, - }); - const lines = sink.chunks.join('').trimEnd().split('\n').map(l => JSON.parse(l) as RpcResponse); - expect(lines.map(l => l.id)).toEqual(['a', null, 'b']); - expect(lines[1]?.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); - }); - - test('a stream of only notifications writes zero bytes', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const sink = memoryOutput(); - await runStdioServer(server, { - input: chunksOf([ - `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`, - `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: 1 } })}\n`, - ]), - output: sink.output, - }); - expect(sink.chunks).toEqual([]); - }); - - test('waits for drain when output.write signals backpressure before writing the next response', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - const events: string[] = []; - const output: StdioOutput = { - write(chunk: string): boolean { - events.push(`write:${(JSON.parse(chunk) as RpcResponse).id}`); - return false; - }, - once(_event: 'drain', listener: () => void) { - events.push('await-drain'); - queueMicrotask(() => { - events.push('drain'); - listener(); - }); - }, - }; - - await runStdioServer(server, { - input: chunksOf([`${rpc(1, 'ping')}\n${rpc(2, 'ping')}\n`]), - output, - }); - - expect(events).toEqual(['write:1', 'await-drain', 'drain', 'write:2', 'await-drain', 'drain']); - }); - - test('rejects non-positive or non-integer maxLineBytes', async () => { - const server = createMcpServer({ name: 'qa', version: '0.0.0' }); - for (const bad of [0, -1, 1.5, Number.NaN]) { - await expect( - runStdioServer(server, { input: chunksOf([]), output: memoryOutput().output, maxLineBytes: bad }) - ).rejects.toThrow(/maxLineBytes/); - } - }); -}); - -describe('MCP query_data edge cases (QA)', () => { - test('selector rules: both, neither, too many, or non-integer listingIds are rejected with zero store calls', async () => { - const tooMany = Array.from({ length: QUERY_DATA_MAX_LISTING_IDS + 1 }, (_, i) => i + 1); - const cases: Record[] = [ - { listingIds: [1], universe: 'US_EQ', from: '2025-03-01', to: '2025-03-10' }, - { from: '2025-03-01', to: '2025-03-10' }, - { listingIds: [], from: '2025-03-01', to: '2025-03-10' }, - { listingIds: tooMany, from: '2025-03-01', to: '2025-03-10' }, - { listingIds: [1.5], from: '2025-03-01', to: '2025-03-10' }, - { listingIds: [2_147_483_648], from: '2025-03-01', to: '2025-03-10' }, - { listingIds: [1], from: '2025-03-01', to: '2025-03-10', timeframe: '1w' }, - { listingIds: [1], from: '2025-03-01', to: '2025-03-10', limit: 2.5 }, - ]; - for (const args of cases) { - const rec = createRecordingStore({}); - const res = await callQueryData(rec, args); - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "query_data"'); - expect(rec.barsCalls).toHaveLength(0); - expect(rec.universeCalls).toHaveLength(0); - } - - const okRec = createRecordingStore({}); - const ok = await callQueryData(okRec, { - listingIds: tooMany.slice(0, QUERY_DATA_MAX_LISTING_IDS), - from: '2025-03-01', - to: '2025-03-10', - }); - expect(ok.isError).toBe(false); - expect(okRec.barsCalls[0]?.listingIds).toHaveLength(QUERY_DATA_MAX_LISTING_IDS); - }); - - test('from after to maps to MarketDataStoreValidationError with zero store calls', async () => { - const rec = createRecordingStore({}); - const res = await callQueryData(rec, { listingIds: [1], from: '2025-03-10', to: '2025-03-01' }); - expect(res.isError).toBe(true); - expect(res.text).toBe('MarketDataStoreValidationError: Invalid query parameter "from".'); - expect(rec.barsCalls).toHaveLength(0); - }); - - test('exactly limit eligible rows across batches is not truncated; one more is truncated and closes the store stream', async () => { - const base = Date.UTC(2025, 0, 2); - const rowsA = [makeBar(1, base, 1), makeBar(1, base + 1, 2)]; - const rowsB = [makeBar(1, base + 2, 3)]; - - const exact = createRecordingStore({ batches: [{ rows: rowsA }, { rows: rowsB }] }); - const exactRes = await callQueryData(exact, { - listingIds: [1], - from: '2025-01-01', - to: '2025-03-01', - limit: 3, - }); - const exactPayload = JSON.parse(exactRes.text) as QueryDataResultPayload; - expect(exactPayload.rowCount).toBe(3); - expect(exactPayload.truncated).toBe(false); - - const more = createRecordingStore({ - batches: [{ rows: rowsA }, { rows: rowsB }, { rows: [makeBar(1, base + 3, 4)] }, { rows: [makeBar(1, base + 4, 5)] }], - }); - const moreRes = await callQueryData(more, { - listingIds: [1], - from: '2025-01-01', - to: '2025-03-01', - limit: 3, - }); - const morePayload = JSON.parse(moreRes.text) as QueryDataResultPayload; - expect(morePayload.rowCount).toBe(3); - expect(morePayload.truncated).toBe(true); - expect(morePayload.rows.map(r => r.close)).toEqual([1, 2, 3]); - expect(more.iteratorClosed()).toBe(true); - }); - - test('post-cutoff rows dropped by the fence do not count toward the limit or the truncated flag', async () => { - const pre = makeBar(1, Date.UTC(2025, 2, 10), 1); - const leaks = [ - makeBar(1, VAULT_CUTOFF_TS, 9), - makeBar(1, Date.UTC(2025, 2, 11), 9, VAULT_CUTOFF_TS + 5), - makeBar(1, Number.NaN, 9), - ]; - const rec = createRecordingStore({ batches: [{ rows: [pre, ...leaks] }] }); - const res = await callQueryData(rec, { listingIds: [1], from: '2025-03-01', to: '2025-04-30', limit: 1 }); - const payload = JSON.parse(res.text) as QueryDataResultPayload; - expect(payload.rows).toEqual([pre]); - expect(payload.truncated).toBe(false); - expect(res.text).not.toContain('"close":9'); - }); - - test('mid-day Vault cutoff: universe date is the last completed UTC day and bars bounds stay below the cutoff', async () => { - const midDayCutoff = Date.UTC(2025, 2, 31, 12, 0, 0, 0); - const rec = createRecordingStore({ - universeIds: [5], - batches: [{ rows: [makeBar(5, Date.UTC(2025, 2, 31, 11, 0), 1), makeBar(5, midDayCutoff, 2)] }], - }); - const res = await callQueryData( - rec, - { universe: 'US_EQ', from: '2025-03-01', to: '2025-04-30' }, - midDayCutoff - ); - expect(res.isError).toBe(false); - expect(rec.universeCalls).toEqual([{ ref: 'US_EQ', date: '2025-03-30' }]); - const q = rec.barsCalls[0]; - expect(q?.scope).toBe('vault_fenced'); - expect(q?.to).toBe('2025-03-31T11:59:59.999999Z'); - expect(q?.asOf).toBe('2025-03-31T11:59:59.999999Z'); - const payload = JSON.parse(res.text) as QueryDataResultPayload; - expect(payload.rows.every(r => r.ts < midDayCutoff && r.knownAt < midDayCutoff)).toBe(true); - expect(payload.rowCount).toBe(1); - }); - - test('in-fence date-only to with omitted asOf resolves universe on the to date', async () => { - const rec = createRecordingStore({ universeIds: [] }); - const res = await callQueryData(rec, { universe: 'CA_EQ', from: '2025-02-01', to: '2025-03-20' }); - expect(res.isError).toBe(false); - expect(rec.universeCalls).toEqual([{ ref: 'CA_EQ', date: '2025-03-20' }]); - expect(rec.barsCalls).toHaveLength(0); - }); - - test('errors thrown by store.universe are mapped or sanitized and bars is never called', async () => { - const fenceRec = createRecordingStore({ - universeError: new VaultHoldoutFenceError('2025-04-01', VAULT_CUTOFF_TS + 1, VAULT_CUTOFF_TS), - }); - const fenceRes = await callQueryData(fenceRec, { universe: 'US_EQ', from: '2025-03-01', to: '2025-03-20' }); - expect(fenceRes.isError).toBe(true); - expect(fenceRes.text).toContain('VaultHoldoutFenceError'); - expect(fenceRec.barsCalls).toHaveLength(0); - - const crashRec = createRecordingStore({ - universeError: new Error('connect ECONNREFUSED postgres://user:pw@10.0.0.51:5432/trading_bot'), - }); - const crashRes = await callQueryData(crashRec, { universe: 'US_EQ', from: '2025-03-01', to: '2025-03-20' }); - expect(crashRes.isError).toBe(true); - expect(crashRes.text).toBe('Error: Tool execution failed.'); - expect(crashRes.text).not.toContain('postgres://'); - expect(crashRec.barsCalls).toHaveLength(0); - }); - - test('factory rejects invalid store and vault cutoff values eagerly', () => { - const rec = createRecordingStore({}); - for (const bad of [Number.NaN, Number.POSITIVE_INFINITY, 1.5, 8_640_000_000_000_000]) { - expect(() => createQueryDataTool({ store: rec.store, vaultContext: { vaultCutoffTs: bad } })).toThrow( - /vaultCutoffTs/ - ); - } - expect(() => - createQueryDataTool({ - store: {} as MarketDataStore, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }) - ).toThrow(/store/); - }); -}); diff --git a/libs/research/test/mcp-event-study-qa.test.ts b/libs/research/test/mcp-event-study-qa.test.ts deleted file mode 100644 index fca76a34..00000000 --- a/libs/research/test/mcp-event-study-qa.test.ts +++ /dev/null @@ -1,1116 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import type { EventStudyExchangeCalendars } from '../src/event-panel'; -import type { - BarBatch, - BarRecord, - EventKind, - MarketDataStore, - Table, - TableRow, -} from '../src/market-data-store'; -import { - type BarsQuery, - EVENTS_COLUMNS, - type EventsQuery, - MarketDataStoreNotImplementedError, - type UniverseQuery, -} from '../src/market-data-store-duckdb'; -import { - type EventStudyExchangeCalendarQuery, - type EventStudyResultPayload, - createEventStudyTool, - createMcpServer, -} from '../src/mcp/index'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; - -// QA fixture: deterministic synthetic equity bars & events with explicit -// half-day closes, intraday Vault cutoffs, exact boundary timestamps, and -// malformed rows. Models gross daily close-to-close returns, raw adjustment, -// no fills or transaction costs. -const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = []; - const current = new Date(`${startDate}T00:00:00.000Z`); - while (out.length < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out.push(current.toISOString().slice(0, 10)); - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function utcMs(date: string, hour: number, minute = 0, second = 0, ms = 0): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hour, minute, second, ms); -} - -function createFakeLedger(): { - executor: TrialLedgerExecutor; - insertCalls: number; - rows: Array<{ expression_hash: string; daily_series: number[] }>; -} { - const rows: Array<{ expression_hash: string; daily_series: number[] }> = []; - let nextId = 1; - const state = { - rows, - insertCalls: 0, - executor: null as unknown as TrialLedgerExecutor, - }; - - state.executor = { - async query>(text: string, params?: readonly unknown[]) { - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - state.insertCalls += 1; - const p = params ?? []; - const id = nextId++; - const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); - rows.push({ - expression_hash: p[6] as string, - daily_series: dailySeries, - }); - return { - rows: [ - { - trial_id: String(id), - created_at: new Date(Date.UTC(2024, 5, 1, 12, 0, id)), - } as unknown as Row, - ], - rowCount: 1, - }; - } - if (trimmed.startsWith('SELECT')) { - const storedRows = rows.map((r, idx) => ({ - trial_id: String(idx + 1), - created_at: new Date(Date.UTC(2024, 5, 1, 12, 0, idx + 1)), - principal_id: AGENT_PRINCIPAL, - campaign_id: null, - stage: 'event_study', - universe_market: 'US_EQ', - horizon_bucket: 'swing_1_10d', - hypothesis_id: null, - expression_hash: r.expression_hash, - sample_start: '2023-01-02', - sample_end: '2023-02-01', - n_obs: r.daily_series.length, - sharpe_unann: 0.5, - skewness: 0, - kurtosis: 3, - daily_series: r.daily_series, - })); - return { rows: storedRows as unknown as Row[], rowCount: storedRows.length }; - } - return { rows: [], rowCount: 0 }; - }, - }; - - return state; -} - -function createPassThroughStore(params: { - bars: readonly BarRecord[]; - eventsTable: Table; -}): MarketDataStore { - return { - bars(_q: BarsQuery): AsyncIterable { - return { - async *[Symbol.asyncIterator]() { - yield { rows: [...params.bars] }; - }, - }; - }, - async events(_q: EventsQuery): Promise
{ - return params.eventsTable; - }, - async universe(_q: UniverseQuery): Promise { - return []; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; -} - -async function invoke( - server: ReturnType, - args: Record -): Promise<{ - isError?: boolean; - text: string; - payload?: EventStudyResultPayload; -}> { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/call', - params: { name: 'event_study', arguments: args }, - }) - ); - const rpc = JSON.parse(raw!) as { - result: { content: Array<{ type: string; text: string }>; isError?: boolean }; - }; - const text = rpc.result.content[0]!.text; - return { - isError: rpc.result.isError, - text, - payload: rpc.result.isError ? undefined : (JSON.parse(text) as EventStudyResultPayload), - }; -} - -describe('MCP event_study QA edge cases', () => { - test('event released after a half-day close anchors to the next trading session, not the half-day', async () => { - const dates = makeBusinessDates('2023-05-01', 25); - const vaultCutoffDate = dates[24]!; - const vaultCutoffTs = utcMs(vaultCutoffDate, 0); - const listingIds = [101, 102, 103, 104, 105, 106]; - - // Make day index 8 a half-day (closes at 18:00 UTC = 13:00 ET instead of 21:00 UTC). - // Place 6 events across days 8 and 14, released at 19:00 UTC (after 18:00 UTC half-day close, - // before 21:00 UTC bar stamp). For half-day (index 8), events must anchor to index 9! - // Put a +10% jump on index 9 and +20% jump on index 15 (next day after 14, also half-day), - // and 0% return on index 8 and 14 so AAR at offset 0 proves next-session anchoring. - const halfDayIndices = new Set([8, 14]); - const jumpDayReturns = new Map([ - [9, 0.1], - [15, 0.2], - ]); - - const bars: BarRecord[] = []; - for (const id of listingIds) { - let price = 100; - for (let t = 0; t < 24; t += 1) { - const ret = jumpDayReturns.get(t) ?? 0; - price = Number((price * (1 + ret)).toFixed(6)); - const ts = utcMs(dates[t]!, 21); // bars_1d always stamped 16:00 ET (21:00 UTC) - bars.push({ - listingId: id, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 10_000, - knownAt: ts, - }); - } - } - - const eventRows: TableRow[] = []; - for (let i = 0; i < 3; i += 1) { - // Released at 19:00 UTC on half-day index 8 -> anchors to index 9 (+10%) - eventRows.push({ - listing_id: listingIds[i]!, - ts: utcMs(dates[8]!, 19), - known_at: utcMs(dates[8]!, 19), - known_at_source: 'exact', - kind: 'filing' as EventKind, - subtype: '8-K', - payload_json: '{}', - }); - } - for (let i = 3; i < 6; i += 1) { - // Released at 19:00 UTC on half-day index 14 -> anchors to index 15 (+20%) - eventRows.push({ - listing_id: listingIds[i]!, - ts: utcMs(dates[14]!, 19), - known_at: utcMs(dates[14]!, 19), - known_at_source: 'exact', - kind: 'filing' as EventKind, - subtype: '8-K', - payload_json: '{}', - }); - } - - const store = createPassThroughStore({ - bars, - eventsTable: { columns: [...EVENTS_COLUMNS], rows: eventRows }, - }); - const ledger = createFakeLedger(); - - const resolveExchangeCalendars = async ( - q: EventStudyExchangeCalendarQuery - ): Promise => { - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map((date, _idx) => { - const globalIdx = dates.indexOf(date); - const closeHour = halfDayIndices.has(globalIdx) ? 18 : 21; - return { date, closeTs: utcMs(date, closeHour) }; - }); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { - calendars: new Map([['XNYS', sessions]]), - listingCalendarId, - }; - }; - - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - - const res = await invoke(server, { - listingIds, - from: dates[0]!, - to: dates[23]!, - event: { kinds: ['filing'] }, - preDays: 1, - postDays: 1, - benchmark: 'none', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(res.isError).toBeUndefined(); - expect(res.payload?.status).toBe('ok'); - if (res.payload?.status !== 'ok') { - throw new Error('Expected ok'); - } - - // Offset -1 is the half-day itself (0% return); Offset 0 is the next session (mean of +10% and +20% = +15%). - const offsetMinus1 = res.payload.study.offsets.find(o => o.offset === -1)!; - const offset0 = res.payload.study.offsets.find(o => o.offset === 0)!; - expect(offsetMinus1.aar).toBeCloseTo(0, 8); - expect(offset0.aar).toBeCloseTo(0.15, 8); - }); - - test('intraday Vault cutoff excludes rows on the cutoff UTC day and handles start-on-cutoff-day safely', async () => { - const dates = makeBusinessDates('2023-06-01', 25); - const cutoffDate = dates[20]!; - // Intraday Vault cutoff at 12:00 UTC on cutoffDate - const vaultCutoffTs = utcMs(cutoffDate, 12); - const listingIds = [201, 202, 203, 204, 205, 206]; - - const bars: BarRecord[] = []; - for (const id of listingIds) { - let price = 50; - for (let t = 0; t < 22; t += 1) { - price = Number((price * (1 + (t % 3 === 0 ? 0.02 : -0.005))).toFixed(6)); - const ts = t === 20 ? utcMs(dates[t]!, 10) : utcMs(dates[t]!, 21); // Bar on cutoff day at 10:00 UTC (< cutoffTs!) - bars.push({ - listingId: id, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 5_000, - knownAt: ts, - }); - } - } - - const baseEvents: TableRow[] = [ - // 6 valid pre-cutoff events across 2 dates - ...listingIds.slice(0, 3).map(id => ({ - listing_id: id, - ts: utcMs(dates[6]!, 14), - known_at: utcMs(dates[6]!, 14), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - })), - ...listingIds.slice(3, 6).map(id => ({ - listing_id: id, - ts: utcMs(dates[12]!, 14), - known_at: utcMs(dates[12]!, 14), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - })), - ]; - - const intradayCutoffEvents: TableRow[] = [ - // Event on cutoff UTC day BEFORE intraday vaultCutoffTs (10:00 UTC < 12:00 UTC) -> MUST be excluded! - { - listing_id: listingIds[0]!, - ts: utcMs(cutoffDate, 10), - known_at: utcMs(cutoffDate, 10), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Valid ts earlier, but known_at on cutoff UTC day at 09:00 UTC (< 12:00 UTC) -> MUST be excluded! - { - listing_id: listingIds[1]!, - ts: utcMs(dates[10]!, 14), - known_at: utcMs(cutoffDate, 9), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Unrequested valid kind on cutoff day -> MUST NOT inflate vaultExcludedEvents - { - listing_id: listingIds[2]!, - ts: utcMs(cutoffDate, 10), - known_at: utcMs(cutoffDate, 10), - known_at_source: 'exact', - kind: 'ceo_post', - subtype: null, - payload_json: '{}', - }, - ]; - - const calendarCalls: EventStudyExchangeCalendarQuery[] = []; - const resolveExchangeCalendars = async ( - q: EventStudyExchangeCalendarQuery - ): Promise => { - calendarCalls.push(q); - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map(date => ({ date, closeTs: utcMs(date, 21) })); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; - }; - - const store = createPassThroughStore({ - bars, - eventsTable: { - columns: [...EVENTS_COLUMNS], - rows: [...baseEvents, ...intradayCutoffEvents], - }, - }); - const ledger = createFakeLedger(); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - - const res = await invoke(server, { - listingIds, - from: dates[0]!, - to: dates[21]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 2, - benchmark: 'none', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(res.payload?.status).toBe('ok'); - expect(res.payload?.vaultExcludedEvents).toBe(2); - expect(res.payload?.panelDiagnostics.vaultExcludedDates).toBe(2); - expect(res.payload?.eventCount).toBe(6); - expect(calendarCalls[0]!.toDate < cutoffDate).toBe(true); - - // Request starting on the intraday cutoff day before vaultCutoffTs: - // returns insufficient_data cleanly without calling calendar resolver with inverted dates. - calendarCalls.length = 0; - const ledger2 = createFakeLedger(); - const server2 = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store, - ledger: ledger2.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - - const startOnCutoffRes = await invoke(server2, { - listingIds, - from: `${cutoffDate}T01:00:00.000Z`, - to: `${cutoffDate}T11:00:00.000Z`, - event: { kinds: ['filing'] }, - preDays: 1, - postDays: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(startOnCutoffRes.isError).toBeUndefined(); - expect(startOnCutoffRes.payload?.status).toBe('insufficient_data'); - expect(calendarCalls).toHaveLength(0); - expect(ledger2.insertCalls).toBe(0); - }); - - test('exact boundary timestamps (fromMs, toMs, asOfMs) and malformed ts rejection', async () => { - const dates = makeBusinessDates('2023-07-03', 20); - const vaultCutoffDate = dates[19]!; - const vaultCutoffTs = utcMs(vaultCutoffDate, 0); - const listingIds = [301, 302, 303, 304, 305, 306]; - - const bars: BarRecord[] = []; - for (const id of listingIds) { - let price = 30; - for (let t = 0; t < 19; t += 1) { - price = Number((price * (1 + (t % 2 === 0 ? 0.015 : -0.005))).toFixed(6)); - const ts = utcMs(dates[t]!, 21); - bars.push({ - listingId: id, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 1_000, - knownAt: ts, - }); - } - } - - const fromIso = `${dates[2]}T00:00:00.000Z`; - const toIso = `${dates[15]}T23:59:59.999Z`; - const asOfIso = `${dates[14]}T21:00:00.000Z`; - const fromMs = Date.parse(fromIso); - const toMs = Date.parse(toIso); - const asOfMs = Date.parse(asOfIso); - - const rows: TableRow[] = [ - // Exact fromMs -> included - { - listing_id: listingIds[0]!, - ts: fromMs, - known_at: fromMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // fromMs - 1 -> excluded - { - listing_id: listingIds[1]!, - ts: fromMs - 1, - known_at: fromMs - 1, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Exact asOfMs -> included - { - listing_id: listingIds[2]!, - ts: utcMs(dates[10]!, 14), - known_at: asOfMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // asOfMs + 1 -> excluded - { - listing_id: listingIds[3]!, - ts: utcMs(dates[10]!, 14), - known_at: asOfMs + 1, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // toMs + 1 -> excluded - { - listing_id: listingIds[4]!, - ts: toMs + 1, - known_at: asOfMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - ]; - - const resolveExchangeCalendars = async ( - q: EventStudyExchangeCalendarQuery - ): Promise => { - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map(date => ({ date, closeTs: utcMs(date, 21) })); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; - }; - - const store = createPassThroughStore({ - bars, - eventsTable: { columns: [...EVENTS_COLUMNS], rows }, - }); - const ledger = createFakeLedger(); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - - const res = await invoke(server, { - listingIds, - from: fromIso, - to: toIso, - asOf: asOfIso, - event: { kinds: ['filing'] }, - preDays: 1, - postDays: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - // Only 2 events survived the exact boundaries (fromMs and asOfMs) -> insufficient_data (< 5) - expect(res.payload?.status).toBe('insufficient_data'); - expect(res.payload?.eventCount).toBe(2); - expect(ledger.insertCalls).toBe(0); - - // Malformed `ts` on an otherwise eligible event row must fail with sanitized EventPanelError - const malformedStore = createPassThroughStore({ - bars, - eventsTable: { - columns: [...EVENTS_COLUMNS], - rows: [ - { - listing_id: listingIds[0]!, - ts: 'not-a-timestamp' as unknown as number, - known_at: fromMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - ], - }, - }); - const malformedLedger = createFakeLedger(); - const malformedServer = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: malformedStore, - ledger: malformedLedger.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - - const badRes = await invoke(malformedServer, { - listingIds, - from: fromIso, - to: toIso, - asOf: asOfIso, - event: { kinds: ['filing'] }, - preDays: 1, - postDays: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(badRes.isError).toBe(true); - expect(badRes.text).toBe('EventPanelError: Event table data failed event panel validation.'); - expect(malformedLedger.insertCalls).toBe(0); - }); - - test('microsecond-precision from rejects leaked boundary-millisecond event and matches clean run', async () => { - const dates = makeBusinessDates('2023-07-03', 24); - const vaultCutoffDate = dates[23]!; - const vaultCutoffTs = utcMs(vaultCutoffDate, 0); - const listingIds = [401, 402, 403, 404, 405, 406]; - - const bars: BarRecord[] = []; - for (let l = 0; l < listingIds.length; l += 1) { - const id = listingIds[l]!; - let price = 40 + l * 2; - for (let t = 0; t < 23; t += 1) { - // Distinct per-listing returns on dates[3] so admitting listingIds[1] at .123Z - // measurably shifts eventCount, eventsUsed, CAR, and ledger daily_series. - const ret = - t === 3 - ? l === 1 - ? 0.25 - : 0.05 - : t === 9 - ? 0.03 + l * 0.004 - : t === 15 - ? -0.02 + l * 0.003 - : 0.002; - price = Number((price * (1 + ret)).toFixed(6)); - const ts = utcMs(dates[t]!, 21); - bars.push({ - listingId: id, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 10_000, - knownAt: ts, - }); - } - } - - // Researcher sets microsecond-precision start on half-day dates[2] (18:00 UTC close, 21:00 UTC bar stamp): - // bars from dates[2]..dates[22] enter the panel, so dates[3] (session index 1) has finite close-to-close returns. - // A leaked filing at 19:00:00.123Z (< .123456Z) would anchor to dates[3] and shift CAR/daily_series if admitted. - // A valid filing at 19:00:00.124Z (> .123456Z) must be admitted and anchored to dates[3]. - const microFromIso = `${dates[2]}T19:00:00.123456Z`; - const leakedBoundaryMs = Date.parse(`${dates[2]}T19:00:00.123Z`); - const admittedNextMs = Date.parse(`${dates[2]}T19:00:00.124Z`); - - const validRows: TableRow[] = [ - // Admitted event at fromMs + 1 (.124Z) -> anchors to dates[3] (after dates[2] 18:00 UTC half-day close) - { - listing_id: listingIds[0]!, - ts: admittedNextMs, - known_at: admittedNextMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // 3 events on dates[9] - ...listingIds.slice(0, 3).map(id => ({ - listing_id: id, - ts: utcMs(dates[9]!, 14), - known_at: utcMs(dates[9]!, 14), - known_at_source: 'exact', - kind: 'filing' as EventKind, - subtype: '8-K', - payload_json: '{}', - })), - // 3 events on dates[15] - ...listingIds.slice(3, 6).map(id => ({ - listing_id: id, - ts: utcMs(dates[15]!, 14), - known_at: utcMs(dates[15]!, 14), - known_at_source: 'exact', - kind: 'filing' as EventKind, - subtype: '8-K', - payload_json: '{}', - })), - ]; - - // Leaked out-of-window filing at .123Z (strictly before .123456Z) on listingIds[1] (+25% on dates[3]). - const leakedRow: TableRow = { - listing_id: listingIds[1]!, - ts: leakedBoundaryMs, - known_at: leakedBoundaryMs, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }; - - const resolveExchangeCalendars = async ( - q: EventStudyExchangeCalendarQuery - ): Promise => { - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map(date => ({ - date, - closeTs: utcMs(date, date === dates[2] ? 18 : 21), - })); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; - }; - - const runWithRows = async (rows: readonly TableRow[]) => { - const store = createPassThroughStore({ - bars, - eventsTable: { columns: [...EVENTS_COLUMNS], rows: [...rows] }, - }); - const ledger = createFakeLedger(); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars, - }), - ], - }); - const res = await invoke(server, { - listingIds, - from: microFromIso, - to: dates[22]!, - event: { kinds: ['filing'] }, - preDays: 0, - postDays: 1, - benchmark: 'none', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - return { res, ledger }; - }; - - const leaky = await runWithRows([leakedRow, ...validRows]); - const clean = await runWithRows(validRows); - - expect(leaky.res.isError).toBeUndefined(); - expect(clean.res.isError).toBeUndefined(); - expect(leaky.res.payload?.status).toBe('ok'); - expect(clean.res.payload?.status).toBe('ok'); - if (leaky.res.payload?.status !== 'ok' || clean.res.payload?.status !== 'ok') { - throw new Error('Expected ok payloads'); - } - - // Leaked .123Z row must be excluded; admitted .124Z row + 6 later events = 7 anchored & used events. - expect(leaky.res.payload.eventCount).toBe(7); - expect(clean.res.payload.eventCount).toBe(7); - expect(leaky.res.payload.study.diagnostics.eventsUsed).toBe(7); - expect(clean.res.payload.study.diagnostics.eventsUsed).toBe(7); - expect(leaky.res.payload.study.offsets).toEqual(clean.res.payload.study.offsets); - expect(leaky.res.payload.trial.expressionHash).toBe(clean.res.payload.trial.expressionHash); - expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series); - }); -}); - -// --------------------------------------------------------------------------- -// Quant QA additions (T-133): exact benchmark economics, late-revised bars, -// subtype-filter accounting, resolver contract edges, and microsecond upper bounds. -// Fixture "qa-t133-v1": 6 listings, weekday sessions, flat prices except -// explicit jump days; gross close-to-close returns, raw adjustment, no costs. -// --------------------------------------------------------------------------- - -const QA_LISTINGS = [701, 702, 703, 704, 705, 706]; - -function qaXnysResolver(dates: readonly string[]) { - const calls: EventStudyExchangeCalendarQuery[] = []; - const resolve = (q: EventStudyExchangeCalendarQuery): EventStudyExchangeCalendars => { - calls.push(q); - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map(date => ({ date, closeTs: utcMs(date, 21) })); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { calendars: new Map([['XNYS', sessions]]), listingCalendarId }; - }; - return { calls, resolve }; -} - -/** Flat 100 prices; `jumps` maps `${listingIndex}:${dayIndex}` -> daily return. */ -function qaBars(dates: readonly string[], days: number, jumps: ReadonlyMap) { - const bars: BarRecord[] = []; - for (let l = 0; l < QA_LISTINGS.length; l += 1) { - let price = 100; - for (let t = 0; t < days; t += 1) { - price = Number((price * (1 + (jumps.get(`${l}:${t}`) ?? 0))).toFixed(6)); - const ts = utcMs(dates[t]!, 21); - bars.push({ - listingId: QA_LISTINGS[l]!, - ts, - open: price, - high: price, - low: price, - close: price, - volume: 1_000, - knownAt: ts, - }); - } - } - return bars; -} - -function qaEvent(l: number, ts: number, extra?: Partial): TableRow { - return { - listing_id: QA_LISTINGS[l]!, - ts, - known_at: ts, - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - ...extra, - }; -} - -function qaServer(params: { - bars: readonly BarRecord[]; - rows: readonly TableRow[]; - vaultCutoffTs: number; - resolveExchangeCalendars: ( - q: EventStudyExchangeCalendarQuery - ) => EventStudyExchangeCalendars | Promise; -}) { - const ledger = createFakeLedger(); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: createPassThroughStore({ - bars: params.bars, - eventsTable: { columns: [...EVENTS_COLUMNS], rows: [...params.rows] }, - }), - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: params.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: params.resolveExchangeCalendars, - }), - ], - }); - return { server, ledger }; -} - -describe('MCP event_study QA additions', () => { - // Day 6: listings 0-2 get +10% with events; day 12: listings 3-5 get +20% with events. - // Other listings are flat, so the equal-weight benchmark on day 6 is 0.05 and on day 12 is 0.10. - const dates = makeBusinessDates('2023-03-01', 22); - const vaultCutoffTs = utcMs(dates[21]!, 0); - const jumps = new Map([ - ['0:6', 0.1], - ['1:6', 0.1], - ['2:6', 0.1], - ['3:12', 0.2], - ['4:12', 0.2], - ['5:12', 0.2], - ]); - const bars = qaBars(dates, 21, jumps); - const eventRows: TableRow[] = [ - ...[0, 1, 2].map(l => qaEvent(l, utcMs(dates[6]!, 14))), - ...[3, 4, 5].map(l => qaEvent(l, utcMs(dates[12]!, 14))), - ]; - const baseArgs = { - listingIds: QA_LISTINGS, - from: dates[0]!, - to: dates[20]!, - event: { kinds: ['filing'] }, - preDays: 1, - postDays: 1, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - test('benchmark "none" reports raw event-day returns and "equal_weight" subtracts the cross-sectional mean', async () => { - const none = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - const ew = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - - const resNone = await invoke(none.server, { ...baseArgs, benchmark: 'none' }); - const resEw = await invoke(ew.server, { ...baseArgs, benchmark: 'equal_weight' }); - - if (resNone.payload?.status !== 'ok' || resEw.payload?.status !== 'ok') { - throw new Error(`Expected ok payloads: ${resNone.text} | ${resEw.text}`); - } - const at = (p: typeof resNone.payload, offset: number) => - p.study.offsets.find(o => o.offset === offset)!; - - // none: mean(+10% x3, +20% x3) = 0.15; flat neighbours. - expect(at(resNone.payload, 0).aar).toBeCloseTo(0.15, 10); - expect(at(resNone.payload, -1).aar).toBeCloseTo(0, 10); - expect(at(resNone.payload, 1).aar).toBeCloseTo(0, 10); - // equal_weight: mean(0.10-0.05 x3, 0.20-0.10 x3) = 0.075. - expect(at(resEw.payload, 0).aar).toBeCloseTo(0.075, 10); - expect(at(resEw.payload, 0).n).toBe(6); - expect(resNone.payload.study.hasBenchmark).toBe(false); - expect(resEw.payload.study.hasBenchmark).toBe(true); - expect(none.ledger.insertCalls).toBe(1); - expect(ew.ledger.insertCalls).toBe(1); - expect(resNone.payload.trial.expressionHash).not.toBe(resEw.payload.trial.expressionHash); - }); - - test('a late-revised bar (knownAt > asOf) leaked by the store is dropped before the panel', async () => { - const asOfIso = `${dates[18]!}T21:00:00.000Z`; - // Same (listing, ts) as an original bar but a different close and knownAt after asOf. - // If admitted, the panel would throw duplicate_bar or change returns. - const revised: BarRecord = { - ...bars.find(b => b.listingId === QA_LISTINGS[0] && b.ts === utcMs(dates[6]!, 21))!, - close: 999, - open: 999, - high: 999, - low: 999, - knownAt: utcMs(dates[19]!, 12), - }; - const clean = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - const leaky = qaServer({ - bars: [...bars, revised], - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - - const resClean = await invoke(clean.server, { ...baseArgs, asOf: asOfIso, benchmark: 'none' }); - const resLeaky = await invoke(leaky.server, { ...baseArgs, asOf: asOfIso, benchmark: 'none' }); - - expect(resLeaky.isError).toBeUndefined(); - if (resLeaky.payload?.status !== 'ok' || resClean.payload?.status !== 'ok') { - throw new Error(`Expected ok payloads: ${resLeaky.text}`); - } - expect(resLeaky.payload.study.offsets).toEqual(resClean.payload.study.offsets); - expect(resLeaky.payload.panelDiagnostics).toEqual(resClean.payload.panelDiagnostics); - expect(leaky.ledger.rows[0]!.daily_series).toEqual(clean.ledger.rows[0]!.daily_series); - }); - - test('subtype filter drops null and non-matching subtypes (even in the Vault) without counting Vault exclusions', async () => { - const noise: TableRow[] = [ - qaEvent(0, utcMs(dates[9]!, 14), { subtype: null }), - qaEvent(1, utcMs(dates[9]!, 14), { subtype: '10-Q' }), - // Non-matching subtype on the cutoff day: filtered as unrequested, not as a Vault exclusion. - qaEvent(2, utcMs(dates[21]!, 14), { subtype: '10-K' }), - // Matching subtype on the cutoff day: a genuine Vault exclusion. - qaEvent(3, utcMs(dates[21]!, 14)), - ]; - const { server, ledger } = qaServer({ - bars, - rows: [...eventRows, ...noise], - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - - const res = await invoke(server, { - ...baseArgs, - event: { kinds: ['filing'], subtypes: ['8-K'] }, - benchmark: 'none', - }); - - if (res.payload?.status !== 'ok') { - throw new Error(`Expected ok: ${res.text}`); - } - expect(res.payload.eventCount).toBe(6); - expect(res.payload.vaultExcludedEvents).toBe(1); - expect(res.payload.event.subtypes).toEqual(['8-K']); - expect(res.payload.study.offsets.find(o => o.offset === 0)!.aar).toBeCloseTo(0.15, 10); - expect(ledger.insertCalls).toBe(1); - }); - - test('synchronous calendar resolver is accepted and a non-Error throw maps to the fixed resolver message', async () => { - const sync = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - const syncRes = await invoke(sync.server, { ...baseArgs, benchmark: 'none' }); - expect(syncRes.payload?.status).toBe('ok'); - - const SECRET = 'SECRET_CAL_DSN_55120'; - const failing = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: () => { - throw `postgres://calendar:${SECRET}@db/cal`; - }, - }); - const failRes = await invoke(failing.server, { ...baseArgs, benchmark: 'none' }); - expect(failRes.isError).toBe(true); - expect(failRes.text).toBe('Error: Exchange calendar resolution failed.'); - expect(failRes.text).not.toContain(SECRET); - expect(failing.ledger.insertCalls).toBe(0); - - const rejecting = qaServer({ - bars, - rows: eventRows, - vaultCutoffTs, - resolveExchangeCalendars: () => Promise.reject(new TypeError(`/srv/cal/${SECRET}.parquet`)), - }); - const rejectRes = await invoke(rejecting.server, { ...baseArgs, benchmark: 'none' }); - expect(rejectRes.isError).toBe(true); - expect(rejectRes.text).toBe('Error: Exchange calendar resolution failed.'); - expect(rejectRes.text).not.toContain(SECRET); - }); - - test('microsecond-precision to/asOf keep rows at the boundary millisecond and drop the next millisecond', async () => { - // to/asOf at dates[14] 15:00:00.123456Z. Base events (days 6, 12) are inside the window. - const boundaryIso = `${dates[14]!}T15:00:00.123456Z`; - const boundaryMs = Date.parse(`${dates[14]!}T15:00:00.123Z`); - const extra: TableRow[] = [ - qaEvent(0, boundaryMs), // ts == toMs, known_at == asOfMs (.123 <= .123456) -> kept - qaEvent(1, boundaryMs + 1), // .124 > .123456 -> dropped - qaEvent(2, utcMs(dates[10]!, 14), { known_at: boundaryMs + 1 }), // known after asOf -> dropped - ]; - const { server } = qaServer({ - bars, - rows: [...eventRows, ...extra], - vaultCutoffTs, - resolveExchangeCalendars: qaXnysResolver(dates).resolve, - }); - - const res = await invoke(server, { - ...baseArgs, - to: boundaryIso, - asOf: boundaryIso, - benchmark: 'none', - }); - - expect(res.isError).toBeUndefined(); - expect(res.payload?.effectiveTo).toBe(boundaryIso); - expect(res.payload?.effectiveAsOf).toBe(boundaryIso); - // The boundary-ms event passes the defensive filter and reaches the panel, which drops it - // as after-last-session (its dates[14] close is after asOf). The .124 rows never reach the - // panel: if they did, droppedAfterLastSession would be > 1 or eventCount would change. - expect(res.payload?.panelDiagnostics.droppedAfterLastSession).toBe(1); - expect(res.payload?.eventCount).toBe(6); - expect(res.payload?.study.diagnostics.eventsUsed).toBe(6); - expect(res.payload?.vaultExcludedEvents).toBe(0); - }); -}); diff --git a/libs/research/test/mcp-event-study.test.ts b/libs/research/test/mcp-event-study.test.ts deleted file mode 100644 index 30729c3b..00000000 --- a/libs/research/test/mcp-event-study.test.ts +++ /dev/null @@ -1,1451 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - EventPanelError, - type EventStudyExchangeCalendars, - buildEventStudyInput, - eventsTableToEventRows, -} from '../src/event-panel'; -import { - type BarBatch, - type BarRecord, - type EventKind, - type MarketDataStore, - MarketDataStoreValidationError, - type Table, - type TableRow, - VaultHoldoutFenceError, - VaultScopeNotAuthorizedError, -} from '../src/market-data-store'; -import { - AdjFactorsSnapshotError, - type BarsQuery, - EVENTS_COLUMNS, - type EventsQuery, - MarketDataStoreNotImplementedError, - type UniverseQuery, -} from '../src/market-data-store-duckdb'; -import { - EVENT_STUDY_MAX_LISTING_IDS, - EVENT_STUDY_MAX_POST_DAYS, - EVENT_STUDY_MAX_PRE_DAYS, - EVENT_STUDY_MAX_SUBTYPES, - EVENT_STUDY_MAX_SUBTYPE_LENGTH, - type EventStudyExchangeCalendarQuery, - type EventStudyResultPayload, - createEventStudyTool, - createMcpServer, -} from '../src/mcp/index'; -import { SignalStudyError, runEventStudy } from '../src/signal-study'; -import { TrialLedgerError, type TrialLedgerExecutor } from '../src/trial-ledger'; - -// Synthetic fixture: seeded (20261201) 8 listings, 60 pre-cutoff + 8 post-cutoff -// business sessions from 2022-11-01, daily close-to-close returns, raw adjustment, -// no fills or transaction costs, XNYS 21:00 UTC close calendar. -const SEED = 20261201; -const AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; -const CAMPAIGN_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; -const HYPOTHESIS_UUID = '12345678-1234-4123-8123-123456789abc'; - -function createSeededRng(seed: number): () => number { - let state = seed >>> 0; - return () => { - state = (state + 0x6d2b79f5) >>> 0; - let t = Math.imul(state ^ (state >>> 15), 1 | state); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296; - }; -} - -function makeBusinessDates(startDate: string, count: number): string[] { - const out: string[] = new Array(count); - const current = new Date(`${startDate}T00:00:00.000Z`); - let written = 0; - while (written < count) { - const day = current.getUTCDay(); - if (day !== 0 && day !== 6) { - out[written] = current.toISOString().slice(0, 10); - written += 1; - } - current.setUTCDate(current.getUTCDate() + 1); - } - return out; -} - -function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0): number { - const [y, m, d] = date.split('-').map(Number); - return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, 0); -} - -function parseBound(raw: string, endOfDay: boolean): number { - if (raw.length === 10) { - return Date.parse(`${raw}T${endOfDay ? '23:59:59.999' : '00:00:00.000'}Z`); - } - return Date.parse(raw); -} - -interface StoredTrialRow { - readonly trial_id: string; - readonly created_at: Date; - readonly principal_id: string; - readonly campaign_id: string | null; - readonly stage: string; - readonly universe_market: string; - readonly horizon_bucket: string; - readonly hypothesis_id: string | null; - readonly expression_hash: string; - readonly sample_start: string; - readonly sample_end: string; - readonly n_obs: number; - readonly sharpe_unann: number; - readonly skewness: number; - readonly kurtosis: number; - readonly daily_series: readonly number[]; -} - -function createFakeTrialLedger(options?: { - insertError?: Error; - dsrReadError?: Error; -}): { - executor: TrialLedgerExecutor; - rows: StoredTrialRow[]; - insertCalls: number; - selectCalls: number; -} { - const rows: StoredTrialRow[] = []; - let nextTrialId = 1; - const state = { - rows, - insertCalls: 0, - selectCalls: 0, - executor: null as unknown as TrialLedgerExecutor, - }; - - state.executor = { - async query>(text: string, params?: readonly unknown[]) { - const trimmed = text.trimStart(); - if (trimmed.startsWith('INSERT INTO trial_ledger')) { - state.insertCalls += 1; - if (options?.insertError !== undefined) { - throw options.insertError; - } - const p = params ?? []; - const trialId = nextTrialId++; - const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId)); - const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); - const stored: StoredTrialRow = { - trial_id: String(trialId), - created_at: createdAt, - principal_id: p[0] as string, - campaign_id: (p[1] as string | null) ?? null, - stage: p[2] as string, - universe_market: p[3] as string, - horizon_bucket: p[4] as string, - hypothesis_id: (p[5] as string | null) ?? null, - expression_hash: p[6] as string, - sample_start: p[7] as string, - sample_end: p[8] as string, - n_obs: p[9] as number, - sharpe_unann: p[10] as number, - skewness: p[11] as number, - kurtosis: p[12] as number, - daily_series: dailySeries, - }; - rows.push(stored); - return { - rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row], - rowCount: 1, - }; - } - - if (trimmed.startsWith('SELECT')) { - state.selectCalls += 1; - if (options?.dsrReadError !== undefined) { - throw options.dsrReadError; - } - if (text.includes('WHERE trial_id = $1::bigint')) { - const targetId = String(params?.[0]); - const matched = rows.filter(r => r.trial_id === targetId); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - if (text.includes('WHERE universe_market = $1')) { - const market = params?.[0] as string; - const bucket = params?.[1] as string; - const matched = rows.filter( - r => r.universe_market === market && r.horizon_bucket === bucket - ); - return { rows: matched as unknown as Row[], rowCount: matched.length }; - } - } - - return { rows: [], rowCount: 0 }; - }, - }; - - return state; -} - -interface SyntheticEventFixture { - readonly listingIds: number[]; - readonly allDates: string[]; - readonly vaultCutoffDate: string; - readonly vaultCutoffTs: number; - readonly bars: BarRecord[]; - readonly eventsTable: Table; -} - -function buildSyntheticEventFixture(options?: { - preCutoffSessions?: number; - postCutoffSessions?: number; - listingCount?: number; - zeroVariance?: boolean; -}): SyntheticEventFixture { - const rand = createSeededRng(SEED); - const listingCount = options?.listingCount ?? 8; - const preCutoffSessions = options?.preCutoffSessions ?? 65; - const postCutoffSessions = options?.postCutoffSessions ?? 8; - const zeroVariance = options?.zeroVariance ?? false; - - const allDates = makeBusinessDates('2022-11-01', preCutoffSessions + postCutoffSessions); - const vaultCutoffDate = allDates[preCutoffSessions]!; - const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0); - const listingIds = Array.from({ length: listingCount }, (_, i) => 60_001 + i); - - const bars: BarRecord[] = []; - const eventRows: TableRow[] = []; - const prices = Array.from({ length: listingCount }, (_, i) => 20 + i * 3); - - // Place filings across multiple pre-cutoff dates (well inside window) and some post-cutoff. - const eventDayIndices = [12, 18, 26, 34, 42, 50]; - const eventSet = new Set(); - for (let eIdx = 0; eIdx < eventDayIndices.length; eIdx += 1) { - const t = eventDayIndices[eIdx]!; - if (t >= preCutoffSessions) { - continue; - } - // 2 listings per event date => 12 events across 6 distinct dates (spans pre and post 2023-01-01) - for (let k = 0; k < 2; k += 1) { - const l = (eIdx * 2 + k) % listingCount; - eventSet.add(`${t}:${l}`); - const date = allDates[t]!; - const ts = makeUtcMs(date, 14); // 09:00 ET intraday filing -> anchors on same session - const kind: EventKind = eIdx % 2 === 0 ? 'filing' : 'earnings'; - const subtype = kind === 'filing' ? '8-K' : 'Q4'; - eventRows.push({ - listing_id: listingIds[l]!, - ts, - known_at: ts, - known_at_source: 'exact', - kind, - subtype, - payload_json: '{}', - }); - } - } - - for (let t = 0; t < allDates.length; t += 1) { - const date = allDates[t]!; - const closeTs = makeUtcMs(date, 21); // 16:00 ET close - for (let l = 0; l < listingCount; l += 1) { - let close: number; - if (zeroVariance) { - close = 100; - } else { - const isEvent = eventSet.has(`${t}:${l}`); - const base = (rand() - 0.5) * 0.015; - const dailyRet = isEvent ? base + 0.025 + l * 0.002 : base; - prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet)); - close = Number(prices[l]!.toFixed(6)); - } - bars.push({ - listingId: listingIds[l]!, - ts: closeTs, - open: close, - high: close, - low: close, - close, - volume: 25_000, - vwap: close, - knownAt: closeTs, - }); - } - } - - return { - listingIds, - allDates, - vaultCutoffDate, - vaultCutoffTs, - bars, - eventsTable: { - columns: [...EVENTS_COLUMNS], - rows: eventRows, - }, - }; -} - -interface FakeStoreState { - readonly store: MarketDataStore; - readonly barsCalls: BarsQuery[]; - readonly eventsCalls: EventsQuery[]; - readonly universeCalls: UniverseQuery[]; -} - -function createFakeStore( - fixture: SyntheticEventFixture, - options?: { - extraBars?: readonly BarRecord[]; - extraEvents?: readonly TableRow[]; - universeResolver?: (q: UniverseQuery) => number[]; - barsError?: unknown; - eventsError?: unknown; - universeError?: unknown; - } -): FakeStoreState { - const barsCalls: BarsQuery[] = []; - const eventsCalls: EventsQuery[] = []; - const universeCalls: UniverseQuery[] = []; - - const store: MarketDataStore = { - bars(q: BarsQuery): AsyncIterable { - barsCalls.push(q); - const ids = new Set(q.listingIds); - const fromMs = parseBound(q.from, false); - const toMs = parseBound(q.to, true); - const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); - const rows = fixture.bars.filter( - b => - ids.has(b.listingId) && - b.ts >= fromMs && - b.ts <= toMs && - b.ts <= asOfMs && - b.knownAt <= asOfMs - ); - const thrown = options?.barsError; - return { - async *[Symbol.asyncIterator]() { - if (thrown !== undefined) { - throw thrown; - } - yield { rows: [...rows, ...(options?.extraBars ?? [])] }; - }, - }; - }, - async events(q: EventsQuery): Promise
{ - eventsCalls.push(q); - if (options?.eventsError !== undefined) { - throw options.eventsError; - } - const kinds = new Set(q.kinds); - const ids = q.listingIds !== undefined ? new Set(q.listingIds) : null; - const fromMs = parseBound(q.from, false); - const toMs = parseBound(q.to, true); - const asOfMs = q.asOf === undefined ? Number.POSITIVE_INFINITY : parseBound(q.asOf, true); - const rows = fixture.eventsTable.rows.filter(r => { - if (!kinds.has(r.kind as string)) { - return false; - } - if (ids !== null && !ids.has(r.listing_id as number)) { - return false; - } - const ts = r.ts as number; - const knownAt = r.known_at as number; - return ts >= fromMs && ts <= toMs && knownAt <= asOfMs; - }); - return { - columns: fixture.eventsTable.columns, - rows: [...rows, ...(options?.extraEvents ?? [])], - }; - }, - async universe(q: UniverseQuery): Promise { - universeCalls.push(q); - if (options?.universeError !== undefined) { - throw options.universeError; - } - return options?.universeResolver ? options.universeResolver(q) : fixture.listingIds; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - - return { store, barsCalls, eventsCalls, universeCalls }; -} - -function createFakeCalendarResolver( - dates: readonly string[], - options?: { - hourUtc?: number; - error?: unknown; - } -): { - calls: EventStudyExchangeCalendarQuery[]; - resolveExchangeCalendars: ( - q: EventStudyExchangeCalendarQuery - ) => Promise; -} { - const calls: EventStudyExchangeCalendarQuery[] = []; - const hourUtc = options?.hourUtc ?? 21; - - return { - calls, - async resolveExchangeCalendars( - q: EventStudyExchangeCalendarQuery - ): Promise { - calls.push(q); - if (options?.error !== undefined) { - throw options.error; - } - const sessions = dates - .filter(d => d >= q.fromDate && d <= q.toDate) - .map(date => ({ date, closeTs: makeUtcMs(date, hourUtc) })); - const listingCalendarId = new Map(); - for (const id of q.listingIds) { - listingCalendarId.set(id, 'XNYS'); - } - return { - calendars: new Map([['XNYS', sessions]]), - listingCalendarId, - }; - }, - }; -} - -async function callEventStudy( - server: ReturnType, - args: Record, - id = 1 -): Promise<{ - rpc: Record; - result?: { content: Array<{ type: string; text: string }>; isError?: boolean }; - payload?: EventStudyResultPayload; -}> { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id, - method: 'tools/call', - params: { name: 'event_study', arguments: args }, - }) - ); - const rpc = JSON.parse(raw!) as Record; - const result = rpc.result as - | { content: Array<{ type: string; text: string }>; isError?: boolean } - | undefined; - let payload: EventStudyResultPayload | undefined; - if (result !== undefined && !result.isError && result.content[0]?.text) { - payload = JSON.parse(result.content[0].text) as EventStudyResultPayload; - } - return { rpc, result, payload }; -} - -describe('MCP event_study tool', () => { - test('tools/list advertises strict JSON schema and exported bounds constants', async () => { - const fixture = buildSyntheticEventFixture(); - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - - expect(EVENT_STUDY_MAX_LISTING_IDS).toBe(500); - expect(EVENT_STUDY_MAX_PRE_DAYS).toBe(60); - expect(EVENT_STUDY_MAX_POST_DAYS).toBe(60); - expect(EVENT_STUDY_MAX_SUBTYPES).toBe(100); - expect(EVENT_STUDY_MAX_SUBTYPE_LENGTH).toBe(128); - - const raw = await server.handleMessage( - JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }) - ); - const parsed = JSON.parse(raw!) as { - result: { - tools: Array<{ - name: string; - inputSchema: { - type: string; - additionalProperties: boolean; - properties: Record>; - }; - }>; - }; - }; - - expect(parsed.result.tools).toHaveLength(1); - const tool = parsed.result.tools[0]!; - expect(tool.name).toBe('event_study'); - expect(tool.inputSchema.type).toBe('object'); - expect(tool.inputSchema.additionalProperties).toBe(false); - - const props = tool.inputSchema.properties; - expect(props.scope).toBeUndefined(); - expect(props.principalId).toBeUndefined(); - expect(props.vaultCutoffDate).toBeUndefined(); - expect(props.vault_evaluation_only).toBeUndefined(); - - const eventSchema = props.event as { - additionalProperties?: boolean; - properties?: { - subtypes?: { - maxItems?: number; - items?: { maxLength?: number }; - }; - }; - }; - expect(eventSchema.additionalProperties).toBe(false); - expect(eventSchema.properties?.subtypes?.maxItems).toBe(EVENT_STUDY_MAX_SUBTYPES); - expect(eventSchema.properties?.subtypes?.items?.maxLength).toBe( - EVENT_STUDY_MAX_SUBTYPE_LENGTH - ); - }); - - test('happy path matches direct runEventStudy, writes one event_study trial, and omits raw series', async () => { - const fixture = buildSyntheticEventFixture(); - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - - const from = fixture.allDates[0]!; - const to = fixture.allDates[64]!; - const preDays = 3; - const postDays = 5; - - const { result, payload } = await callEventStudy(server, { - listingIds: fixture.listingIds, - from, - to, - event: { kinds: ['filing', 'earnings'] }, - preDays, - postDays, - benchmark: 'equal_weight', - adjustment: 'raw', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - campaignId: CAMPAIGN_UUID, - hypothesisId: HYPOTHESIS_UUID, - }); - - expect(result?.isError).toBeUndefined(); - expect(payload).toBeDefined(); - expect(payload?.status).toBe('ok'); - if (!payload || payload.status !== 'ok') { - throw new Error('Expected ok payload'); - } - - expect(payload.scope).toBe('vault_fenced'); - expect(payload.vaultCutoffTs).toBe(fixture.vaultCutoffTs); - expect(payload.vaultCutoffDate).toBe(fixture.vaultCutoffDate); - expect(payload.clampedTo).toBe(false); - expect(payload.clampedAsOf).toBe(false); - expect(payload.listingCount).toBe(fixture.listingIds.length); - expect(payload.eventCount).toBe(12); - expect(payload.vaultExcludedEvents).toBe(0); - expect(payload.study.offsets).toHaveLength(preDays + postDays + 1); - expect(payload.study.hasBenchmark).toBe(true); - expect(payload.study.diagnostics.eventsUsed).toBeGreaterThanOrEqual(5); - expect(payload.study.clustered).not.toBeNull(); - expect(payload.study.recency).not.toBeNull(); - - // Verify no raw arrays or typed series are exposed in the JSON payload. - const serialized = result!.content[0]!.text; - expect(serialized).not.toContain('entityReturns'); - expect(serialized).not.toContain('benchmarkReturns'); - expect(serialized).not.toContain('eventCars'); - expect(serialized).not.toContain('meanCars'); - expect(serialized).not.toContain('eventCounts'); - - // Verify trial_ledger write - expect(ledger.insertCalls).toBe(1); - expect(ledger.rows).toHaveLength(1); - const row = ledger.rows[0]!; - expect(row.stage).toBe('event_study'); - expect(row.principal_id).toBe(AGENT_PRINCIPAL); - expect(row.universe_market).toBe('US_EQ'); - expect(row.horizon_bucket).toBe('swing_1_10d'); - expect(row.campaign_id).toBe(CAMPAIGN_UUID); - expect(row.hypothesis_id).toBe(HYPOTHESIS_UUID); - expect(row.sample_end < fixture.vaultCutoffDate).toBe(true); - expect(payload.trial.trialId).toBe(1); - expect(payload.deflatedSharpe.trialId).toBe(1); - expect(payload.deflatedSharpe.clusterSize).toBe(1); - - // Direct parity check against buildEventStudyInput + runEventStudy - const directLedger = createFakeTrialLedger(); - const directEvents = eventsTableToEventRows(fixture.eventsTable, { - kinds: ['earnings', 'filing'], - }); - const directCal = await cal.resolveExchangeCalendars({ - listingIds: fixture.listingIds, - fromDate: from, - toDate: to, - }); - const directBuilt = buildEventStudyInput({ - bars: fixture.bars.filter(b => b.ts < fixture.vaultCutoffTs), - events: directEvents, - vaultCutoffDate: fixture.vaultCutoffDate, - benchmark: 'equal_weight', - exchangeCalendars: directCal, - }); - const directRun = await runEventStudy(directLedger.executor, { - principalId: AGENT_PRINCIPAL, - campaignId: CAMPAIGN_UUID, - hypothesisId: HYPOTHESIS_UUID, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - expression: { - expression: 'mcp:event_study:v1:earnings,filing', - params: { - version: 1, - kinds: ['earnings', 'filing'], - subtypes: null, - preDays, - postDays, - benchmark: 'equal_weight', - adjustment: 'raw', - effectiveFrom: payload.effectiveFrom, - effectiveTo: payload.effectiveTo, - effectiveAsOf: payload.effectiveAsOf, - }, - universe: { - kind: 'listingIds', - listingIds: fixture.listingIds, - }, - horizon: `${postDays}d`, - }, - input: directBuilt.input, - vaultCutoffDate: fixture.vaultCutoffDate, - options: { preDays, postDays }, - }); - - expect(directRun.status).toBe('ok'); - if (directRun.status !== 'ok') { - throw new Error('Expected direct ok'); - } - - expect(payload.trial.expressionHash).toBe(directRun.trial.expressionHash); - expect(row.daily_series).toEqual(directLedger.rows[0]!.daily_series); - expect(payload.study.offsets).toEqual( - directRun.study.offsets.map(o => ({ - offset: o.offset, - n: o.n, - aar: o.aar, - caar: o.caar, - caarFromZero: o.caarFromZero, - })) - ); - }); - - test('replay with reordered/duplicated IDs, kinds, and subtypes yields identical expressionHash and results; param change alters hash', async () => { - const fixture = buildSyntheticEventFixture(); - const from = fixture.allDates[0]!; - const to = fixture.allDates[64]!; - - const runWithArgs = async (args: Record) => { - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, args); - expect(res.payload?.status).toBe('ok'); - return res.payload as Extract; - }; - - const p1 = await runWithArgs({ - listingIds: fixture.listingIds, - from, - to, - event: { kinds: ['filing', 'earnings'], subtypes: ['8-K', 'Q4'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - const p2 = await runWithArgs({ - listingIds: [...fixture.listingIds].reverse().concat(fixture.listingIds[0]!), - from, - to, - event: { kinds: ['earnings', 'filing', 'earnings'], subtypes: ['Q4', '8-K', 'Q4'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(p2.trial.expressionHash).toBe(p1.trial.expressionHash); - expect(p2.study.offsets).toEqual(p1.study.offsets); - expect(p2.event.kinds).toEqual(['earnings', 'filing']); - expect(p2.event.subtypes).toEqual(['8-K', 'Q4']); - - // Changing benchmark changes the expressionHash - const p3 = await runWithArgs({ - listingIds: fixture.listingIds, - from, - to, - event: { kinds: ['filing', 'earnings'], subtypes: ['8-K', 'Q4'] }, - preDays: 2, - postDays: 4, - benchmark: 'none', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(p3.trial.expressionHash).not.toBe(p1.trial.expressionHash); - expect(p3.study.hasBenchmark).toBe(false); - expect(p1.study.hasBenchmark).toBe(true); - // With equal_weight benchmark vs none, AAR values differ when cross-sectional mean return is non-zero - expect(p3.study.offsets[2]!.aar).not.toBeCloseTo(p1.study.offsets[2]!.aar, 8); - }); - - test('Vault fence clamps to/asOf, filters leaky store rows, and matches clean replay', async () => { - const fixture = buildSyntheticEventFixture(); - const from = fixture.allDates[0]!; - const postCutoffTo = fixture.allDates[fixture.allDates.length - 1]!; - const cutoffDate = fixture.vaultCutoffDate; - - const poisonedEvents: TableRow[] = [ - // Post-cutoff ts & known_at - { - listing_id: fixture.listingIds[0]!, - ts: makeUtcMs(cutoffDate, 14), - known_at: makeUtcMs(cutoffDate, 14), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Valid ts in window, but known_at in Vault - { - listing_id: fixture.listingIds[1]!, - ts: makeUtcMs(fixture.allDates[20]!, 14), - known_at: makeUtcMs(cutoffDate, 15), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Foreign listing - { - listing_id: 999_999, - ts: makeUtcMs(fixture.allDates[20]!, 14), - known_at: makeUtcMs(fixture.allDates[20]!, 14), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - // Before study window - { - listing_id: fixture.listingIds[2]!, - ts: makeUtcMs('2022-01-05', 14), - known_at: makeUtcMs('2022-01-05', 14), - known_at_source: 'exact', - kind: 'filing', - subtype: '8-K', - payload_json: '{}', - }, - ]; - - const poisonedBars: BarRecord[] = [ - // Post-cutoff bar with NaN close (must never be read or affect returns) - { - listingId: fixture.listingIds[0]!, - ts: makeUtcMs(cutoffDate, 21), - open: Number.NaN, - high: Number.NaN, - low: Number.NaN, - close: Number.NaN, - volume: 100, - knownAt: makeUtcMs(cutoffDate, 21), - }, - // Foreign listing bar - { - listingId: 999_999, - ts: makeUtcMs(fixture.allDates[15]!, 21), - open: 50, - high: 50, - low: 50, - close: 50, - volume: 100, - knownAt: makeUtcMs(fixture.allDates[15]!, 21), - }, - ]; - - const leakyStore = createFakeStore(fixture, { - extraBars: poisonedBars, - extraEvents: poisonedEvents, - }); - const leakyLedger = createFakeTrialLedger(); - const leakyCal = createFakeCalendarResolver(fixture.allDates); - - const leakyServer = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: leakyStore.store, - ledger: leakyLedger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: leakyCal.resolveExchangeCalendars, - }), - ], - }); - - const leakyRes = await callEventStudy(leakyServer, { - listingIds: fixture.listingIds, - from, - to: postCutoffTo, - asOf: postCutoffTo, - event: { kinds: ['filing', 'earnings'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(leakyRes.payload?.status).toBe('ok'); - const leakyPayload = leakyRes.payload as Extract; - expect(leakyPayload.clampedTo).toBe(true); - expect(leakyPayload.clampedAsOf).toBe(true); - expect(leakyPayload.toMs).toBeLessThan(fixture.vaultCutoffTs); - expect(leakyPayload.asOfMs).toBeLessThan(fixture.vaultCutoffTs); - expect(leakyPayload.vaultExcludedEvents).toBe(2); - expect(leakyPayload.panelDiagnostics.vaultExcludedDates).toBe(1); - expect(leakyPayload.eventCount).toBe(12); - - // Verify no store call received a bound >= vaultCutoffTs - expect(Date.parse(leakyStore.barsCalls[0]!.to)).toBeLessThan(fixture.vaultCutoffTs); - expect(Date.parse(leakyStore.barsCalls[0]!.asOf!)).toBeLessThan(fixture.vaultCutoffTs); - expect(Date.parse(leakyStore.eventsCalls[0]!.to)).toBeLessThan(fixture.vaultCutoffTs); - expect(Date.parse(leakyStore.eventsCalls[0]!.asOf!)).toBeLessThan(fixture.vaultCutoffTs); - expect(leakyCal.calls[0]!.toDate < fixture.vaultCutoffDate).toBe(true); - - // Compare against clean store with same arguments - const cleanStore = createFakeStore(fixture); - const cleanLedger = createFakeTrialLedger(); - const cleanCal = createFakeCalendarResolver(fixture.allDates); - const cleanServer = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: cleanStore.store, - ledger: cleanLedger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cleanCal.resolveExchangeCalendars, - }), - ], - }); - - const cleanRes = await callEventStudy(cleanServer, { - listingIds: fixture.listingIds, - from, - to: postCutoffTo, - asOf: postCutoffTo, - event: { kinds: ['filing', 'earnings'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - const cleanPayload = cleanRes.payload as Extract; - expect(cleanPayload.panelDiagnostics.vaultExcludedDates).toBe(0); - expect(leakyPayload.study.offsets).toEqual(cleanPayload.study.offsets); - expect(leakyPayload.trial.expressionHash).toBe(cleanPayload.trial.expressionHash); - expect(leakyLedger.rows[0]!.daily_series).toEqual(cleanLedger.rows[0]!.daily_series); - }); - - test('named universe resolves strictly pre-start and earlier explicit asOf caps calendar & events', async () => { - const fixture = buildSyntheticEventFixture(); - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: 'operator', - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - - const from = fixture.allDates[0]!; // 2022-11-01 - const to = fixture.allDates[64]!; - const earlierAsOf = fixture.allDates[40]!; // Excludes events at day 42 and 50 - - const res = await callEventStudy(server, { - universe: 'US_EQ', - from, - to, - asOf: earlierAsOf, - event: { kinds: ['filing', 'earnings'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - - expect(fakeStore.universeCalls).toHaveLength(1); - expect(fakeStore.universeCalls[0]!.ref).toBe('US_EQ'); - expect(fakeStore.universeCalls[0]!.date).toBe('2022-10-31'); // Strictly before 2022-11-01 - expect(cal.calls[0]!.toDate).toBe(earlierAsOf); - expect(res.payload?.status).toBe('ok'); - expect(res.payload?.eventCount).toBe(8); // Only days 12, 18, 26, 34 (2 listings each) - expect(ledger.rows[0]!.principal_id).toBe('operator'); - }); - - test('strict input schema rejects invalid arguments with zero dependency calls and accepts boundary windows', async () => { - const fixture = buildSyntheticEventFixture(); - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - - const validBase = { - listingIds: [60_001], - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - const invalidCases: Record[] = [ - { ...validBase, scope: 'vault_evaluation_only' }, - { ...validBase, principalId: 'operator' }, - { ...validBase, vaultCutoffDate: '2099-01-01' }, - { ...validBase, vault_evaluation_only: true }, - { ...validBase, extraKey: 123 }, - { ...validBase, event: { kinds: ['filing'], unknownNested: true } }, - { ...validBase, universe: 'US_EQ' }, // both listingIds and universe - { - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 5, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }, // neither selector - { ...validBase, event: { kinds: [] } }, - { ...validBase, event: { kinds: ['unknown_kind'] } }, - { ...validBase, event: { kinds: ['filing'], subtypes: [] } }, - { - ...validBase, - event: { - kinds: ['filing'], - subtypes: Array.from({ length: EVENT_STUDY_MAX_SUBTYPES + 1 }, (_, i) => `SUB_${i}`), - }, - }, - { - ...validBase, - event: { - kinds: ['filing'], - subtypes: ['x'.repeat(EVENT_STUDY_MAX_SUBTYPE_LENGTH + 1)], - }, - }, - { ...validBase, preDays: -1 }, - { ...validBase, preDays: 61 }, - { ...validBase, preDays: 1.5 }, - { ...validBase, postDays: -1 }, - { ...validBase, postDays: 61 }, - { ...validBase, postDays: 2.5 }, - { ...validBase, postDays: 10, horizonBucket: 'position_10d_plus' }, - { ...validBase, postDays: 11, horizonBucket: 'swing_1_10d' }, - { ...validBase, campaignId: 'not-a-uuid' }, - { ...validBase, hypothesisId: 'not-a-uuid' }, - { - universe: 'US_EQ', - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 5, - universeMarket: 'CA_EQ', - horizonBucket: 'swing_1_10d', - }, - ]; - - for (let i = 0; i < invalidCases.length; i += 1) { - const res = await callEventStudy(server, invalidCases[i]!, i + 1); - expect(res.result?.isError).toBe(true); - expect(res.result?.content[0]?.text).toContain('Invalid arguments for tool "event_study"'); - } - - expect(fakeStore.barsCalls).toHaveLength(0); - expect(fakeStore.eventsCalls).toHaveLength(0); - expect(fakeStore.universeCalls).toHaveLength(0); - expect(cal.calls).toHaveLength(0); - expect(ledger.insertCalls).toBe(0); - - // Valid boundary windows: 0, 10 (swing_1_10d), 11, 60 (position_10d_plus) - const boundaryWindows: Array<{ preDays: number; postDays: number; bucket: string }> = [ - { preDays: 0, postDays: 0, bucket: 'swing_1_10d' }, - { preDays: 0, postDays: 10, bucket: 'swing_1_10d' }, - { preDays: 11, postDays: 11, bucket: 'position_10d_plus' }, - { preDays: 60, postDays: 60, bucket: 'position_10d_plus' }, - ]; - for (const w of boundaryWindows) { - const res = await callEventStudy(server, { - ...validBase, - preDays: w.preDays, - postDays: w.postDays, - horizonBucket: w.bucket, - }); - expect(res.result?.isError).toBeUndefined(); - expect(res.payload).toBeDefined(); - } - }); - - test('insufficient_data paths (empty universe, empty grid, below_min_events, zero_variance_series) write zero ledger rows', async () => { - const fixture = buildSyntheticEventFixture(); - - // 1. Empty resolved universe -> zero bars/events/calendar/ledger calls - { - const fakeStore = createFakeStore(fixture, { universeResolver: () => [] }); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, { - universe: 'US_EQ', - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - expect(res.payload?.status).toBe('insufficient_data'); - if (res.payload?.status === 'insufficient_data') { - expect(res.payload.reason).toBe('below_min_events'); - } - expect(res.payload?.listingCount).toBe(0); - expect(fakeStore.barsCalls).toHaveLength(0); - expect(fakeStore.eventsCalls).toHaveLength(0); - expect(cal.calls).toHaveLength(0); - expect(ledger.insertCalls).toBe(0); - } - - // 2. Empty session grid (no bars in range) - { - const emptyBarsFixture: SyntheticEventFixture = { ...fixture, bars: [] }; - const fakeStore = createFakeStore(emptyBarsFixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, { - listingIds: fixture.listingIds, - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - expect(res.payload?.status).toBe('insufficient_data'); - expect(res.payload?.eventCount).toBe(0); - expect(ledger.insertCalls).toBe(0); - } - - // 3. Below minimum events (subtype with no matches) - { - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, { - listingIds: fixture.listingIds, - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing'], subtypes: ['NONEXISTENT_SUBTYPE'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - expect(res.payload?.status).toBe('insufficient_data'); - if (res.payload?.status === 'insufficient_data') { - expect(res.payload.reason).toBe('below_min_events'); - } - expect(ledger.insertCalls).toBe(0); - } - - // 4. Zero-variance clustered CAR series - { - const flatFixture = buildSyntheticEventFixture({ zeroVariance: true }); - const fakeStore = createFakeStore(flatFixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(flatFixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: flatFixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, { - listingIds: flatFixture.listingIds, - from: flatFixture.allDates[0]!, - to: flatFixture.allDates[64]!, - event: { kinds: ['filing', 'earnings'] }, - preDays: 2, - postDays: 4, - benchmark: 'none', - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - expect(res.payload?.status).toBe('insufficient_data'); - if (res.payload?.status === 'insufficient_data') { - expect(res.payload.reason).toBe('zero_variance_series'); - } - // Offsets are still projected when study.status === 'ok' - expect(res.payload?.study.offsets).toHaveLength(7); - expect(ledger.insertCalls).toBe(0); - } - }); - - test('factory option validation, wholly-in-Vault request, and sanitized error mapping without secret leaks', async () => { - const fixture = buildSyntheticEventFixture(); - const fakeStore = createFakeStore(fixture); - const ledger = createFakeTrialLedger(); - const cal = createFakeCalendarResolver(fixture.allDates); - const SECRET = 'SECRET_MARKER_SQL_URI_88421'; - - // Factory option validation - expect(() => - createEventStudyTool({ - store: {} as MarketDataStore, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createEventStudyTool({ - store: fakeStore.store, - ledger: {} as TrialLedgerExecutor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }) - ).toThrow(SignalStudyError); - - expect(() => - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: null as unknown as typeof cal.resolveExchangeCalendars, - }) - ).toThrow(EventPanelError); - - expect(() => - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: 'invalid-principal', - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }) - ).toThrow(TrialLedgerError); - - expect(() => - createEventStudyTool({ - store: fakeStore.store, - ledger: ledger.executor, - vaultContext: { vaultCutoffTs: Number.NaN }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: cal.resolveExchangeCalendars, - }) - ).toThrow(MarketDataStoreValidationError); - - // Request wholly in Vault -> zero dependency calls - { - const s = createFakeStore(fixture); - const l = createFakeTrialLedger(); - const c = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: s.store, - ledger: l.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: c.resolveExchangeCalendars, - }), - ], - }); - const res = await callEventStudy(server, { - listingIds: fixture.listingIds, - from: fixture.vaultCutoffDate, - to: fixture.allDates[fixture.allDates.length - 1]!, - event: { kinds: ['filing'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }); - expect(res.result?.isError).toBe(true); - expect(res.result?.content[0]?.text).toContain('VaultHoldoutFenceError'); - expect(s.barsCalls).toHaveLength(0); - expect(s.eventsCalls).toHaveLength(0); - expect(c.calls).toHaveLength(0); - expect(l.insertCalls).toBe(0); - } - - const baseArgs = { - listingIds: fixture.listingIds, - from: fixture.allDates[0]!, - to: fixture.allDates[64]!, - event: { kinds: ['filing', 'earnings'] }, - preDays: 2, - postDays: 4, - universeMarket: 'US_EQ', - horizonBucket: 'swing_1_10d', - }; - - const errorCases: Array<{ - name: string; - storeOpts?: Parameters[1]; - calError?: unknown; - ledgerOpts?: Parameters[0]; - expectedPrefix: string; - }> = [ - { - name: 'store VaultHoldoutFenceError', - storeOpts: { - barsError: new VaultHoldoutFenceError('2025-01-01', 1, 1, `leak ${SECRET}`), - }, - expectedPrefix: 'VaultHoldoutFenceError:', - }, - { - name: 'store VaultScopeNotAuthorizedError', - storeOpts: { barsError: new VaultScopeNotAuthorizedError(`leak ${SECRET}`) }, - expectedPrefix: 'VaultScopeNotAuthorizedError:', - }, - { - name: 'store MarketDataStoreValidationError', - storeOpts: { - eventsError: new MarketDataStoreValidationError(`leak ${SECRET}`, 'from'), - }, - expectedPrefix: 'MarketDataStoreValidationError:', - }, - { - name: 'store MarketDataStoreNotImplementedError', - storeOpts: { - eventsError: new MarketDataStoreNotImplementedError('events', `leak ${SECRET}`), - }, - expectedPrefix: 'MarketDataStoreNotImplementedError:', - }, - { - name: 'store AdjFactorsSnapshotError', - storeOpts: { - barsError: new AdjFactorsSnapshotError('missing_snapshot', `leak ${SECRET}`), - }, - expectedPrefix: 'AdjFactorsSnapshotError:', - }, - { - name: 'calendar resolver generic Error', - calError: new Error(`calendar db down ${SECRET}`), - expectedPrefix: 'Error: Exchange calendar resolution failed.', - }, - { - name: 'calendar resolver EventPanelError', - calError: new EventPanelError('invalid_option', `bad cal ${SECRET}`), - expectedPrefix: 'EventPanelError:', - }, - { - name: 'SignalStudyError from store/runner', - storeOpts: { - eventsError: new SignalStudyError('invalid_panel', `bad panel ${SECRET}`), - }, - expectedPrefix: 'SignalStudyError:', - }, - { - name: 'TrialLedgerError on INSERT', - ledgerOpts: { - insertError: new TrialLedgerError('VAULT_FENCE_VIOLATION', `pg detail ${SECRET}`), - }, - expectedPrefix: 'TrialLedgerError:', - }, - ]; - - for (const tc of errorCases) { - const s = createFakeStore(fixture, tc.storeOpts); - const l = createFakeTrialLedger(tc.ledgerOpts); - const c = createFakeCalendarResolver(fixture.allDates, { error: tc.calError }); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: s.store, - ledger: l.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: c.resolveExchangeCalendars, - }), - ], - }); - - const res = await callEventStudy(server, baseArgs); - expect(res.result?.isError).toBe(true); - const text = res.result?.content[0]?.text ?? ''; - expect(text).toContain(tc.expectedPrefix); - expect(text).not.toContain(SECRET); - } - - // Post-insert DSR read failure: trial is recorded once (no retry) and sanitized message informs caller - { - const s = createFakeStore(fixture); - const l = createFakeTrialLedger({ - dsrReadError: new Error(`pg select timeout ${SECRET}`), - }); - const c = createFakeCalendarResolver(fixture.allDates); - const server = createMcpServer({ - name: 'research-mcp', - version: '1.0.0', - tools: [ - createEventStudyTool({ - store: s.store, - ledger: l.executor, - vaultContext: { vaultCutoffTs: fixture.vaultCutoffTs }, - principalId: AGENT_PRINCIPAL, - resolveExchangeCalendars: c.resolveExchangeCalendars, - }), - ], - }); - - const res = await callEventStudy(server, baseArgs); - expect(res.result?.isError).toBe(true); - const text = res.result?.content[0]?.text ?? ''; - expect(text).toBe( - 'SignalStudyError: Trial was recorded, but cluster deflated Sharpe evaluation failed.' - ); - expect(text).not.toContain(SECRET); - expect(l.insertCalls).toBe(1); - expect(l.rows).toHaveLength(1); - } - }); -}); diff --git a/libs/research/test/mcp-file-finding-qa.test.ts b/libs/research/test/mcp-file-finding-qa.test.ts deleted file mode 100644 index 397637ba..00000000 --- a/libs/research/test/mcp-file-finding-qa.test.ts +++ /dev/null @@ -1,469 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type AppendFindingResult, - FILE_FINDING_ERROR_FILING_FAILED, - FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, - FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, - FILE_FINDING_MAX_EVIDENCE_REFS, - FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, - FILE_FINDING_MAX_REF_LENGTH, - FILE_FINDING_MAX_SUMMARY_LENGTH, - FILE_FINDING_MAX_TITLE_LENGTH, - FILE_FINDING_MAX_TRIAL_REFS, - type FileFindingResultPayload, - type FiledFindingRecord, - type FindingWritePort, - type TrialRefLookupPort, - areFiledFindingPayloadsEqual, - createFileFindingTool, -} from '../src/mcp/index'; - -// Compile-time guard: the write port exposes exactly one append method (no update/delete). -type Equal = (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 - ? true - : false; -const writePortKeysAreAppendOnly: Equal = true; - -const FIXED_EPOCH_MS = Date.UTC(2025, 5, 2, 15, 30, 0); - -interface RecordingPort { - readonly calls: { record: FiledFindingRecord; idempotencyKey: string | undefined }[]; - readonly port: FindingWritePort; -} - -function recordingPort( - respond: (record: FiledFindingRecord, key: string | undefined) => unknown -): RecordingPort { - const calls: RecordingPort['calls'] = []; - return { - calls, - port: { - async appendFinding(record, idempotencyKey) { - calls.push({ record, idempotencyKey }); - return respond(record, idempotencyKey) as AppendFindingResult; - }, - }, - }; -} - -function createdEcho(record: FiledFindingRecord): AppendFindingResult { - return { status: 'created', id: record.id, createdAt: record.createdAt }; -} - -function lookupFrom( - answer: (ref: string) => unknown -): { readonly queried: string[]; readonly port: TrialRefLookupPort } { - const queried: string[] = []; - return { - queried, - port: { - hasResearchVisibleTrial(ref: string) { - queried.push(ref); - return answer(ref) as boolean; - }, - }, - }; -} - -function counter(fn: () => T): { calls: number; fn: () => T } { - const state = { - calls: 0, - fn: () => { - state.calls += 1; - return fn(); - }, - }; - return state; -} - -const validArgs = { - kind: 'finding', - title: 'QA filing', - summary: 'Research-visible summary.', - trialRefs: ['trial-1'], -}; - -function parseReceipt(text: string | undefined): FileFindingResultPayload { - return JSON.parse(text ?? '') as FileFindingResultPayload; -} - -describe('MCP file_finding QA edge cases', () => { - test('write port type exposes only appendFinding', () => { - expect(writePortKeysAreAppendOnly).toBe(true); - }); - - test('deduplicates trial refs before lookup, verifies in sorted order, and short-circuits on the first unavailable ref', async () => { - const rec = recordingPort(createdEcho); - const lookup = lookupFrom(ref => ref !== 'trial-b'); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookup.port, - newId: () => 'id-1', - now: () => FIXED_EPOCH_MS, - }); - - const res = await tool.execute({ - ...validArgs, - trialRefs: ['trial-c', 'trial-a', 'trial-b', 'trial-a', 'trial-c'], - }); - - expect(res.isError).toBe(true); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - expect(lookup.queried).toEqual(['trial-a', 'trial-b']); - expect(rec.calls).toHaveLength(0); - }); - - test('accepts a synchronous boolean lookup and queries each unique ref exactly once on success', async () => { - const rec = recordingPort(createdEcho); - const lookup = lookupFrom(() => true); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookup.port, - newId: () => 'id-sync', - now: () => FIXED_EPOCH_MS, - }); - - const res = await tool.execute({ ...validArgs, trialRefs: ['t2', 't1', 't2', 't1'] }); - - expect(res.isError).toBeUndefined(); - expect(lookup.queried).toEqual(['t1', 't2']); - expect(rec.calls).toHaveLength(1); - expect(rec.calls[0]?.record.trialRefs).toEqual(['t1', 't2']); - }); - - test('treats non-boolean lookup answers as a filing failure with zero writes and no metadata generation', async () => { - for (const answer of [1, 'true', null, undefined, {}]) { - const rec = recordingPort(createdEcho); - const ids = counter(() => 'never'); - const clock = counter(() => FIXED_EPOCH_MS); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => answer).port, - newId: ids.fn, - now: clock.fn, - }); - - const res = await tool.execute(validArgs); - - expect(res.isError).toBe(true); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(rec.calls).toHaveLength(0); - expect(ids.calls).toBe(0); - expect(clock.calls).toBe(0); - } - }); - - test('rejects unusable generated ids and clock values with a fixed error and zero writes', async () => { - const badSources: readonly { - readonly label: string; - readonly newId: () => string; - readonly now: () => Date | number; - }[] = [ - { label: 'empty id', newId: () => '', now: () => FIXED_EPOCH_MS }, - { label: 'blank id', newId: () => ' ', now: () => FIXED_EPOCH_MS }, - { label: 'non-string id', newId: () => 42 as unknown as string, now: () => FIXED_EPOCH_MS }, - { - label: 'throwing id source', - newId: () => { - throw new Error('postgres://u:p@db/x id sequence exhausted'); - }, - now: () => FIXED_EPOCH_MS, - }, - { label: 'NaN clock', newId: () => 'id-1', now: () => Number.NaN }, - { label: 'infinite clock', newId: () => 'id-1', now: () => Number.POSITIVE_INFINITY }, - { label: 'invalid Date', newId: () => 'id-1', now: () => new Date('not-a-date') }, - { label: 'out-of-range epoch', newId: () => 'id-1', now: () => 9e15 }, - { label: 'string clock', newId: () => 'id-1', now: () => '2025-01-01' as unknown as number }, - { - label: 'throwing clock', - newId: () => 'id-1', - now: () => { - throw new Error('clock unavailable at /srv/secret.ts:1:1'); - }, - }, - ]; - - for (const source of badSources) { - const rec = recordingPort(createdEcho); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: source.newId, - now: source.now, - }); - - const res = await tool.execute(validArgs); - - expect({ label: source.label, isError: res.isError }).toEqual({ - label: source.label, - isError: true, - }); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(rec.calls).toHaveLength(0); - } - }); - - test('stores Date and epoch clock values as identical UTC ISO timestamps', async () => { - const fromDate = recordingPort(createdEcho); - const fromEpoch = recordingPort(createdEcho); - const lookup = lookupFrom(() => true).port; - - await createFileFindingTool({ - port: fromDate.port, - trialLookup: lookup, - newId: () => 'id-d', - now: () => new Date(FIXED_EPOCH_MS), - }).execute(validArgs); - await createFileFindingTool({ - port: fromEpoch.port, - trialLookup: lookup, - newId: () => 'id-e', - now: () => FIXED_EPOCH_MS, - }).execute(validArgs); - - expect(fromDate.calls[0]?.record.createdAt).toBe('2025-06-02T15:30:00.000Z'); - expect(fromEpoch.calls[0]?.record.createdAt).toBe('2025-06-02T15:30:00.000Z'); - }); - - test('passes the trimmed idempotency key to the port and undefined when omitted', async () => { - const rec = recordingPort(createdEcho); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-k', - now: () => FIXED_EPOCH_MS, - }); - - await tool.execute({ ...validArgs, idempotencyKey: '\t retry-key-7 \n' }); - await tool.execute(validArgs); - - expect(rec.calls.map(c => c.idempotencyKey)).toEqual(['retry-key-7', undefined]); - }); - - test('receipt reflects the port-stored id and timestamp on replay, not freshly generated metadata', async () => { - const rec = recordingPort(() => ({ - status: 'replayed', - id: 'stored-original', - createdAt: '2024-12-31T23:59:59.000Z', - })); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'fresh-id', - now: () => FIXED_EPOCH_MS, - }); - - const res = await tool.execute({ ...validArgs, idempotencyKey: 'k' }); - - expect(res.isError).toBeUndefined(); - expect(parseReceipt(res.content[0]?.text)).toEqual({ - id: 'stored-original', - createdAt: '2024-12-31T23:59:59.000Z', - created: false, - }); - }); - - test('maps malformed port outcomes to the fixed filing error and conflict to the fixed conflict error', async () => { - const malformed: readonly unknown[] = [ - null, - undefined, - 'created', - {}, - { status: 'updated', id: 'x', createdAt: 'y' }, - { status: 'created', id: '', createdAt: '2025-01-01T00:00:00.000Z' }, - { status: 'created', id: 'x' }, - { status: 'replayed', id: 7, createdAt: '2025-01-01T00:00:00.000Z' }, - ]; - - for (const outcome of malformed) { - const tool = createFileFindingTool({ - port: recordingPort(() => outcome).port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-m', - now: () => FIXED_EPOCH_MS, - }); - const res = await tool.execute(validArgs); - expect(res.isError).toBe(true); - expect(res.content[0]?.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - } - - const conflictTool = createFileFindingTool({ - port: recordingPort(() => ({ status: 'conflict' })).port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-c', - now: () => FIXED_EPOCH_MS, - }); - const conflict = await conflictTool.execute({ ...validArgs, idempotencyKey: 'k' }); - expect(conflict.isError).toBe(true); - expect(conflict.content[0]?.text).toBe(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); - }); - - test('accepts every field exactly at its hard limit', async () => { - const rec = recordingPort(createdEcho); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-limit', - now: () => FIXED_EPOCH_MS, - }); - const trialRefs = Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS }, (_, i) => - `t${String(i).padStart(2, '0')}`.padEnd(FILE_FINDING_MAX_REF_LENGTH, 'x') - ); - const evidenceRefs = Array.from({ length: FILE_FINDING_MAX_EVIDENCE_REFS }, (_, i) => - `e${String(i).padStart(2, '0')}`.padEnd(FILE_FINDING_MAX_REF_LENGTH, 'y') - ); - - const res = await tool.execute({ - kind: 'dead_end', - title: 'T'.repeat(FILE_FINDING_MAX_TITLE_LENGTH), - summary: 'S'.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH), - trialRefs, - evidenceRefs, - idempotencyKey: 'K'.repeat(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH), - }); - - expect(res.isError).toBeUndefined(); - expect(rec.calls).toHaveLength(1); - expect(rec.calls[0]?.record.trialRefs).toHaveLength(FILE_FINDING_MAX_TRIAL_REFS); - expect(rec.calls[0]?.record.evidenceRefs).toHaveLength(FILE_FINDING_MAX_EVIDENCE_REFS); - }); - - test('measures limits after trimming, so padded at-limit text is accepted', async () => { - const rec = recordingPort(createdEcho); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-trim', - now: () => FIXED_EPOCH_MS, - }); - - const res = await tool.execute({ - ...validArgs, - title: ` ${'T'.repeat(FILE_FINDING_MAX_TITLE_LENGTH)} `, - }); - - expect(res.isError).toBeUndefined(); - expect(rec.calls[0]?.record.title).toHaveLength(FILE_FINDING_MAX_TITLE_LENGTH); - }); - - test('validation errors never echo submitted text, refs, or keys', async () => { - const sentinel = 'HOLDOUT_OBSERVATION_SENTINEL_0x5f3'; - const rec = recordingPort(createdEcho); - const tool = createFileFindingTool({ - port: rec.port, - trialLookup: lookupFrom(() => true).port, - newId: () => 'id-v', - now: () => FIXED_EPOCH_MS, - }); - - const cases: readonly Record[] = [ - { ...validArgs, summary: `${sentinel} `.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH) }, - { ...validArgs, title: sentinel.repeat(20) }, - { ...validArgs, trialRefs: [sentinel.repeat(10)] }, - { ...validArgs, evidenceRefs: [sentinel.repeat(10)] }, - { ...validArgs, idempotencyKey: sentinel.repeat(5) }, - { ...validArgs, kind: sentinel }, - { ...validArgs, [sentinel]: 1.2345 }, - { ...validArgs, observations: [{ date: '2025-09-01', value: sentinel }] }, - ]; - - for (const args of cases) { - const res = await tool.execute(args); - expect(res.isError).toBe(true); - expect(res.content[0]?.text).not.toContain(sentinel); - } - expect(rec.calls).toHaveLength(0); - }); - - test('concurrent same-key filings across two tool instances store one row (promise barrier, no timers)', async () => { - const stored: FiledFindingRecord[] = []; - const byKey = new Map(); - let releaseFirst: () => void = () => undefined; - const firstHeld = new Promise(resolve => { - releaseFirst = resolve; - }); - let secondArrived: () => void = () => undefined; - const secondReached = new Promise(resolve => { - secondArrived = resolve; - }); - let callIndex = 0; - - const port: FindingWritePort = { - async appendFinding(record, key) { - callIndex += 1; - const mine = callIndex; - // Atomic compare-and-append (no await between read and write). - let outcome: AppendFindingResult; - const existing = key === undefined ? undefined : byKey.get(key); - if (existing === undefined) { - stored.push(record); - if (key !== undefined) { - byKey.set(key, record); - } - outcome = { status: 'created', id: record.id, createdAt: record.createdAt }; - } else if (areFiledFindingPayloadsEqual(existing, record)) { - outcome = { status: 'replayed', id: existing.id, createdAt: existing.createdAt }; - } else { - outcome = { status: 'conflict' }; - } - if (mine === 1) { - await firstHeld; - } else { - secondArrived(); - } - return outcome; - }, - }; - const lookup = lookupFrom(() => true).port; - const toolA = createFileFindingTool({ - port, - trialLookup: lookup, - newId: () => 'inst-a', - now: () => FIXED_EPOCH_MS, - }); - const toolB = createFileFindingTool({ - port, - trialLookup: lookup, - newId: () => 'inst-b', - now: () => FIXED_EPOCH_MS + 1_000, - }); - const args = { ...validArgs, idempotencyKey: 'concurrent' }; - - const pendingA = toolA.execute(args); - const pendingB = toolB.execute(args); - await secondReached; - releaseFirst(); - const [resA, resB] = await Promise.all([pendingA, pendingB]); - - expect(stored).toHaveLength(1); - expect(parseReceipt(resA.content[0]?.text)).toEqual({ - id: 'inst-a', - createdAt: new Date(FIXED_EPOCH_MS).toISOString(), - created: true, - }); - expect(parseReceipt(resB.content[0]?.text)).toEqual({ - id: 'inst-a', - createdAt: new Date(FIXED_EPOCH_MS).toISOString(), - created: false, - }); - }); - - test('payload equality helper ignores server metadata and is order-sensitive on normalized refs', () => { - const base = { - kind: 'finding' as const, - title: 't', - summary: 's', - trialRefs: ['a', 'b'], - evidenceRefs: [], - }; - expect( - areFiledFindingPayloadsEqual( - { ...base, id: 'x', createdAt: '1', status: 'pending_review' } as FiledFindingRecord, - { ...base, id: 'y', createdAt: '2', status: 'pending_review' } as FiledFindingRecord - ) - ).toBe(true); - expect(areFiledFindingPayloadsEqual(base, { ...base, trialRefs: ['a'] })).toBe(false); - expect(areFiledFindingPayloadsEqual(base, { ...base, evidenceRefs: ['e'] })).toBe(false); - expect(areFiledFindingPayloadsEqual(base, { ...base, title: 'T' })).toBe(false); - }); -}); diff --git a/libs/research/test/mcp-file-finding.test.ts b/libs/research/test/mcp-file-finding.test.ts deleted file mode 100644 index ea47b644..00000000 --- a/libs/research/test/mcp-file-finding.test.ts +++ /dev/null @@ -1,1100 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import * as rootResearchExports from '../src/index'; -import { - type AppendFindingResult, - FILE_FINDING_ERROR_FILING_FAILED, - FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, - FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, - FILE_FINDING_ERROR_UNKNOWN_KEYS, - FILE_FINDING_INITIAL_STATUS, - FILE_FINDING_KINDS, - FILE_FINDING_MAX_EVIDENCE_REFS, - FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, - FILE_FINDING_MAX_REF_LENGTH, - FILE_FINDING_MAX_SUMMARY_LENGTH, - FILE_FINDING_MAX_TITLE_LENGTH, - FILE_FINDING_MAX_TRIAL_REFS, - type FileFindingResultPayload, - type FiledFindingRecord, - type FindingQuery, - type FindingRecord, - type FindingWritePort, - type KnowledgePort, - type ReadKnowledgeResultPayload, - type TrialRefLookupPort, - areFiledFindingPayloadsEqual, - createFileFindingTool, - createMcpServer, - createReadKnowledgeTool, - fileFindingInputSchema, -} from '../src/mcp/index'; - -interface SharedFindingsFakeOptions { - readonly failNextAppendError?: unknown; - readonly alwaysAppendError?: unknown; - readonly delayFirstAppendMs?: number; - readonly attachExtraReceiptField?: boolean; -} - -interface SharedFindingsFake { - readonly stored: FiledFindingRecord[]; - readonly appendCalls: { - readonly record: FiledFindingRecord; - readonly idempotencyKey?: string; - }[]; - readonly writePort: FindingWritePort; - readonly knowledgePort: KnowledgePort; - readonly invokedWriteMethods: string[]; -} - -function createSharedFindingsFake(options?: SharedFindingsFakeOptions): SharedFindingsFake { - const stored: FiledFindingRecord[] = []; - const byIdempotencyKey = new Map(); - const appendCalls: { readonly record: FiledFindingRecord; readonly idempotencyKey?: string }[] = - []; - const invokedWriteMethods: string[] = []; - - let failOnceError: unknown = options?.failNextAppendError; - let firstCallSeen = false; - - const rawWritePort: FindingWritePort = { - async appendFinding( - record: FiledFindingRecord, - idempotencyKey?: string - ): Promise { - appendCalls.push({ record, idempotencyKey }); - - if (options?.alwaysAppendError !== undefined) { - throw options.alwaysAppendError; - } - - if (failOnceError !== undefined) { - const err = failOnceError; - failOnceError = undefined; - throw err; - } - - // Atomic compare-and-append before any async yield so concurrent calls with - // the same idempotencyKey cannot both insert. - let outcome: AppendFindingResult; - if (idempotencyKey !== undefined) { - const existing = byIdempotencyKey.get(idempotencyKey); - if (existing !== undefined) { - if (areFiledFindingPayloadsEqual(existing, record)) { - outcome = { - status: 'replayed', - id: existing.id, - createdAt: existing.createdAt, - }; - } else { - outcome = { status: 'conflict' }; - } - } else { - const copy: FiledFindingRecord = { - ...record, - trialRefs: [...record.trialRefs], - evidenceRefs: [...record.evidenceRefs], - }; - stored.push(copy); - byIdempotencyKey.set(idempotencyKey, copy); - outcome = { - status: 'created', - id: copy.id, - createdAt: copy.createdAt, - }; - } - } else { - const copy: FiledFindingRecord = { - ...record, - trialRefs: [...record.trialRefs], - evidenceRefs: [...record.evidenceRefs], - }; - stored.push(copy); - outcome = { - status: 'created', - id: copy.id, - createdAt: copy.createdAt, - }; - } - - if (!firstCallSeen && options?.delayFirstAppendMs !== undefined) { - firstCallSeen = true; - await new Promise(resolve => setTimeout(resolve, options.delayFirstAppendMs)); - } - - if (options?.attachExtraReceiptField === true && outcome.status !== 'conflict') { - return { - ...outcome, - internalDsn: 'postgres://leaked:pass@127.0.0.1:5432/trading_bot', - } as unknown as AppendFindingResult; - } - - return outcome; - }, - }; - - const writePort = new Proxy(rawWritePort, { - get(target, prop, receiver) { - const value: unknown = Reflect.get(target, prop, receiver); - if (typeof value === 'function' && typeof prop === 'string') { - return (...args: unknown[]) => { - invokedWriteMethods.push(prop); - return (value as (...a: unknown[]) => unknown).apply(target, args); - }; - } - return value; - }, - }); - - const knowledgePort: KnowledgePort = { - async listLibraryCards() { - return []; - }, - async listFindings(q: FindingQuery): Promise { - return stored.filter(item => { - if (q.id !== undefined && item.id !== q.id) { - return false; - } - if (q.query !== undefined) { - const needle = q.query.toLowerCase(); - return ( - item.title.toLowerCase().includes(needle) || item.summary.toLowerCase().includes(needle) - ); - } - return true; - }); - }, - async listProviderCaveats() { - return []; - }, - }; - - return { - stored, - appendCalls, - writePort, - knowledgePort, - invokedWriteMethods, - }; -} - -interface FakeTrialLookup { - readonly queriedRefs: string[]; - readonly port: TrialRefLookupPort; -} - -function createFakeTrialLookup(options?: { - readonly researchVisibleRefs?: readonly string[]; - readonly vaultOnlyRefs?: readonly string[]; - readonly throwError?: unknown; -}): FakeTrialLookup { - const visibleSet = new Set( - options?.researchVisibleRefs ?? ['trial-101', 'trial-102', '9007199254740993123'] - ); - const vaultOnlySet = new Set(options?.vaultOnlyRefs ?? ['trial-vault-999']); - const queriedRefs: string[] = []; - - const port: TrialRefLookupPort = { - async hasResearchVisibleTrial(trialRef: string): Promise { - queriedRefs.push(trialRef); - if (options?.throwError !== undefined) { - throw options.throwError; - } - if (vaultOnlySet.has(trialRef)) { - return false; - } - return visibleSet.has(trialRef); - }, - }; - - return { queriedRefs, port }; -} - -function createFixedClock(startIso = '2025-03-01T12:00:00.000Z', stepMs = 60_000) { - let current = Date.parse(startIso); - let calls = 0; - return { - get calls() { - return calls; - }, - now: () => { - calls += 1; - const value = current; - current += stepMs; - return value; - }, - }; -} - -function createFixedIdGenerator(prefix = 'find') { - let counter = 0; - return { - get calls() { - return counter; - }, - newId: () => { - counter += 1; - return `${prefix}-${String(counter).padStart(4, '0')}`; - }, - }; -} - -async function callTool( - server: ReturnType, - toolName: string, - args: Record, - id: string | number = 'req-1' -): Promise<{ - readonly isError: boolean; - readonly text: string; - readonly payload: TPayload | null; -}> { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id, - method: 'tools/call', - params: { - name: toolName, - arguments: args, - }, - }) - ); - - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw as string) as { - error?: unknown; - result: { - isError?: boolean; - content: { type: string; text: string }[]; - }; - }; - expect(parsed.error).toBeUndefined(); - const isError = parsed.result.isError === true; - const text = parsed.result.content[0]?.text ?? ''; - - return { - isError, - text, - payload: isError ? null : (JSON.parse(text) as TPayload), - }; -} - -describe('MCP file_finding tool', () => { - test('files both finding and dead_end with fixed server metadata, normalization, and explicit receipt projection', async () => { - const fake = createSharedFindingsFake({ attachExtraReceiptField: true }); - const trialLookup = createFakeTrialLookup(); - const clock = createFixedClock('2025-03-01T10:00:00.000Z', 60_000); - const idGen = createFixedIdGenerator('finding'); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: idGen.newId, - now: clock.now, - }), - ], - }); - - const findingRes = await callTool(server, 'file_finding', { - kind: 'finding', - title: ' Post-earnings drift decays after day 3 ', - summary: ' Cross-sectional CAR flattens after session +3 across 2015-2024. ', - trialRefs: [' trial-102 ', '9007199254740993123', 'trial-102', 'trial-101'], - evidenceRefs: [' snap-b ', 'snap-a', 'snap-b', 'Snap-A'], - }); - - expect(findingRes.isError).toBe(false); - expect(findingRes.payload).toEqual({ - id: 'finding-0001', - createdAt: '2025-03-01T10:00:00.000Z', - created: true, - }); - expect(Object.keys(findingRes.payload as unknown as Record).sort()).toEqual([ - 'created', - 'createdAt', - 'id', - ]); - - expect(fake.stored[0]).toEqual({ - id: 'finding-0001', - kind: 'finding', - title: 'Post-earnings drift decays after day 3', - status: FILE_FINDING_INITIAL_STATUS, - createdAt: '2025-03-01T10:00:00.000Z', - summary: 'Cross-sectional CAR flattens after session +3 across 2015-2024.', - trialRefs: ['9007199254740993123', 'trial-101', 'trial-102'], - evidenceRefs: ['Snap-A', 'snap-a', 'snap-b'], - }); - - const deadEndRes = await callTool(server, 'file_finding', { - kind: 'dead_end', - title: 'Short-interest 1d reversal', - summary: 'No net edge after realistic borrow and spread costs.', - trialRefs: ['trial-101'], - }); - - expect(deadEndRes.isError).toBe(false); - expect(deadEndRes.payload).toEqual({ - id: 'finding-0002', - createdAt: '2025-03-01T10:01:00.000Z', - created: true, - }); - expect(fake.stored[1]).toEqual({ - id: 'finding-0002', - kind: 'dead_end', - title: 'Short-interest 1d reversal', - status: 'pending_review', - createdAt: '2025-03-01T10:01:00.000Z', - summary: 'No net edge after realistic borrow and spread costs.', - trialRefs: ['trial-101'], - evidenceRefs: [], - }); - expect(fake.invokedWriteMethods).toEqual(['appendFinding', 'appendFinding']); - }); - - test('rejects invalid inputs, blank or over-length fields, raw array limits, unknown fields, and metadata overrides with zero writes', async () => { - const fake = createSharedFindingsFake(); - const trialLookup = createFakeTrialLookup(); - const clock = createFixedClock(); - const idGen = createFixedIdGenerator(); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: idGen.newId, - now: clock.now, - }), - ], - }); - - const validBase = { - kind: 'finding', - title: 'Valid title', - summary: 'Valid research-visible summary', - trialRefs: ['trial-101'], - }; - - const invalidCases: readonly { - readonly label: string; - readonly args: Record; - readonly forbiddenSubstring?: string; - }[] = [ - { label: 'missing trialRefs', args: { kind: 'finding', title: 'T', summary: 'S' } }, - { label: 'empty trialRefs', args: { ...validBase, trialRefs: [] } }, - { label: 'blank trialRef', args: { ...validBase, trialRefs: [' '] } }, - { label: 'blank evidenceRef', args: { ...validBase, evidenceRefs: [' '] } }, - { label: 'blank title', args: { ...validBase, title: ' ' } }, - { label: 'blank summary', args: { ...validBase, summary: '\t\n ' } }, - { label: 'blank idempotencyKey', args: { ...validBase, idempotencyKey: ' ' } }, - { - label: 'over-length title', - args: { ...validBase, title: 'a'.repeat(FILE_FINDING_MAX_TITLE_LENGTH + 1) }, - }, - { - label: 'over-length summary', - args: { ...validBase, summary: 's'.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH + 1) }, - }, - { - label: 'over-length trialRef', - args: { ...validBase, trialRefs: ['r'.repeat(FILE_FINDING_MAX_REF_LENGTH + 1)] }, - }, - { - label: 'over-length evidenceRef', - args: { ...validBase, evidenceRefs: ['e'.repeat(FILE_FINDING_MAX_REF_LENGTH + 1)] }, - }, - { - label: 'over-length idempotencyKey', - args: { - ...validBase, - idempotencyKey: 'k'.repeat(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH + 1), - }, - }, - { - label: 'raw trialRefs exceeds 32 even with duplicates', - args: { - ...validBase, - trialRefs: Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS + 1 }, () => 'trial-101'), - }, - }, - { - label: 'raw evidenceRefs exceeds 32 even with duplicates', - args: { - ...validBase, - evidenceRefs: Array.from( - { length: FILE_FINDING_MAX_EVIDENCE_REFS + 1 }, - () => 'snap-01' - ), - }, - }, - { - label: 'invalid kind does not echo caller value', - args: { ...validBase, kind: 'vault_secret_kind_sentinel' }, - forbiddenSubstring: 'vault_secret_kind_sentinel', - }, - { label: 'invalid title type', args: { ...validBase, title: 123 } }, - { label: 'invalid trialRefs type', args: { ...validBase, trialRefs: 'trial-101' } }, - { - label: 'caller-supplied id rejected', - args: { ...validBase, id: 'attacker-id' }, - forbiddenSubstring: 'attacker-id', - }, - { - label: 'caller-supplied status rejected', - args: { ...validBase, status: 'confirmed' }, - forbiddenSubstring: 'confirmed', - }, - { - label: 'caller-supplied createdAt rejected', - args: { ...validBase, createdAt: '2020-01-01T00:00:00.000Z' }, - forbiddenSubstring: '2020-01-01', - }, - { - label: 'holdout scope rejected without echoing key', - args: { ...validBase, scope: 'vault_evaluation_only' }, - forbiddenSubstring: 'scope', - }, - { - label: 'holdout vault_evaluation_only rejected without echoing key', - args: { ...validBase, vault_evaluation_only: true }, - forbiddenSubstring: 'vault_evaluation_only', - }, - { - label: 'holdout vaultCutoffTs rejected without echoing key', - args: { ...validBase, vaultCutoffTs: 1_700_000_000_000 }, - forbiddenSubstring: 'vaultCutoffTs', - }, - { - label: 'unknown-key sentinel rejected without echoing sentinel', - args: { ...validBase, vaultHoldoutKeySentinel_XYZ: 'secret-value' }, - forbiddenSubstring: 'vaultHoldoutKeySentinel_XYZ', - }, - ]; - - for (const testCase of invalidCases) { - const res = await callTool(server, 'file_finding', testCase.args); - expect(res.isError).toBe(true); - if (testCase.forbiddenSubstring !== undefined) { - expect(res.text).not.toContain(testCase.forbiddenSubstring); - } - if ( - testCase.label.includes('unknown-key') || - testCase.label.includes('holdout') || - testCase.label.includes('caller-supplied') - ) { - expect(res.text).toContain(FILE_FINDING_ERROR_UNKNOWN_KEYS); - } - } - - expect(fake.stored).toHaveLength(0); - expect(fake.appendCalls).toHaveLength(0); - expect(trialLookup.queriedRefs).toHaveLength(0); - expect(idGen.calls).toBe(0); - expect(clock.calls).toBe(0); - - // Raw 32 duplicate entries are accepted (bounds applied before dedup). - const maxRawRes = await callTool(server, 'file_finding', { - ...validBase, - trialRefs: Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS }, () => 'trial-101'), - evidenceRefs: Array.from({ length: FILE_FINDING_MAX_EVIDENCE_REFS }, () => 'snap-1'), - }); - expect(maxRawRes.isError).toBe(false); - expect(fake.stored).toHaveLength(1); - expect(fake.stored[0]?.trialRefs).toEqual(['trial-101']); - expect(fake.stored[0]?.evidenceRefs).toEqual(['snap-1']); - }); - - test('rejects unknown and Vault-only trial refs identically with zero writes and zero metadata generation', async () => { - const fake = createSharedFindingsFake(); - const trialLookup = createFakeTrialLookup({ - researchVisibleRefs: ['trial-101'], - vaultOnlyRefs: ['trial-vault-only-secret'], - }); - const clock = createFixedClock(); - const idGen = createFixedIdGenerator(); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: idGen.newId, - now: clock.now, - }), - ], - }); - - const unknownRes = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Mixed valid and unknown ref', - summary: 'Should fail before writing.', - trialRefs: ['trial-101', 'trial-unknown-secret-ref'], - }); - - const vaultRes = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Mixed valid and Vault-only ref', - summary: 'Should fail identically to unknown ref.', - trialRefs: ['trial-101', 'trial-vault-only-secret'], - }); - - expect(unknownRes.isError).toBe(true); - expect(vaultRes.isError).toBe(true); - expect(unknownRes.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - expect(vaultRes.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); - expect(unknownRes.text).not.toContain('trial-unknown-secret-ref'); - expect(vaultRes.text).not.toContain('trial-vault-only-secret'); - expect(fake.stored).toHaveLength(0); - expect(fake.appendCalls).toHaveLength(0); - expect(idGen.calls).toBe(0); - expect(clock.calls).toBe(0); - }); - - test('sanitizes lookup and append exceptions so DSNs and stack markers never leak', async () => { - const fakeDsn = 'postgres://writer:supersecret@10.0.0.51:5432/trading_bot'; - const stackMarker = 'at internalPgPoolQuery (/srv/stock-bot/secret-adapter.ts:91:13)'; - - const lookupErr = new Error(`Lookup failed on ${fakeDsn}\n ${stackMarker}`); - lookupErr.name = 'PgConnectionError'; - - const lookupFake = createSharedFindingsFake(); - const failingLookup = createFakeTrialLookup({ throwError: lookupErr }); - const lookupServer = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: lookupFake.writePort, - trialLookup: failingLookup.port, - newId: createFixedIdGenerator().newId, - now: createFixedClock().now, - }), - ], - }); - - const lookupRes = await callTool(lookupServer, 'file_finding', { - kind: 'finding', - title: 'Lookup failure test', - summary: 'Summary text', - trialRefs: ['trial-101'], - }); - expect(lookupRes.isError).toBe(true); - expect(lookupRes.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(lookupRes.text).not.toContain(fakeDsn); - expect(lookupRes.text).not.toContain(stackMarker); - expect(lookupRes.text).not.toContain('PgConnectionError'); - expect(lookupFake.appendCalls).toHaveLength(0); - - const appendErr = new Error(`INSERT failed on ${fakeDsn}\n ${stackMarker}`); - appendErr.name = 'DatabaseWriteError'; - const appendFake = createSharedFindingsFake({ alwaysAppendError: appendErr }); - const appendServer = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: appendFake.writePort, - trialLookup: createFakeTrialLookup().port, - newId: createFixedIdGenerator().newId, - now: createFixedClock().now, - }), - ], - }); - - const appendRes = await callTool(appendServer, 'file_finding', { - kind: 'finding', - title: 'Append failure test', - summary: 'Summary text', - trialRefs: ['trial-101'], - }); - expect(appendRes.isError).toBe(true); - expect(appendRes.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(appendRes.text).not.toContain(fakeDsn); - expect(appendRes.text).not.toContain(stackMarker); - expect(appendRes.text).not.toContain('DatabaseWriteError'); - }); - - test('enforces idempotency replays, per-field conflicts, concurrent retries across instances, post-failure retry, and independent unkeyed calls', async () => { - const fake = createSharedFindingsFake(); - const trialLookup = createFakeTrialLookup(); - const clock = createFixedClock('2025-03-01T14:00:00.000Z', 60_000); - const idGen = createFixedIdGenerator('idem'); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: idGen.newId, - now: clock.now, - }), - ], - }); - - const first = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Momentum crowding signal', - summary: 'Observed IC decay during high volatility regimes.', - trialRefs: ['trial-102', 'trial-101'], - idempotencyKey: ' key-001 ', - }); - expect(first.isError).toBe(false); - expect(first.payload).toEqual({ - id: 'idem-0001', - createdAt: '2025-03-01T14:00:00.000Z', - created: true, - }); - expect(fake.stored).toHaveLength(1); - - // Replay with whitespace, duplicate/reordered refs, and explicit empty evidenceRefs. - const replay = await callTool(server, 'file_finding', { - kind: 'finding', - title: ' Momentum crowding signal ', - summary: ' Observed IC decay during high volatility regimes. ', - trialRefs: ['trial-101', ' trial-102 ', 'trial-101'], - evidenceRefs: [], - idempotencyKey: 'key-001', - }); - expect(replay.isError).toBe(false); - expect(replay.payload).toEqual({ - id: 'idem-0001', - createdAt: '2025-03-01T14:00:00.000Z', - created: false, - }); - expect(fake.stored).toHaveLength(1); - - // Changing each normalized payload field in turn causes a conflict with zero extra rows. - const conflictPayloads: readonly Record[] = [ - { - kind: 'dead_end', - title: 'Momentum crowding signal', - summary: 'Observed IC decay during high volatility regimes.', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: [], - idempotencyKey: 'key-001', - }, - { - kind: 'finding', - title: 'Different title', - summary: 'Observed IC decay during high volatility regimes.', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: [], - idempotencyKey: 'key-001', - }, - { - kind: 'finding', - title: 'Momentum crowding signal', - summary: 'Different summary', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: [], - idempotencyKey: 'key-001', - }, - { - kind: 'finding', - title: 'Momentum crowding signal', - summary: 'Observed IC decay during high volatility regimes.', - trialRefs: ['trial-101'], - evidenceRefs: [], - idempotencyKey: 'key-001', - }, - { - kind: 'finding', - title: 'Momentum crowding signal', - summary: 'Observed IC decay during high volatility regimes.', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: ['snap-extra'], - idempotencyKey: 'key-001', - }, - ]; - - for (const conflictArgs of conflictPayloads) { - const res = await callTool(server, 'file_finding', conflictArgs); - expect(res.isError).toBe(true); - expect(res.text).toBe(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); - } - expect(fake.stored).toHaveLength(1); - - // Concurrent same-key calls across two separate tool instances sharing one port. - const concurrentFake = createSharedFindingsFake({ delayFirstAppendMs: 10 }); - const toolA = createFileFindingTool({ - port: concurrentFake.writePort, - trialLookup: trialLookup.port, - newId: createFixedIdGenerator('instA').newId, - now: createFixedClock('2025-03-02T00:00:00.000Z').now, - }); - const toolB = createFileFindingTool({ - port: concurrentFake.writePort, - trialLookup: trialLookup.port, - newId: createFixedIdGenerator('instB').newId, - now: createFixedClock('2025-03-02T05:00:00.000Z').now, - }); - const concurrentArgs = { - kind: 'finding', - title: 'Concurrent filing', - summary: 'Submitted concurrently by two retries.', - trialRefs: ['trial-101'], - idempotencyKey: 'concurrent-key', - }; - - const [resA, resB] = await Promise.all([ - toolA.execute(concurrentArgs), - toolB.execute(concurrentArgs), - ]); - expect(resA.isError).toBeUndefined(); - expect(resB.isError).toBeUndefined(); - const payloadA = JSON.parse(resA.content[0]?.text ?? '') as FileFindingResultPayload; - const payloadB = JSON.parse(resB.content[0]?.text ?? '') as FileFindingResultPayload; - expect(concurrentFake.stored).toHaveLength(1); - expect(payloadA.id).toBe(payloadB.id); - expect(payloadA.createdAt).toBe(payloadB.createdAt); - expect([payloadA.created, payloadB.created].sort()).toEqual([false, true]); - - // Retry after an injected pre-commit failure succeeds cleanly. - const retryFake = createSharedFindingsFake({ - failNextAppendError: new Error('transient pre-commit timeout'), - }); - const retryServer = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: retryFake.writePort, - trialLookup: trialLookup.port, - newId: createFixedIdGenerator('retry').newId, - now: createFixedClock('2025-03-03T08:00:00.000Z').now, - }), - ], - }); - - const failedAttempt = await callTool(retryServer, 'file_finding', { - kind: 'dead_end', - title: 'Retry after failure', - summary: 'First attempt fails before commit.', - trialRefs: ['trial-101'], - idempotencyKey: 'retry-key', - }); - expect(failedAttempt.isError).toBe(true); - expect(failedAttempt.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); - expect(retryFake.stored).toHaveLength(0); - - const retryAttempt = await callTool(retryServer, 'file_finding', { - kind: 'dead_end', - title: 'Retry after failure', - summary: 'First attempt fails before commit.', - trialRefs: ['trial-101'], - idempotencyKey: 'retry-key', - }); - expect(retryAttempt.isError).toBe(false); - expect(retryAttempt.payload).toEqual({ - id: 'retry-0002', - createdAt: '2025-03-03T08:01:00.000Z', - created: true, - }); - expect(retryFake.stored).toHaveLength(1); - - // Unkeyed calls with identical payloads are independent. - const unkeyed1 = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Unkeyed entry', - summary: 'Independent unkeyed filing.', - trialRefs: ['trial-101'], - }); - const unkeyed2 = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Unkeyed entry', - summary: 'Independent unkeyed filing.', - trialRefs: ['trial-101'], - }); - expect(unkeyed1.isError).toBe(false); - expect(unkeyed2.isError).toBe(false); - expect(unkeyed1.payload?.created).toBe(true); - expect(unkeyed2.payload?.created).toBe(true); - expect(unkeyed1.payload?.id).not.toBe(unkeyed2.payload?.id); - expect(fake.stored).toHaveLength(3); - }); - - test('advertises strict schema via tools/list and round-trips filed records through read_knowledge', async () => { - const fake = createSharedFindingsFake(); - const trialLookup = createFakeTrialLookup(); - const clock = createFixedClock('2025-03-04T09:30:00.000Z', 120_000); - const idGen = createFixedIdGenerator('kb'); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: idGen.newId, - now: clock.now, - }), - createReadKnowledgeTool({ - port: fake.knowledgePort, - }), - ], - }); - - const listRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'list-1', - method: 'tools/list', - }) - ); - expect(listRaw).not.toBeNull(); - const listParsed = JSON.parse(listRaw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - type: string; - properties: Record>; - required?: string[]; - additionalProperties: boolean; - }; - }[]; - }; - }; - - expect(listParsed.result.tools.map(t => t.name)).toEqual(['file_finding', 'read_knowledge']); - const tool = listParsed.result.tools.find(t => t.name === 'file_finding'); - expect(tool).toBeDefined(); - expect(tool?.inputSchema.type).toBe('object'); - expect(tool?.inputSchema.additionalProperties).toBe(false); - expect(tool?.inputSchema.required).toEqual(['kind', 'title', 'summary', 'trialRefs']); - expect(tool?.inputSchema.properties.kind).toMatchObject({ - type: 'string', - enum: [...FILE_FINDING_KINDS], - }); - expect(tool?.inputSchema.properties.title).toMatchObject({ - type: 'string', - minLength: 1, - maxLength: FILE_FINDING_MAX_TITLE_LENGTH, - }); - expect(tool?.inputSchema.properties.summary).toMatchObject({ - type: 'string', - minLength: 1, - maxLength: FILE_FINDING_MAX_SUMMARY_LENGTH, - }); - expect(tool?.inputSchema.properties.trialRefs).toMatchObject({ - type: 'array', - minItems: 1, - maxItems: FILE_FINDING_MAX_TRIAL_REFS, - items: { type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_REF_LENGTH }, - }); - expect(tool?.inputSchema.properties.evidenceRefs).toMatchObject({ - type: 'array', - maxItems: FILE_FINDING_MAX_EVIDENCE_REFS, - default: [], - items: { type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_REF_LENGTH }, - }); - expect(tool?.inputSchema.properties.idempotencyKey).toMatchObject({ - type: 'string', - minLength: 1, - maxLength: FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, - }); - expect(tool?.inputSchema.properties.id).toBeUndefined(); - expect(tool?.inputSchema.properties.status).toBeUndefined(); - expect(tool?.inputSchema.properties.createdAt).toBeUndefined(); - expect(tool?.inputSchema.properties.scope).toBeUndefined(); - expect(tool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); - expect(tool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); - - // File both kinds via tools/call and read each back through read_knowledge. - const filedFinding = await callTool( - server, - 'file_finding', - { - kind: 'finding', - title: ' Event-study drift after SEC 8-K ', - summary: ' CAR peaks on session +2 and persists through +5. ', - trialRefs: ['trial-102', 'trial-101', 'trial-102'], - evidenceRefs: ['ev-html-2', 'ev-html-1'], - }, - 'call-f1' - ); - expect(filedFinding.isError).toBe(false); - const findingId = filedFinding.payload?.id as string; - - const filedDeadEnd = await callTool( - server, - 'file_finding', - { - kind: 'dead_end', - title: 'Intraday gap fade on microcaps', - summary: 'Edge disappears once 15 bps slippage is modeled.', - trialRefs: ['9007199254740993123'], - }, - 'call-f2' - ); - expect(filedDeadEnd.isError).toBe(false); - const deadEndId = filedDeadEnd.payload?.id as string; - - const readFinding = await callTool( - server, - 'read_knowledge', - { source: 'findings', id: findingId }, - 'call-r1' - ); - expect(readFinding.isError).toBe(false); - expect(readFinding.payload).toEqual({ - rowCount: 1, - sources: { library: 0, findings: 1, provider_caveats: 0 }, - rows: [ - { - source: 'findings', - id: findingId, - title: 'Event-study drift after SEC 8-K', - status: 'pending_review', - createdAt: '2025-03-04T09:30:00.000Z', - summary: 'CAR peaks on session +2 and persists through +5.', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: ['ev-html-1', 'ev-html-2'], - truncated: false, - }, - ], - }); - expect(fake.stored.find(r => r.id === findingId)?.kind).toBe('finding'); - - const readDeadEnd = await callTool( - server, - 'read_knowledge', - { source: 'findings', id: deadEndId }, - 'call-r2' - ); - expect(readDeadEnd.isError).toBe(false); - expect(readDeadEnd.payload).toEqual({ - rowCount: 1, - sources: { library: 0, findings: 1, provider_caveats: 0 }, - rows: [ - { - source: 'findings', - id: deadEndId, - title: 'Intraday gap fade on microcaps', - status: 'pending_review', - createdAt: '2025-03-04T09:32:00.000Z', - summary: 'Edge disappears once 15 bps slippage is modeled.', - trialRefs: ['9007199254740993123'], - evidenceRefs: [], - truncated: false, - }, - ], - }); - expect(fake.stored.find(r => r.id === deadEndId)?.kind).toBe('dead_end'); - }); - - test('produces bit-identical receipts, stored records, and read-backs across deterministic replays', async () => { - async function runReplay() { - const fake = createSharedFindingsFake(); - const trialLookup = createFakeTrialLookup(); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createFileFindingTool({ - port: fake.writePort, - trialLookup: trialLookup.port, - newId: createFixedIdGenerator('rep').newId, - now: createFixedClock('2025-03-05T00:00:00.000Z', 30_000).now, - }), - createReadKnowledgeTool({ port: fake.knowledgePort }), - ], - }); - - const r1 = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Replay finding', - summary: 'Deterministic summary.', - trialRefs: ['trial-102', 'trial-101'], - evidenceRefs: ['ev-b', 'ev-a'], - idempotencyKey: 'rep-key-1', - }); - const r2 = await callTool(server, 'file_finding', { - kind: 'finding', - title: 'Replay finding', - summary: 'Deterministic summary.', - trialRefs: ['trial-101', 'trial-102'], - evidenceRefs: ['ev-a', 'ev-b'], - idempotencyKey: 'rep-key-1', - }); - const r3 = await callTool(server, 'read_knowledge', { - source: 'findings', - }); - return { - receipts: [r1.payload, r2.payload], - stored: fake.stored, - knowledge: r3.payload, - }; - } - - const firstRun = await runReplay(); - const secondRun = await runReplay(); - expect(secondRun).toEqual(firstRun); - }); - - test('validates factory options eagerly and keeps MCP symbols out of browser-safe root export', () => { - const validPort = createSharedFindingsFake().writePort; - const validLookup = createFakeTrialLookup().port; - const validNewId = () => 'id-1'; - const validNow = () => Date.UTC(2025, 2, 1); - - expect(() => createFileFindingTool(null as never)).toThrow(/options/i); - expect(() => - createFileFindingTool({ - port: {} as never, - trialLookup: validLookup, - newId: validNewId, - now: validNow, - }) - ).toThrow(/port/i); - expect(() => - createFileFindingTool({ - port: validPort, - trialLookup: {} as never, - newId: validNewId, - now: validNow, - }) - ).toThrow(/trialLookup/i); - expect(() => - createFileFindingTool({ - port: validPort, - trialLookup: validLookup, - newId: 'not-a-fn' as never, - now: validNow, - }) - ).toThrow(/newId/i); - expect(() => - createFileFindingTool({ - port: validPort, - trialLookup: validLookup, - newId: validNewId, - now: 'not-a-fn' as never, - }) - ).toThrow(/now/i); - - expect( - fileFindingInputSchema.safeParse({ - kind: 'finding', - title: 'Schema export sanity check', - summary: 'Direct schema parse works.', - trialRefs: ['trial-101'], - }).success - ).toBe(true); - - expect(Object.keys(rootResearchExports)).not.toContain('createFileFindingTool'); - }); -}); diff --git a/libs/research/test/mcp-protocol.test.ts b/libs/research/test/mcp-protocol.test.ts deleted file mode 100644 index 511a8f7e..00000000 --- a/libs/research/test/mcp-protocol.test.ts +++ /dev/null @@ -1,454 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { z } from 'zod'; -import * as rootResearchExports from '../src/index'; -import { - JSON_RPC_ERROR_CODES, - MCP_PROTOCOL_VERSION, - createMcpServer, - defineMcpTool, - zodObjectToJsonSchema, -} from '../src/mcp/index'; - -interface JsonRpcParsedResponse { - jsonrpc: string; - id: string | number | null; - result?: Record; - error?: { - code: number; - message: string; - data?: unknown; - }; -} - -function parseResponse(raw: string | null): JsonRpcParsedResponse { - expect(raw).not.toBeNull(); - return JSON.parse(raw as string) as JsonRpcParsedResponse; -} - -describe('MCP protocol & server core', () => { - test('initialize returns protocolVersion, serverInfo, and capabilities.tools', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: MCP_PROTOCOL_VERSION, - capabilities: {}, - clientInfo: { name: 'test-client', version: '1.0.0' }, - }, - }) - ); - - const response = parseResponse(raw); - expect(response.jsonrpc).toBe('2.0'); - expect(response.id).toBe(1); - expect(response.error).toBeUndefined(); - expect(response.result).toEqual({ - protocolVersion: MCP_PROTOCOL_VERSION, - capabilities: { tools: {} }, - serverInfo: { - name: 'stock-bot-research', - version: '0.1.0', - }, - }); - }); - - test('notifications/initialized returns null (no response)', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - method: 'notifications/initialized', - }) - ); - - expect(raw).toBeNull(); - }); - - test('ping returns empty object result', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'ping-1', - method: 'ping', - }) - ); - - const response = parseResponse(raw); - expect(response.id).toBe('ping-1'); - expect(response.result).toEqual({}); - }); - - test('echoes string and numeric request ids verbatim (including 0 and negative integers)', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const ids: readonly (string | number)[] = ['req-abc', '', 0, -42, 9007199254740991]; - for (const id of ids) { - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id, - method: 'ping', - }) - ); - const response = parseResponse(raw); - expect(response.id).toBe(id); - } - }); - - test('malformed JSON returns -32700 with id: null', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const raw = await server.handleMessage('{not valid json'); - const response = parseResponse(raw); - expect(response.id).toBeNull(); - expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); - }); - - test('non-JSON-RPC objects and explicit invalid id return -32600', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const badPayloads = [ - '42', - '"hello"', - 'null', - '[]', - JSON.stringify({ foo: 'bar' }), - JSON.stringify({ jsonrpc: '1.0', id: 1, method: 'ping' }), - JSON.stringify({ jsonrpc: '2.0', id: null, method: 'ping' }), - JSON.stringify({ jsonrpc: '2.0', id: true, method: 'ping' }), - JSON.stringify({ jsonrpc: '2.0', id: { nested: 1 }, method: 'ping' }), - JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping', extra: true }), - ]; - - for (const payload of badPayloads) { - const raw = await server.handleMessage(payload); - const response = parseResponse(raw); - expect(response.id).toBeNull(); - expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_REQUEST); - } - }); - - test('unknown method returns -32601 echoing request id', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'unknown-1', - method: 'resources/list', - }) - ); - - const response = parseResponse(raw); - expect(response.id).toBe('unknown-1'); - expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.METHOD_NOT_FOUND); - }); - - test('tools/call rejects unknown tool name and malformed params with -32602', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [], - }); - - const unknownToolRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 10, - method: 'tools/call', - params: { name: 'does_not_exist', arguments: {} }, - }) - ); - const unknownToolResp = parseResponse(unknownToolRaw); - expect(unknownToolResp.id).toBe(10); - expect(unknownToolResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); - - const badParamsRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 11, - method: 'tools/call', - params: { name: 123, arguments: 'not-an-object' }, - }) - ); - const badParamsResp = parseResponse(badParamsRaw); - expect(badParamsResp.id).toBe(11); - expect(badParamsResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); - }); - - test('invalid tool arguments return isError: true with readable message and zero handler calls', async () => { - let handlerCalls = 0; - const echoTool = defineMcpTool({ - name: 'echo_count', - description: 'Echoes a positive integer count.', - inputSchema: z.object({ count: z.number().int().min(1) }).strict(), - handler(input) { - handlerCalls += 1; - return { - content: [{ type: 'text', text: String(input.count) }], - }; - }, - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [echoTool], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 20, - method: 'tools/call', - params: { - name: 'echo_count', - arguments: { count: 0, unexpected: true }, - }, - }) - ); - - expect(handlerCalls).toBe(0); - const response = parseResponse(raw); - expect(response.id).toBe(20); - expect(response.error).toBeUndefined(); - const result = response.result as { - isError?: boolean; - content: { type: string; text: string }[]; - }; - expect(result.isError).toBe(true); - expect(result.content[0]?.type).toBe('text'); - expect(result.content[0]?.text).toContain('Invalid arguments for tool "echo_count"'); - }); - - test('throwing tool handler returns isError: true with sanitized error and zero stack trace 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'); - }); -}); diff --git a/libs/research/test/mcp-query-data.test.ts b/libs/research/test/mcp-query-data.test.ts deleted file mode 100644 index 664e5c13..00000000 --- a/libs/research/test/mcp-query-data.test.ts +++ /dev/null @@ -1,783 +0,0 @@ -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 { - barsCalls.push(q); - if (options?.barsError !== undefined) { - const err = options.barsError; - return { - [Symbol.asyncIterator]() { - return { - next() { - return Promise.reject(err); - }, - }; - }, - }; - } - return { - async *[Symbol.asyncIterator]() { - for (const batch of batches) { - yield batch; - } - }, - }; - }, - async universe(q: UniverseQuery): Promise { - universeCalls.push(q); - if (options?.universeError !== undefined) { - throw options.universeError; - } - return [...universeIds]; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - - return { barsCalls, universeCalls, store }; -} - -async function callQueryData( - fake: FakeStoreState, - args: Record -): Promise<{ - rawResponse: string; - isError: boolean; - text: string; -}> { - const tool = createQueryDataTool({ - store: fake.store, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [tool], - }); - - const rawResponse = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'q1', - method: 'tools/call', - params: { - name: 'query_data', - arguments: args, - }, - }) - ); - - expect(rawResponse).not.toBeNull(); - const parsed = JSON.parse(rawResponse as string) as { - result: { - isError?: boolean; - content: { type: string; text: string }[]; - }; - }; - return { - rawResponse: rawResponse as string, - isError: parsed.result.isError === true, - text: parsed.result.content[0]?.text ?? '', - }; -} - -describe('MCP query_data tool', () => { - test('tools/list exposes query_data with strict inputSchema and omits scope / vault_evaluation_only', async () => { - const fake = createFakeStore(); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: fake.store, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - ], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/list', - }) - ); - - const parsed = JSON.parse(raw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - type: string; - properties: Record; - required?: string[]; - additionalProperties: boolean; - }; - }[]; - }; - }; - - expect(parsed.result.tools).toHaveLength(1); - const tool = parsed.result.tools[0]; - expect(tool?.name).toBe('query_data'); - expect(tool?.inputSchema.type).toBe('object'); - expect(tool?.inputSchema.additionalProperties).toBe(false); - expect(tool?.inputSchema.required).toEqual(['from', 'to']); - - const propKeys = Object.keys(tool?.inputSchema.properties ?? {}); - expect(propKeys).toContain('listingIds'); - expect(propKeys).toContain('universe'); - expect(propKeys).toContain('from'); - expect(propKeys).toContain('to'); - expect(propKeys).toContain('limit'); - expect(propKeys).not.toContain('scope'); - expect(propKeys).not.toContain('vault_evaluation_only'); - expect(tool?.inputSchema.required).not.toContain('scope'); - expect(tool?.inputSchema.required).not.toContain('vault_evaluation_only'); - }); - - test('returns pre-cutoff rows and records scope === vault_fenced on every bars() call', async () => { - const bar1 = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150.5); - const bar2 = makeBar(101, Date.UTC(2025, 2, 30, 20, 0, 0), 152.0); - const fake = createFakeStore({ - batches: [{ rows: [bar1, bar2] }], - }); - - const { isError, text } = await callQueryData(fake, { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - }); - - expect(isError).toBe(false); - expect(fake.barsCalls).toHaveLength(1); - expect(fake.barsCalls[0]?.scope).toBe('vault_fenced'); - - const payload = JSON.parse(text) as QueryDataResultPayload; - expect(payload.scope).toBe('vault_fenced'); - expect(payload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS); - expect(payload.clampedTo).toBe(false); - expect(payload.rowCount).toBe(2); - expect(payload.truncated).toBe(false); - expect(payload.rows).toEqual([bar1, bar2]); - }); - - test('enforces default limit, explicit limit, max limit, and rejects out-of-bounds limits with zero store calls', async () => { - const totalRows = QUERY_DATA_MAX_LIMIT + 5; - const allRows: BarRecord[] = []; - for (let i = 0; i < totalRows; i += 1) { - allRows.push(makeBar(101, Date.UTC(2024, 0, 1, 0, 0, 0) + i * 60_000, 100 + i * 0.01)); - } - - // Omitted limit -> caps at QUERY_DATA_DEFAULT_LIMIT with truncated: true - const defaultFake = createFakeStore({ batches: [{ rows: allRows }] }); - const defaultRes = await callQueryData(defaultFake, { - listingIds: [101], - from: '2024-01-01', - to: '2025-03-01', - }); - expect(defaultRes.isError).toBe(false); - const defaultPayload = JSON.parse(defaultRes.text) as QueryDataResultPayload; - expect(defaultPayload.limit).toBe(QUERY_DATA_DEFAULT_LIMIT); - expect(defaultPayload.rowCount).toBe(QUERY_DATA_DEFAULT_LIMIT); - expect(defaultPayload.truncated).toBe(true); - - // Explicit limit -> caps at requested value - const explicitFake = createFakeStore({ batches: [{ rows: allRows }] }); - const explicitRes = await callQueryData(explicitFake, { - listingIds: [101], - from: '2024-01-01', - to: '2025-03-01', - limit: 3, - }); - expect(explicitRes.isError).toBe(false); - const explicitPayload = JSON.parse(explicitRes.text) as QueryDataResultPayload; - expect(explicitPayload.limit).toBe(3); - expect(explicitPayload.rowCount).toBe(3); - expect(explicitPayload.truncated).toBe(true); - - // Exact QUERY_DATA_MAX_LIMIT -> succeeds - const maxFake = createFakeStore({ batches: [{ rows: allRows }] }); - const maxRes = await callQueryData(maxFake, { - listingIds: [101], - from: '2024-01-01', - to: '2025-03-01', - limit: QUERY_DATA_MAX_LIMIT, - }); - expect(maxRes.isError).toBe(false); - const maxPayload = JSON.parse(maxRes.text) as QueryDataResultPayload; - expect(maxPayload.rowCount).toBe(QUERY_DATA_MAX_LIMIT); - expect(maxPayload.truncated).toBe(true); - - // limit > QUERY_DATA_MAX_LIMIT or <= 0 -> isError: true with zero store calls - for (const badLimit of [QUERY_DATA_MAX_LIMIT + 1, 0, -5]) { - const badFake = createFakeStore({ batches: [{ rows: allRows }] }); - const badRes = await callQueryData(badFake, { - listingIds: [101], - from: '2024-01-01', - to: '2025-03-01', - limit: badLimit, - }); - expect(badRes.isError).toBe(true); - expect(badFake.barsCalls).toHaveLength(0); - expect(badFake.universeCalls).toHaveLength(0); - } - }); - - test('rejects scope, vault_evaluation_only, or unknown keys with isError: true and zero store calls', async () => { - const injectedPayloads: Record[] = [ - { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - scope: 'vault_evaluation_only', - }, - { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - scope: 'vault_fenced', - }, - { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - vault_evaluation_only: true, - }, - { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - unknownFlag: 'x', - }, - ]; - - for (const args of injectedPayloads) { - const fake = createFakeStore({ - batches: [{ rows: [makeBar(101, Date.UTC(2025, 2, 20, 20, 0, 0), 100)] }], - }); - const res = await callQueryData(fake, args); - expect(res.isError).toBe(true); - expect(fake.barsCalls).toHaveLength(0); - expect(fake.universeCalls).toHaveLength(0); - } - }); - - test('range starting at or after vaultCutoffTs returns isError: true naming VaultHoldoutFenceError with zero store calls', async () => { - const fake = createFakeStore({ - batches: [{ rows: [makeBar(101, Date.UTC(2025, 3, 5, 20, 0, 0), 200)] }], - }); - - const res = await callQueryData(fake, { - listingIds: [101], - from: '2025-03-31', - to: '2025-04-15', - }); - - expect(res.isError).toBe(true); - expect(res.text).toContain('VaultHoldoutFenceError'); - expect(fake.barsCalls).toHaveLength(0); - expect(fake.universeCalls).toHaveLength(0); - }); - - test('range straddling vaultCutoffTs clamps to/asOf strictly below cutoff', async () => { - const preBar = makeBar(101, Date.UTC(2025, 2, 30, 20, 0, 0), 150); - const fake = createFakeStore({ - batches: [{ rows: [preBar] }], - }); - - const res = await callQueryData(fake, { - listingIds: [101], - from: '2025-03-01', - to: '2025-04-30', - asOf: '2025-05-01', - }); - - expect(res.isError).toBe(false); - expect(fake.barsCalls).toHaveLength(1); - expect(fake.barsCalls[0]?.scope).toBe('vault_fenced'); - expect(Date.parse(fake.barsCalls[0]?.to ?? '')).toBe(VAULT_CUTOFF_TS - 1); - expect(Date.parse(fake.barsCalls[0]?.asOf ?? '')).toBe(VAULT_CUTOFF_TS - 1); - - const payload = JSON.parse(res.text) as QueryDataResultPayload; - expect(payload.clampedTo).toBe(true); - expect(payload.clampedAsOf).toBe(true); - expect(payload.toMs).toBe(VAULT_CUTOFF_TS - 1); - expect(payload.asOfMs).toBe(VAULT_CUTOFF_TS - 1); - expect(payload.rows).toEqual([preBar]); - }); - - test('defense-in-depth drops post-cutoff rows (ts >= cutoff or knownAt >= cutoff) from a leaky store', async () => { - const preBar = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150); - const leakyTsBar = makeBar(101, VAULT_CUTOFF_TS, 999); - const leakyFutureTsBar = makeBar(101, Date.UTC(2025, 3, 2, 20, 0, 0), 1000); - const leakyKnownAtBar = makeBar( - 101, - Date.UTC(2025, 2, 25, 20, 0, 0), - 148, - VAULT_CUTOFF_TS - ); - - const fake = createFakeStore({ - batches: [{ rows: [preBar, leakyTsBar, leakyFutureTsBar, leakyKnownAtBar] }], - }); - - const res = await callQueryData(fake, { - listingIds: [101], - from: '2025-03-01', - to: '2025-04-15', - }); - - expect(res.isError).toBe(false); - const payload = JSON.parse(res.text) as QueryDataResultPayload; - expect(payload.rowCount).toBe(1); - expect(payload.rows).toEqual([preBar]); - }); - - test('universe path resolves strictly pre-cutoff date and handles empty universe cleanly', async () => { - const preBar = makeBar(202, Date.UTC(2025, 2, 28, 20, 0, 0), 50); - const populatedFake = createFakeStore({ - universeIds: [202], - batches: [{ rows: [preBar] }], - }); - - const res = await callQueryData(populatedFake, { - universe: 'US_EQ', - from: '2025-03-01', - to: '2025-04-30', - }); - - expect(res.isError).toBe(false); - expect(populatedFake.universeCalls).toEqual([{ ref: 'US_EQ', date: '2025-03-30' }]); - expect(populatedFake.barsCalls).toHaveLength(1); - expect(populatedFake.barsCalls[0]?.listingIds).toEqual([202]); - expect(populatedFake.barsCalls[0]?.scope).toBe('vault_fenced'); - - // Empty universe -> zero bars() calls - const emptyFake = createFakeStore({ universeIds: [] }); - const emptyRes = await callQueryData(emptyFake, { - universe: 'CA_EQ', - from: '2025-03-01', - to: '2025-03-30', - }); - expect(emptyRes.isError).toBe(false); - expect(emptyFake.universeCalls).toHaveLength(1); - expect(emptyFake.barsCalls).toHaveLength(0); - const emptyPayload = JSON.parse(emptyRes.text) as QueryDataResultPayload; - expect(emptyPayload.rowCount).toBe(0); - expect(emptyPayload.rows).toEqual([]); - }); - - test('maps store domain errors 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([ - [101, [janBar101]], - [202, [janBar202]], - ]); - - const universeDates: string[] = []; - const store: MarketDataStore = { - async universe(q: UniverseQuery): Promise { - universeDates.push(q.date); - // Listing 202 resumed trading on 2025-03-26, so it is NOT active on 2025-03-03 - return q.date >= '2025-03-26' ? [101, 202] : [101]; - }, - bars(q: BarsQuery): AsyncIterable { - const rows = q.listingIds.flatMap(id => [...(allBarsByListing.get(id) ?? [])]); - return { - async *[Symbol.asyncIterator]() { - yield { rows }; - }, - }; - }, - crossSection() { - throw new MarketDataStoreNotImplementedError('crossSection'); - }, - fundamentalsAsOf() { - throw new MarketDataStoreNotImplementedError('fundamentalsAsOf'); - }, - events() { - throw new MarketDataStoreNotImplementedError('events'); - }, - shortsAsOf() { - throw new MarketDataStoreNotImplementedError('shortsAsOf'); - }, - macroAsOf() { - throw new MarketDataStoreNotImplementedError('macroAsOf'); - }, - fx() { - throw new MarketDataStoreNotImplementedError('fx'); - }, - }; - - const fake: FakeStoreState = { barsCalls: [], universeCalls: [], store }; - - // Date-only asOf earlier than to -> universe queried on 2025-03-03, excluding listing 202 - const dateOnlyRes = await callQueryData(fake, { - universe: 'US_EQ', - from: '2025-01-01', - to: '2025-03-28', - asOf: '2025-03-03', - }); - expect(dateOnlyRes.isError).toBe(false); - expect(universeDates).toEqual(['2025-03-03']); - const payload = JSON.parse(dateOnlyRes.text) as QueryDataResultPayload; - expect(payload.rows).toEqual([janBar101]); - - // Intraday asOf on 2025-03-03 -> uses completed UTC date 2025-03-02 - const intradayRes = await callQueryData(fake, { - universe: 'US_EQ', - from: '2025-01-01', - to: '2025-03-28', - asOf: '2025-03-03T12:00:00Z', - }); - expect(intradayRes.isError).toBe(false); - expect(universeDates).toEqual(['2025-03-03', '2025-03-02']); - }); - - test('DuckDB planner integration preserves microsecond bounds, accepts matching fenced adj_factors snapshot, and sanitizes snapshot errors', async () => { - const recordedQueries: { sql: string; params: readonly DuckDbParam[] }[] = []; - const expectedVaultCeilingMicros = VAULT_CUTOFF_TS * 1000 - 1; - const barTs = Date.UTC(2025, 2, 20, 20, 0, 0); - - const executor: DuckDbExecutor = { - async run() { - // no-op in memory - }, - async query(sql, params) { - recordedQueries.push({ sql, params }); - if (sql.includes('parquet_kv_metadata')) { - return [ - { key: `${ADJ_SNAPSHOT_KV_PREFIX}format_version`, value: String(ADJ_SNAPSHOT_FORMAT_VERSION) }, - { key: `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_kind`, value: 'point_in_time_fenced' }, - { key: `${ADJ_SNAPSHOT_KV_PREFIX}as_of_micros`, value: 'none' }, - { key: `${ADJ_SNAPSHOT_KV_PREFIX}vault_cutoff_micros`, value: String(VAULT_CUTOFF_TS * 1000) }, - { key: `${ADJ_SNAPSHOT_KV_PREFIX}rows_written`, value: '10' }, - { key: `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_checksum`, value: '0x0123456789abcdef' }, - ]; - } - return [ - { - listing_id: 101, - ts: barTs, - open: 99, - high: 101, - low: 98, - close: 100, - volume: 2_000, - vwap: 100, - known_at: barTs, - }, - ]; - }, - }; - - const duckStore = createDuckDbMarketDataStore({ - curatedRoot: '/mnt/data/stockbot/curated', - vaultCutoffTs: VAULT_CUTOFF_TS, - immutableAdjFactorsPath: '/mnt/data/stockbot/curated/snapshots/adj_2025_03_30.parquet', - executor, - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: duckStore, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - ], - }); - - // 1. Split-adjusted bars with omitted asOf and clamped to -> forwards .999999Z matching snapshot ceiling - const splitRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'duck-1', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [101], - from: '2025-03-01', - to: '2025-04-15', - adjustment: 'split', - }, - }, - }) - ); - const splitResp = JSON.parse(splitRaw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(splitResp.result.isError).toBeUndefined(); - const splitPayload = JSON.parse(splitResp.result.content[0]?.text ?? '{}') as QueryDataResultPayload; - expect(splitPayload.rowCount).toBe(1); - expect(expectedVaultCeilingMicros).toBe(Date.UTC(2025, 2, 30, 23, 59, 59, 999) * 1000 + 999); - const barsQuery1 = recordedQueries.find(q => q.sql.includes('bars_1d')); - expect(barsQuery1).toBeDefined(); - expect(barsQuery1?.params).toEqual([ - 101, - '2025-03-30T23:59:59.999999Z', - 101, - '2025-03-01T00:00:00.000Z', - '2025-03-30T23:59:59.999999Z', - '2025-03-30T23:59:59.999999Z', - ]); - - // 2. Caller-supplied sub-millisecond bounds within the fence are preserved verbatim - recordedQueries.length = 0; - const preciseRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'duck-2', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [101], - from: '2025-03-01T00:00:00.000123Z', - to: '2025-03-20T12:34:56.123456Z', - asOf: '2025-03-25T08:09:10.654321Z', - adjustment: 'raw', - }, - }, - }) - ); - const preciseResp = JSON.parse(preciseRaw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(preciseResp.result.isError).toBeUndefined(); - const barsQuery2 = recordedQueries.find(q => q.sql.includes('bars_1d')); - expect(barsQuery2?.params).toEqual([ - 101, - '2025-03-01T00:00:00.000123Z', - '2025-03-20T12:34:56.123456Z', - '2025-03-25T08:09:10.654321Z', - ]); - - // 3. Unpinned mutable adj_factors path fails closed without leaking internal filesystem path - const unpinnedStore = createDuckDbMarketDataStore({ - curatedRoot: '/mnt/data/stockbot/curated', - vaultCutoffTs: VAULT_CUTOFF_TS, - executor, - }); - const unpinnedServer = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: unpinnedStore, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - ], - }); - const unpinnedRaw = await unpinnedServer.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'duck-3', - method: 'tools/call', - params: { - name: 'query_data', - arguments: { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - adjustment: 'split', - }, - }, - }) - ); - const unpinnedResp = JSON.parse(unpinnedRaw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(unpinnedResp.result.isError).toBe(true); - const unpinnedText = unpinnedResp.result.content[0]?.text ?? ''; - expect(unpinnedText).toContain('AdjFactorsSnapshotError'); - expect(unpinnedText).not.toContain('/mnt/data/stockbot'); - expect(unpinnedText).not.toContain('part.parquet'); - }); - - test('raw JSON own __proto__ key in query_data arguments returns isError: true with zero store calls', async () => { - const fake = createFakeStore({ - batches: [{ rows: [makeBar(101, Date.UTC(2025, 2, 20, 20, 0, 0), 100)] }], - }); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store: fake.store, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - ], - }); - - const rawRequest = - '{"jsonrpc":"2.0","id":"proto-q","method":"tools/call","params":{"name":"query_data","arguments":{"listingIds":[101],"from":"2025-03-01","to":"2025-03-30","__proto__":{"scope":"vault_evaluation_only"}}}}'; - const rawResponse = await server.handleMessage(rawRequest); - const parsed = JSON.parse(rawResponse as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(parsed.result.isError).toBe(true); - expect(fake.barsCalls).toHaveLength(0); - expect(fake.universeCalls).toHaveLength(0); - }); - - test('repeated identical calls produce byte-identical JSON output', async () => { - const bar = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150.25); - const fake1 = createFakeStore({ batches: [{ rows: [bar] }] }); - const fake2 = createFakeStore({ batches: [{ rows: [bar] }] }); - - const args = { - listingIds: [101], - from: '2025-03-01', - to: '2025-03-30', - timeframe: '1d', - adjustment: 'raw', - limit: 10, - }; - - const res1 = await callQueryData(fake1, args); - const res2 = await callQueryData(fake2, args); - expect(res1.rawResponse).toBe(res2.rawResponse); - }); -}); diff --git a/libs/research/test/mcp-read-knowledge-qa.test.ts b/libs/research/test/mcp-read-knowledge-qa.test.ts deleted file mode 100644 index b9d233c5..00000000 --- a/libs/research/test/mcp-read-knowledge-qa.test.ts +++ /dev/null @@ -1,581 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - createMcpServer, - createReadKnowledgeTool, - type FindingQuery, - type FindingRecord, - type KnowledgePort, - type LibraryCardQuery, - type LibraryCardRecord, - type ProviderCaveatQuery, - type ProviderCaveatRecord, - READ_KNOWLEDGE_MAX_LIMIT, - READ_KNOWLEDGE_MAX_QUERY_LENGTH, - READ_KNOWLEDGE_MAX_TEXT_LENGTH, - type ReadKnowledgeResultPayload, -} from '../src/mcp/index'; - -// QA fixtures: deterministic in-memory KnowledgePort (no network, no Postgres, -// no filesystem). All timestamps are pinned ISO strings; shuffles use a seeded PRNG. - -const SECRET = 'postgres://admin:super-secret@10.0.0.51:5432/trading_bot'; - -function card(id: string, o: Partial = {}): LibraryCardRecord { - return { - id, - title: o.title ?? `Card ${id}`, - tags: o.tags ?? ['methodology'], - summary: o.summary ?? `Summary ${id}`, - body: o.body ?? `Body ${id}`, - }; -} - -function finding(id: string, o: Partial = {}): FindingRecord { - return { - id, - title: o.title ?? `Finding ${id}`, - status: o.status ?? 'confirmed', - createdAt: o.createdAt ?? '2025-01-15T12:00:00.000Z', - summary: o.summary ?? `Finding summary ${id}`, - trialRefs: o.trialRefs ?? [`trial-${id}`], - evidenceRefs: o.evidenceRefs ?? [`ev-${id}`], - }; -} - -function caveat(id: string, o: Partial = {}): ProviderCaveatRecord { - return { - id, - provider: o.provider ?? 'eodhd', - dataset: o.dataset ?? `dataset_${id}`, - caveat: o.caveat ?? `Caveat ${id}`, - createdAt: o.createdAt ?? '2025-01-20T08:30:00.000Z', - }; -} - -interface PortImpl { - readonly library?: (q: LibraryCardQuery) => unknown; - readonly findings?: (q: FindingQuery) => unknown; - readonly caveats?: (q: ProviderCaveatQuery) => unknown; -} - -function makePort(impl: PortImpl): { port: KnowledgePort; calls: string[] } { - const calls: string[] = []; - const port: KnowledgePort = { - listLibraryCards(q) { - calls.push('listLibraryCards'); - return (impl.library ?? (() => Promise.resolve([])))(q) as Promise< - readonly LibraryCardRecord[] - >; - }, - listFindings(q) { - calls.push('listFindings'); - return (impl.findings ?? (() => Promise.resolve([])))(q) as Promise< - readonly FindingRecord[] - >; - }, - listProviderCaveats(q) { - calls.push('listProviderCaveats'); - return (impl.caveats ?? (() => Promise.resolve([])))(q) as Promise< - readonly ProviderCaveatRecord[] - >; - }, - }; - return { port, calls }; -} - -function staticPort( - library: readonly LibraryCardRecord[], - findings: readonly FindingRecord[], - caveats: readonly ProviderCaveatRecord[] -): { port: KnowledgePort; calls: string[] } { - return makePort({ - library: async () => library, - findings: async () => findings, - caveats: async () => caveats, - }); -} - -async function call( - port: KnowledgePort, - args: Record | undefined -): Promise<{ isError: boolean; text: string; payload: ReadKnowledgeResultPayload | null }> { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [createReadKnowledgeTool({ port })], - }); - const params: Record = { name: 'read_knowledge' }; - if (args !== undefined) { - params.arguments = args; - } - const raw = await server.handleMessage( - JSON.stringify({ jsonrpc: '2.0', id: 'qa', method: 'tools/call', params }) - ); - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - const isError = parsed.result.isError === true; - const text = parsed.result.content[0]?.text ?? ''; - return { isError, text, payload: isError ? null : (JSON.parse(text) as ReadKnowledgeResultPayload) }; -} - -function expectSanitized(res: { isError: boolean; text: string }): void { - expect(res.isError).toBe(true); - expect(res.text).toMatch(/^[A-Za-z][A-Za-z0-9_]*: Tool execution failed\.$/); - for (const leak of ['super-secret', '10.0.0.51', 'trading_bot', 'postgres://', 'db.ts', ' at ']) { - expect(res.text).not.toContain(leak); - } -} - -function deepFreeze(value: T): T { - if (typeof value === 'object' && value !== null) { - for (const v of Object.values(value)) { - deepFreeze(v); - } - Object.freeze(value); - } - return value; -} - -// mulberry32 — seeded PRNG for reproducible shuffles. -function seededShuffle(items: readonly T[], seed: number): T[] { - let s = seed >>> 0; - const rand = (): number => { - s = (s + 0x6d2b79f5) >>> 0; - let t = s; - t = Math.imul(t ^ (t >>> 15), t | 1); - t ^= t + Math.imul(t ^ (t >>> 7), t | 61); - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; - const out = [...items]; - for (let i = out.length - 1; i > 0; i -= 1) { - const j = Math.floor(rand() * (i + 1)); - [out[i], out[j]] = [out[j] as T, out[i] as T]; - } - return out; -} - -describe('read_knowledge QA: port failures and malformed port output', () => { - test('non-Error rejections and synchronous throws carrying connection strings are sanitized', async () => { - const cases: PortImpl[] = [ - { library: () => Promise.reject(SECRET) }, - { findings: () => Promise.reject({ message: SECRET, stack: 'at /srv/db.ts:1' }) }, - { - caveats: () => { - throw new Error(SECRET); - }, - }, - { - library: () => { - const err = new Error(SECRET); - err.name = SECRET; - throw err; - }, - }, - ]; - for (const impl of cases) { - const { port } = makePort(impl); - const res = await call(port, { query: 'alpha' }); - expectSanitized(res); - } - }); - - test('malformed port responses map to a sanitized isError without echoing record contents', async () => { - const badResponses: PortImpl[] = [ - { library: async () => SECRET }, - { library: async () => undefined }, - { library: async () => [null] }, - { library: async () => [{ ...card('c1'), id: 42 }] }, - { library: async () => [{ ...card('c1'), tags: [SECRET, 7] }] }, - { library: async () => [{ ...card('c1'), tags: SECRET }] }, - { findings: async () => [{ ...finding('f1'), trialRefs: undefined }] }, - { findings: async () => [{ ...finding('f1'), createdAt: 1_700_000_000_000 }] }, - { caveats: async () => [{ ...caveat('v1'), caveat: { text: SECRET } }] }, - { caveats: async () => ({ rows: [caveat('v1')] }) }, - ]; - for (const impl of badResponses) { - const { port } = makePort(impl); - const res = await call(port, {}); - expectSanitized(res); - } - }); - - // Regression: port calls were started eagerly inside the Promise.all array literal, so a - // synchronous throw from a later source abandoned an earlier source's rejected promise. - // Bun treats that unhandled rejection as fatal: the MCP stdio process exits 1 after replying - // and prints the raw error (including any connection string) to stderr. Bun's test runner - // also reports it as an error between tests, so the scenario runs in a child process. - test('earlier async rejection combined with a later synchronous throw does not crash the process', () => { - const indexPath = new URL('../src/mcp/index.ts', import.meta.url).pathname; - const script = ` - import { createMcpServer, createReadKnowledgeTool } from ${JSON.stringify(indexPath)}; - const secret = ${JSON.stringify(SECRET)}; - const combos = [ - { listLibraryCards: () => Promise.reject(new Error(secret)), listFindings: () => { throw new Error('sync'); }, listProviderCaveats: async () => [] }, - { listLibraryCards: () => Promise.reject(new Error(secret)), listFindings: async () => [], listProviderCaveats: () => { throw new Error('sync'); } }, - { listLibraryCards: async () => [], listFindings: () => Promise.reject(new Error(secret)), listProviderCaveats: () => { throw new Error('sync'); } }, - ]; - for (const port of combos) { - const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [createReadKnowledgeTool({ port })] }); - const raw = await server.handleMessage(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'read_knowledge', arguments: {} } })); - console.log(JSON.parse(raw).result.content[0].text); - } - await new Promise(resolve => setTimeout(resolve, 20)); - console.log('DONE'); - `; - - const proc = Bun.spawnSync([process.execPath, '-e', script], { - stdout: 'pipe', - stderr: 'pipe', - timeout: 30_000, - }); - const stdout = proc.stdout.toString(); - const stderr = proc.stderr.toString(); - - expect(stdout.trim().split('\n')).toEqual([ - 'Error: Tool execution failed.', - 'Error: Tool execution failed.', - 'Error: Tool execution failed.', - 'DONE', - ]); - expect(stderr).not.toContain('super-secret'); - expect(proc.exitCode).toBe(0); - }); -}); - -describe('read_knowledge QA: read-only port usage', () => { - test('never calls write-like methods present on the injected object and calls each read method at most once', async () => { - const writes: string[] = []; - const base = staticPort([card('c1')], [finding('f1')], [caveat('v1')]); - const port = Object.assign(base.port, { - fileFinding: () => writes.push('fileFinding'), - upsertCard: () => writes.push('upsertCard'), - deleteCaveat: () => writes.push('deleteCaveat'), - }); - - for (const args of [{}, { source: 'library' }, { id: 'f1' }, { query: 'card', limit: 1 }]) { - base.calls.length = 0; - const res = await call(port, args); - expect(res.isError).toBe(false); - expect(new Set(base.calls).size).toBe(base.calls.length); - } - expect(writes).toEqual([]); - }); - - test('does not mutate deeply frozen port records and returns copies of array fields', async () => { - const lib = deepFreeze([card('c1', { tags: ['Alpha', 'beta'], body: 'b'.repeat(5000) })]); - const fin = deepFreeze([finding('f1', { title: 'Alpha finding' })]); - const cav = deepFreeze([caveat('v1', { dataset: 'alpha_ds', caveat: 'c'.repeat(5000) })]); - const snapshot = JSON.stringify([lib, fin, cav]); - const { port } = staticPort(lib, fin, cav); - - const res = await call(port, { query: 'alpha', tags: ['ALPHA'] }); - - expect(res.isError).toBe(false); - expect(res.payload?.rowCount).toBe(3); - expect(JSON.stringify([lib, fin, cav])).toBe(snapshot); - }); - - test('omitted tools/call arguments use defaults and call all three sources with an empty selector', async () => { - const seen: unknown[] = []; - const { port, calls } = makePort({ - library: async q => { - seen.push(q); - return [card('c1')]; - }, - findings: async q => { - seen.push(q); - return [finding('f1')]; - }, - caveats: async q => { - seen.push(q); - return [caveat('v1')]; - }, - }); - - const res = await call(port, undefined); - - expect(res.isError).toBe(false); - expect(calls.sort()).toEqual(['listFindings', 'listLibraryCards', 'listProviderCaveats']); - expect(seen).toEqual([{}, {}, {}]); - expect(res.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 }); - }); -}); - -describe('read_knowledge QA: input boundaries', () => { - test('accepts query at exactly the cap, including when surrounding whitespace is trimmed', async () => { - const atCap = 'q'.repeat(READ_KNOWLEDGE_MAX_QUERY_LENGTH); - const seen: (string | undefined)[] = []; - const { port } = makePort({ - library: async q => { - seen.push(q.query); - return [card('c1', { title: `x${atCap}x` })]; - }, - }); - - for (const query of [atCap, ` ${atCap}\t\n `]) { - const res = await call(port, { source: 'library', query }); - expect(res.isError).toBe(false); - expect(res.payload?.rows.map(r => r.id)).toEqual(['c1']); - } - expect(seen).toEqual([atCap, atCap]); - }); - - test('accepts limit 1 and limit max as boundary values', async () => { - const lib = Array.from({ length: READ_KNOWLEDGE_MAX_LIMIT + 5 }, (_, i) => - card(`c${String(i).padStart(3, '0')}`) - ); - const { port } = staticPort(lib, [], []); - - const one = await call(port, { limit: 1 }); - const max = await call(port, { limit: READ_KNOWLEDGE_MAX_LIMIT }); - - expect(one.payload?.rows.map(r => r.id)).toEqual(['c000']); - expect(max.payload?.rowCount).toBe(READ_KNOWLEDGE_MAX_LIMIT); - expect(max.payload?.rows.at(-1)?.id).toBe('c099'); - }); - - test('rejects null-valued optional selectors and non-array tags before calling the port', async () => { - for (const args of [ - { query: null }, - { id: null }, - { tags: 'alpha' }, - { tags: [1] }, - { provider: ['eodhd'] }, - { source: null }, - { limit: null }, - { limit: Number.POSITIVE_INFINITY }, - ]) { - const { port, calls } = staticPort([card('c1')], [], []); - const res = await call(port, args); - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "read_knowledge"'); - expect(calls).toEqual([]); - } - }); -}); - -describe('read_knowledge QA: matching semantics', () => { - test('free-text query does not match on id, status, createdAt, or trial/evidence refs alone', async () => { - const { port } = staticPort( - [card('zeta-card', { title: 'A', tags: ['b'], summary: 'c', body: 'zeta in body only' })], - [ - finding('zeta-finding', { - title: 'A', - summary: 'c', - status: 'zeta', - createdAt: 'zeta', - trialRefs: ['zeta'], - evidenceRefs: ['zeta'], - }), - ], - [caveat('zeta-caveat', { provider: 'p', dataset: 'd', caveat: 'c', createdAt: 'zeta' })] - ); - - const res = await call(port, { query: 'zeta' }); - - expect(res.payload).toEqual({ - rowCount: 0, - sources: { library: 0, findings: 0, provider_caveats: 0 }, - rows: [], - }); - }); - - test('provider filter is exact (not substring) and tags filter requires whole-tag equality', async () => { - const { port } = staticPort( - [card('c-full', { tags: ['momentum'] }), card('c-partial', { tags: ['momentum-crash'] })], - [], - [caveat('v-eodhd', { provider: 'eodhd' }), caveat('v-eod', { provider: 'eod' })] - ); - - const byProvider = await call(port, { source: 'provider_caveats', provider: 'EOD' }); - const byTag = await call(port, { source: 'library', tags: ['Momentum'] }); - - expect(byProvider.payload?.rows.map(r => r.id)).toEqual(['v-eod']); - expect(byTag.payload?.rows.map(r => r.id)).toEqual(['c-full']); - }); - - test('provider matched in free text ranks below a dataset match for caveats', async () => { - const { port } = staticPort( - [], - [], - [ - caveat('a-provider', { provider: 'quantmedia', dataset: 'bars', caveat: 'x' }), - caveat('z-dataset', { provider: 'eodhd', dataset: 'quantmedia_filings', caveat: 'x' }), - ] - ); - - const res = await call(port, { query: 'QuantMedia' }); - - expect(res.payload?.rows.map(r => r.id)).toEqual(['z-dataset', 'a-provider']); - }); - - test('id lookup still honours source-specific filters: tag mismatch drops the card but keeps other sources under all', async () => { - const { port } = staticPort( - [card('shared', { tags: ['risk'] })], - [finding('shared')], - [caveat('shared', { provider: 'polygon' })] - ); - - const res = await call(port, { id: 'shared', tags: ['momentum'], provider: 'eodhd' }); - - expect(res.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual(['findings:shared']); - expect(res.payload?.sources).toEqual({ library: 0, findings: 1, provider_caveats: 0 }); - }); - - test('regex and wildcard metacharacters in query are matched literally', async () => { - const { port } = staticPort( - [card('c-literal', { title: 'Sharpe (annualised) * sqrt(252)' }), card('c-plain', { title: 'Sharpe annualised' })], - [finding('f-dot', { summary: 'a.b' }), finding('f-any', { summary: 'axb' })], - [caveat('v-pct', { caveat: '100% adjusted' }), caveat('v-none', { caveat: '100 adjusted' })] - ); - - const paren = await call(port, { query: '(annualised) *' }); - const dot = await call(port, { query: 'a.b' }); - const pct = await call(port, { query: '100%' }); - - expect(paren.payload?.rows.map(r => r.id)).toEqual(['c-literal']); - expect(dot.payload?.rows.map(r => r.id)).toEqual(['f-dot']); - expect(pct.payload?.rows.map(r => r.id)).toEqual(['v-pct']); - }); - - test('case-insensitive matching handles non-ASCII text', async () => { - const { port } = staticPort( - [card('c1', { title: 'Étude des rendements' })], - [finding('f1', { summary: 'ÜBERRENDITE nach Ankündigung' })], - [] - ); - - const res = await call(port, { query: 'étude' }); - const res2 = await call(port, { query: 'überrendite' }); - - expect(res.payload?.rows.map(r => r.id)).toEqual(['c1']); - expect(res2.payload?.rows.map(r => r.id)).toEqual(['f1']); - }); - - test('projects exactly the documented fields for findings and caveats, dropping extra port fields', async () => { - const extraFinding = { ...finding('f1'), holdoutPnl: 123, dsn: SECRET } as FindingRecord; - const extraCaveat = { ...caveat('v1'), internalNote: SECRET } as ProviderCaveatRecord; - const { port } = staticPort([], [extraFinding], [extraCaveat]); - - const res = await call(port, {}); - - expect(res.text).not.toContain('super-secret'); - expect(res.text).not.toContain('holdoutPnl'); - expect(res.payload?.rows).toEqual([ - { - source: 'findings', - id: 'f1', - title: 'Finding f1', - status: 'confirmed', - createdAt: '2025-01-15T12:00:00.000Z', - summary: 'Finding summary f1', - trialRefs: ['trial-f1'], - evidenceRefs: ['ev-f1'], - truncated: false, - }, - { - source: 'provider_caveats', - id: 'v1', - provider: 'eodhd', - dataset: 'dataset_v1', - caveat: 'Caveat v1', - createdAt: '2025-01-20T08:30:00.000Z', - truncated: false, - }, - ]); - }); -}); - -describe('read_knowledge QA: deterministic ranking and limit', () => { - test('seeded permutations of a mixed fixture replay to identical rows and counts at every limit', async () => { - const lib = [ - card('m-title', { title: 'Drift study', summary: 's' }), - card('a-tag', { title: 'x', tags: ['drift'] }), - card('Q-sum', { title: 'x', summary: 'post drift' }), - card('shared', { title: 'Drift shared', summary: 's' }), - ]; - const fin = [ - finding('shared', { title: 'Drift finding' }), - finding('b-sum', { title: 'x', summary: 'DRIFT' }), - finding('k-none', { title: 'x', summary: 'nothing' }), - ]; - const cav = [ - caveat('shared', { dataset: 'drift_ds' }), - caveat('c-cav', { dataset: 'bars', caveat: 'drift noted' }), - ]; - - for (const limit of [1, 2, 3, 5, 8, 20]) { - let baseline: ReadKnowledgeResultPayload | null = null; - for (let seed = 1; seed <= 12; seed += 1) { - const { port } = staticPort( - seededShuffle(lib, seed), - seededShuffle(fin, seed * 7), - seededShuffle(cav, seed * 13) - ); - const res = await call(port, { query: 'drift', limit }); - expect(res.isError).toBe(false); - if (baseline === null) { - baseline = res.payload; - } else { - expect(res.payload).toEqual(baseline); - } - } - const expectedOrder = [ - 'library:m-title', - 'library:shared', - 'findings:shared', - 'provider_caveats:shared', - 'library:Q-sum', - 'library:a-tag', - 'findings:b-sum', - 'provider_caveats:c-cav', - ].slice(0, limit); - expect(baseline?.rows.map(r => `${r.source}:${r.id}`)).toEqual(expectedOrder); - const counts = { library: 0, findings: 0, provider_caveats: 0 }; - for (const r of baseline?.rows ?? []) { - counts[r.source] += 1; - } - expect(baseline?.sources).toEqual(counts); - expect(baseline?.rowCount).toBe(expectedOrder.length); - } - }); - - test('truncation flag reflects only text fields over the cap; title, tags and refs are never truncated', async () => { - const longTitle = 'T'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 10); - const { port } = staticPort( - [card('c1', { title: longTitle, tags: ['t'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 1)] })], - [finding('f1', { title: longTitle })], - [] - ); - - const res = await call(port, {}); - - for (const row of res.payload?.rows ?? []) { - expect(row.truncated).toBe(false); - if (row.source !== 'provider_caveats') { - expect(row.title).toHaveLength(longTitle.length); - } - } - }); -}); - -describe('read_knowledge QA: limit cutting through a cross-source tie', () => { - test('limit inside a same-id tie keeps library > findings > provider_caveats and counts only returned rows', async () => { - const { port } = staticPort( - [card('dup', { title: 'Basis risk' })], - [finding('dup', { title: 'Basis risk' })], - [caveat('dup', { dataset: 'basis_ds' })] - ); - - const two = await call(port, { query: 'basis', limit: 2 }); - - expect(two.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'library:dup', - 'findings:dup', - ]); - expect(two.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 0 }); - expect(two.payload?.rowCount).toBe(2); - }); -}); diff --git a/libs/research/test/mcp-read-knowledge.test.ts b/libs/research/test/mcp-read-knowledge.test.ts deleted file mode 100644 index ec32fe0e..00000000 --- a/libs/research/test/mcp-read-knowledge.test.ts +++ /dev/null @@ -1,1110 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import type { MarketDataStore } from '../src/market-data-store'; -import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; -import { - type FindingQuery, - type FindingRecord, - type KnowledgePort, - type LibraryCardQuery, - type LibraryCardRecord, - type ProviderCaveatQuery, - type ProviderCaveatRecord, - READ_KNOWLEDGE_DEFAULT_LIMIT, - READ_KNOWLEDGE_MAX_LIMIT, - READ_KNOWLEDGE_MAX_QUERY_LENGTH, - READ_KNOWLEDGE_MAX_TEXT_LENGTH, - READ_KNOWLEDGE_SOURCES, - type ReadKnowledgeResultPayload, - type SymbolSearchPort, - createAnalyzeSignalTool, - createEventStudyTool, - createMcpServer, - createQueryDataTool, - createReadKnowledgeTool, - createSearchSymbolsTool, - readKnowledgeInputSchema, -} from '../src/mcp/index'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; - -const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); - -function makeLibraryCard( - overrides: Partial & { readonly id: string } -): LibraryCardRecord { - return { - id: overrides.id, - title: overrides.title ?? `Card ${overrides.id}`, - tags: overrides.tags ?? ['methodology'], - summary: overrides.summary ?? `Summary for ${overrides.id}`, - body: overrides.body ?? `Body for ${overrides.id}`, - }; -} - -function makeFinding(overrides: Partial & { readonly id: string }): FindingRecord { - return { - id: overrides.id, - title: overrides.title ?? `Finding ${overrides.id}`, - status: overrides.status ?? 'confirmed', - createdAt: overrides.createdAt ?? '2025-01-15T12:00:00.000Z', - summary: overrides.summary ?? `Finding summary for ${overrides.id}`, - trialRefs: overrides.trialRefs ?? [`trial-${overrides.id}`], - evidenceRefs: overrides.evidenceRefs ?? [`ev-${overrides.id}`], - }; -} - -function makeCaveat( - overrides: Partial & { readonly id: string } -): ProviderCaveatRecord { - return { - id: overrides.id, - provider: overrides.provider ?? 'eodhd', - dataset: overrides.dataset ?? `Dataset ${overrides.id}`, - caveat: overrides.caveat ?? `Caveat text for ${overrides.id}`, - createdAt: overrides.createdAt ?? '2025-01-20T08:30:00.000Z', - }; -} - -interface FakePortState { - readonly libraryCalls: LibraryCardQuery[]; - readonly findingsCalls: FindingQuery[]; - readonly caveatsCalls: ProviderCaveatQuery[]; - readonly invokedMethods: string[]; - readonly port: KnowledgePort; -} - -function createFakeKnowledgePort(options?: { - readonly libraryCards?: readonly LibraryCardRecord[]; - readonly findings?: readonly FindingRecord[]; - readonly providerCaveats?: readonly ProviderCaveatRecord[]; - readonly libraryError?: unknown; - readonly findingsError?: unknown; - readonly caveatsError?: unknown; - readonly applySelectors?: boolean; -}): FakePortState { - const libraryCalls: LibraryCardQuery[] = []; - const findingsCalls: FindingQuery[] = []; - const caveatsCalls: ProviderCaveatQuery[] = []; - const invokedMethods: string[] = []; - - const libraryCards = options?.libraryCards ?? []; - const findings = options?.findings ?? []; - const providerCaveats = options?.providerCaveats ?? []; - const applySelectors = options?.applySelectors === true; - - const rawPort: KnowledgePort = { - async listLibraryCards(q: LibraryCardQuery): Promise { - libraryCalls.push({ ...q }); - if (options?.libraryError !== undefined) { - throw options.libraryError; - } - if (!applySelectors) { - return [...libraryCards]; - } - return libraryCards.filter(card => { - if (q.id !== undefined && card.id !== q.id) { - return false; - } - if (q.tags !== undefined) { - const cardTags = new Set(card.tags.map(t => t.toLowerCase())); - if (!q.tags.every(t => cardTags.has(t.toLowerCase()))) { - return false; - } - } - if (q.query !== undefined) { - const needle = q.query.toLowerCase(); - const inText = - card.title.toLowerCase().includes(needle) || - card.summary.toLowerCase().includes(needle) || - card.tags.some(t => t.toLowerCase().includes(needle)); - if (!inText) { - return false; - } - } - return true; - }); - }, - async listFindings(q: FindingQuery): Promise { - findingsCalls.push({ ...q }); - if (options?.findingsError !== undefined) { - throw options.findingsError; - } - if (!applySelectors) { - return [...findings]; - } - return findings.filter(finding => { - if (q.id !== undefined && finding.id !== q.id) { - return false; - } - if (q.query !== undefined) { - const needle = q.query.toLowerCase(); - const inText = - finding.title.toLowerCase().includes(needle) || - finding.summary.toLowerCase().includes(needle); - if (!inText) { - return false; - } - } - return true; - }); - }, - async listProviderCaveats(q: ProviderCaveatQuery): Promise { - caveatsCalls.push({ ...q }); - if (options?.caveatsError !== undefined) { - throw options.caveatsError; - } - if (!applySelectors) { - return [...providerCaveats]; - } - return providerCaveats.filter(caveat => { - if (q.id !== undefined && caveat.id !== q.id) { - return false; - } - if (q.provider !== undefined && caveat.provider.toLowerCase() !== q.provider.toLowerCase()) { - return false; - } - if (q.query !== undefined) { - const needle = q.query.toLowerCase(); - const inText = - caveat.provider.toLowerCase().includes(needle) || - caveat.dataset.toLowerCase().includes(needle) || - caveat.caveat.toLowerCase().includes(needle); - if (!inText) { - return false; - } - } - return true; - }); - }, - }; - - const port = new Proxy(rawPort, { - get(target, prop, receiver) { - const value: unknown = Reflect.get(target, prop, receiver); - if (typeof value === 'function' && typeof prop === 'string') { - return (...args: unknown[]) => { - invokedMethods.push(prop); - return (value as (...a: unknown[]) => unknown).apply(target, args); - }; - } - return value; - }, - }); - - return { - libraryCalls, - findingsCalls, - caveatsCalls, - invokedMethods, - port, - }; -} - -function createMinimalStore(): MarketDataStore { - return { - bars() { - return { - async *[Symbol.asyncIterator]() { - // empty stream - }, - }; - }, - async universe() { - return []; - }, - 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'); - }, - }; -} - -function createMinimalLedger(): TrialLedgerExecutor { - return { - async query() { - return { rows: [] }; - }, - }; -} - -function createMinimalSymbolPort(): SymbolSearchPort { - return { - async searchSymbols() { - return []; - }, - }; -} - -async function callReadKnowledge( - fake: FakePortState, - args: Record -): Promise<{ - readonly isError: boolean; - readonly text: string; - readonly payload: ReadKnowledgeResultPayload | null; -}> { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [createReadKnowledgeTool({ port: fake.port })], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'rk-1', - method: 'tools/call', - params: { - name: 'read_knowledge', - arguments: args, - }, - }) - ); - - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw as string) as { - result: { - isError?: boolean; - content: { type: string; text: string }[]; - }; - }; - const isError = parsed.result.isError === true; - const text = parsed.result.content[0]?.text ?? ''; - - return { - isError, - text, - payload: isError ? null : (JSON.parse(text) as ReadKnowledgeResultPayload), - }; -} - -describe('MCP read_knowledge tool', () => { - test('registers alongside existing MCP tools, exposes strict schema via tools/list, and executes via tools/call', async () => { - const store = createMinimalStore(); - const ledger = createMinimalLedger(); - const fake = createFakeKnowledgePort({ - libraryCards: [ - makeLibraryCard({ - id: 'card-cpcv', - title: 'Combinatorial Purged Cross-Validation', - tags: ['validation', 'overfitting'], - summary: 'Purge and embargo overlapping labels across folds.', - body: 'Detailed CPCV methodology card body.', - }), - ], - findings: [ - makeFinding({ - id: 'find-01', - title: 'Earnings drift decay post-2023', - status: 'confirmed', - createdAt: '2025-02-01T10:00:00.000Z', - summary: 'Post-earnings drift attenuates within 3 sessions.', - trialRefs: ['trial-101'], - evidenceRefs: ['ev-202'], - }), - ], - providerCaveats: [ - makeCaveat({ - id: 'cav-01', - provider: 'eodhd', - dataset: 'eodPrices', - caveat: 'Backward split adjustments must be un-adjusted before research.', - createdAt: '2025-02-05T09:00:00.000Z', - }), - ], - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - createAnalyzeSignalTool({ - store, - ledger, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - principalId: 'operator', - }), - createEventStudyTool({ - store, - ledger, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - principalId: 'operator', - resolveExchangeCalendars: () => ({}), - }), - createSearchSymbolsTool({ - port: createMinimalSymbolPort(), - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - createReadKnowledgeTool({ port: fake.port }), - ], - }); - - const listRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/list', - }) - ); - expect(listRaw).not.toBeNull(); - - const listParsed = JSON.parse(listRaw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - type: string; - properties: Record>; - required?: string[]; - additionalProperties: boolean; - }; - }[]; - }; - }; - - expect(listParsed.result.tools.map(t => t.name)).toEqual([ - 'query_data', - 'analyze_signal', - 'event_study', - 'search_symbols', - 'read_knowledge', - ]); - - const tool = listParsed.result.tools.find(t => t.name === 'read_knowledge'); - expect(tool).toBeDefined(); - expect(tool?.inputSchema.type).toBe('object'); - expect(tool?.inputSchema.additionalProperties).toBe(false); - expect(tool?.inputSchema.required).toBeUndefined(); - expect(tool?.inputSchema.properties.source).toMatchObject({ - type: 'string', - enum: [...READ_KNOWLEDGE_SOURCES], - default: 'all', - }); - expect(tool?.inputSchema.properties.query).toMatchObject({ - type: 'string', - minLength: 1, - maxLength: READ_KNOWLEDGE_MAX_QUERY_LENGTH, - }); - expect(tool?.inputSchema.properties.id).toMatchObject({ - type: 'string', - minLength: 1, - }); - expect(tool?.inputSchema.properties.tags).toMatchObject({ - type: 'array', - minItems: 1, - items: { type: 'string', minLength: 1 }, - }); - expect(tool?.inputSchema.properties.provider).toMatchObject({ - type: 'string', - minLength: 1, - }); - expect(tool?.inputSchema.properties.limit).toMatchObject({ - type: 'integer', - minimum: 1, - maximum: READ_KNOWLEDGE_MAX_LIMIT, - default: READ_KNOWLEDGE_DEFAULT_LIMIT, - }); - expect(tool?.inputSchema.properties.scope).toBeUndefined(); - expect(tool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); - expect(tool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); - - // Execute tools/call end-to-end on the multi-tool server. - const callRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 2, - method: 'tools/call', - params: { - name: 'read_knowledge', - arguments: { id: 'card-cpcv' }, - }, - }) - ); - expect(callRaw).not.toBeNull(); - const callParsed = JSON.parse(callRaw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(callParsed.result.isError).toBeUndefined(); - const payload = JSON.parse(callParsed.result.content[0]?.text ?? '') as ReadKnowledgeResultPayload; - expect(payload).toEqual({ - rowCount: 1, - sources: { - library: 1, - findings: 0, - provider_caveats: 0, - }, - rows: [ - { - source: 'library', - id: 'card-cpcv', - title: 'Combinatorial Purged Cross-Validation', - tags: ['validation', 'overfitting'], - summary: 'Purge and embargo overlapping labels across folds.', - body: 'Detailed CPCV methodology card body.', - truncated: false, - }, - ], - }); - expect(new Set(fake.invokedMethods)).toEqual( - new Set(['listLibraryCards', 'listFindings', 'listProviderCaveats']) - ); - }); - - test('invokes only the selected source port methods with applicable parsed selectors', async () => { - const libraryCard = makeLibraryCard({ id: 'lib-1', tags: ['alpha'] }); - const finding = makeFinding({ id: 'fin-1' }); - const caveat = makeCaveat({ id: 'cav-1', provider: 'eodhd' }); - - // source: 'library' - const libFake = createFakeKnowledgePort({ - libraryCards: [libraryCard], - findings: [finding], - providerCaveats: [caveat], - }); - const libRes = await callReadKnowledge(libFake, { - source: 'library', - query: ' lib-1 ', - tags: [' alpha '], - provider: 'eodhd', - }); - expect(libRes.isError).toBe(false); - expect(libFake.invokedMethods).toEqual(['listLibraryCards']); - expect(libFake.libraryCalls).toEqual([{ query: 'lib-1', tags: ['alpha'] }]); - expect(libFake.findingsCalls).toHaveLength(0); - expect(libFake.caveatsCalls).toHaveLength(0); - expect(libRes.payload?.sources).toEqual({ library: 1, findings: 0, provider_caveats: 0 }); - - // source: 'findings' - const finFake = createFakeKnowledgePort({ - libraryCards: [libraryCard], - findings: [finding], - providerCaveats: [caveat], - }); - const finRes = await callReadKnowledge(finFake, { - source: 'findings', - query: ' fin-1 ', - tags: ['alpha'], - provider: 'eodhd', - }); - expect(finRes.isError).toBe(false); - expect(finFake.invokedMethods).toEqual(['listFindings']); - expect(finFake.findingsCalls).toEqual([{ query: 'fin-1' }]); - expect(finFake.libraryCalls).toHaveLength(0); - expect(finFake.caveatsCalls).toHaveLength(0); - expect(finRes.payload?.sources).toEqual({ library: 0, findings: 1, provider_caveats: 0 }); - - // source: 'provider_caveats' - const cavFake = createFakeKnowledgePort({ - libraryCards: [libraryCard], - findings: [finding], - providerCaveats: [caveat], - }); - const cavRes = await callReadKnowledge(cavFake, { - source: 'provider_caveats', - query: ' cav-1 ', - tags: ['alpha'], - provider: ' EODHD ', - }); - expect(cavRes.isError).toBe(false); - expect(cavFake.invokedMethods).toEqual(['listProviderCaveats']); - expect(cavFake.caveatsCalls).toEqual([{ query: 'cav-1', provider: 'EODHD' }]); - expect(cavFake.libraryCalls).toHaveLength(0); - expect(cavFake.findingsCalls).toHaveLength(0); - expect(cavRes.payload?.sources).toEqual({ library: 0, findings: 0, provider_caveats: 1 }); - - // source: 'all' (explicit) and omitted source - for (const args of [ - { source: 'all', id: ' shared-id ', tags: [' beta '], provider: ' polygon ' }, - { id: ' shared-id ', tags: [' beta '], provider: ' polygon ' }, - ]) { - const allFake = createFakeKnowledgePort(); - const allRes = await callReadKnowledge(allFake, args); - expect(allRes.isError).toBe(false); - expect(allFake.libraryCalls).toEqual([{ id: 'shared-id', tags: ['beta'] }]); - expect(allFake.findingsCalls).toEqual([{ id: 'shared-id' }]); - expect(allFake.caveatsCalls).toEqual([{ id: 'shared-id', provider: 'polygon' }]); - expect(allFake.invokedMethods).toEqual([ - 'listLibraryCards', - 'listFindings', - 'listProviderCaveats', - ]); - } - }); - - test('supports exact case-sensitive id precedence over query, missing id, and explicit field projection', async () => { - const extraCard = { - ...makeLibraryCard({ - id: 'Exact-Id', - title: 'Unrelated Title', - summary: 'Unrelated summary', - }), - internalSecret: 'must-not-leak', - } as unknown as LibraryCardRecord; - - const fake = createFakeKnowledgePort({ - libraryCards: [extraCard, makeLibraryCard({ id: 'exact-id', title: 'Lowercase ID' })], - findings: [makeFinding({ id: 'Exact-Id', title: 'Matching Finding ID' })], - providerCaveats: [makeCaveat({ id: 'Exact-Id', dataset: 'Matching Caveat ID' })], - }); - - // id takes precedence over non-matching query and is case-sensitive - const exactRes = await callReadKnowledge(fake, { - id: ' Exact-Id ', - query: 'nonexistent-query-text', - }); - expect(exactRes.isError).toBe(false); - expect(exactRes.payload?.rowCount).toBe(3); - expect(exactRes.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 }); - expect(exactRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'library:Exact-Id', - 'findings:Exact-Id', - 'provider_caveats:Exact-Id', - ]); - expect('internalSecret' in (exactRes.payload?.rows[0] ?? {})).toBe(false); - - // Missing id returns empty result with zero counts - const missingRes = await callReadKnowledge(fake, { id: 'does-not-exist' }); - expect(missingRes.isError).toBe(false); - expect(missingRes.payload).toEqual({ - rowCount: 0, - sources: { library: 0, findings: 0, provider_caveats: 0 }, - rows: [], - }); - }); - - test('omits query from port selectors when id is supplied so selector-filtering ports return exact matches', async () => { - const filteringFake = createFakeKnowledgePort({ - applySelectors: true, - libraryCards: [ - makeLibraryCard({ - id: 'card-cpcv', - title: 'Combinatorial Purged Cross-Validation', - tags: ['validation'], - summary: 'Purge and embargo overlapping labels across folds.', - }), - ], - findings: [ - makeFinding({ - id: 'card-cpcv', - title: 'CPCV split stability', - summary: 'No mention of unrelated factors.', - }), - ], - providerCaveats: [ - makeCaveat({ - id: 'card-cpcv', - provider: 'eodhd', - dataset: 'eodPrices', - caveat: 'Backward split adjustments only.', - }), - ], - }); - - const res = await callReadKnowledge(filteringFake, { - id: 'card-cpcv', - query: 'momentum', - tags: ['validation'], - provider: 'eodhd', - }); - - expect(res.isError).toBe(false); - expect(filteringFake.libraryCalls).toEqual([{ id: 'card-cpcv', tags: ['validation'] }]); - expect(filteringFake.findingsCalls).toEqual([{ id: 'card-cpcv' }]); - expect(filteringFake.caveatsCalls).toEqual([{ id: 'card-cpcv', provider: 'eodhd' }]); - expect(res.payload?.rowCount).toBe(3); - expect(res.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 }); - expect(res.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'library:card-cpcv', - 'findings:card-cpcv', - 'provider_caveats:card-cpcv', - ]); - }); - - test('does not grant exact-ID priority to free-text query matches and stays invariant to query capitalization', async () => { - const fake = createFakeKnowledgePort({ - libraryCards: [ - makeLibraryCard({ - id: 'momentum', - title: 'Factor Crowding Notes', - tags: ['risk'], - summary: 'Discusses momentum drawdown regimes.', - }), - makeLibraryCard({ - id: 'z-card', - title: 'Momentum Basics', - tags: ['factor'], - summary: 'Introductory overview.', - }), - ], - findings: [ - makeFinding({ - id: 'momentum', - title: 'Regime Decay', - summary: 'Observed momentum turnover costs.', - }), - makeFinding({ - id: 'z-finding', - title: 'Momentum Persistence', - summary: 'Observed over 2015–2024.', - }), - ], - providerCaveats: [ - makeCaveat({ - id: 'momentum', - provider: 'eodhd', - dataset: 'eodPrices', - caveat: 'Affects momentum backtests.', - }), - makeCaveat({ - id: 'z-caveat', - provider: 'eodhd', - dataset: 'momentum_signals', - caveat: 'Adjusted series.', - }), - ], - }); - - for (const source of ['library', 'findings', 'provider_caveats'] as const) { - const lowerTop = await callReadKnowledge(fake, { source, query: 'momentum', limit: 1 }); - const upperTop = await callReadKnowledge(fake, { source, query: 'MOMENTUM', limit: 1 }); - - expect(lowerTop.isError).toBe(false); - expect(upperTop.isError).toBe(false); - expect(lowerTop.payload).toEqual(upperTop.payload); - - const expectedId = - source === 'library' ? 'z-card' : source === 'findings' ? 'z-finding' : 'z-caveat'; - expect(lowerTop.payload?.rows.map(r => r.id)).toEqual([expectedId]); - } - }); - - test('filters case-insensitively across titles, tags, summaries, caveats, and source-specific filters', async () => { - const fake = createFakeKnowledgePort({ - libraryCards: [ - makeLibraryCard({ - id: 'lib-tag', - title: 'Factor Neutrality', - tags: ['Momentum', 'Neutrality'], - summary: 'Dollar neutral weighting.', - }), - makeLibraryCard({ - id: 'lib-summary', - title: 'Execution Slippage', - tags: ['Microstructure'], - summary: 'Models MOMENTUM crowding impact.', - }), - makeLibraryCard({ - id: 'lib-only-one-tag', - title: 'Momentum Basics', - tags: ['Momentum'], - summary: 'Single tag card.', - }), - ], - findings: [ - makeFinding({ - id: 'fin-match', - title: 'Cross-sectional Momentum', - summary: 'Observed decay in 2024.', - }), - makeFinding({ - id: 'fin-other', - title: 'Value Spread', - summary: 'Unrelated finding.', - }), - ], - providerCaveats: [ - makeCaveat({ - id: 'cav-eodhd', - provider: 'EODHD', - dataset: 'eodPrices', - caveat: 'Momentum backtests need un-adjusted closes.', - }), - makeCaveat({ - id: 'cav-polygon', - provider: 'Polygon', - dataset: 'intraday1m', - caveat: 'Momentum bars omit odd lots.', - }), - ], - }); - - // With source: 'all', tags filters only library (all-tag match) and provider filters only caveats - const combinedRes = await callReadKnowledge(fake, { - query: ' momentum ', - tags: [' MOMENTUM ', 'neutrality'], - provider: ' eodhd ', - }); - expect(combinedRes.isError).toBe(false); - expect(combinedRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'findings:fin-match', - 'provider_caveats:cav-eodhd', - 'library:lib-tag', - ]); - expect(combinedRes.payload?.sources).toEqual({ - library: 1, - findings: 1, - provider_caveats: 1, - }); - - // Empty result when query matches nothing - const emptyRes = await callReadKnowledge(fake, { query: 'zzz-no-match' }); - expect(emptyRes.isError).toBe(false); - expect(emptyRes.payload).toEqual({ - rowCount: 0, - sources: { library: 0, findings: 0, provider_caveats: 0 }, - rows: [], - }); - }); - - test('ranks deterministically across shuffled fixtures: exact id > title/dataset > other > ascending id > source order', async () => { - const libraryCards: LibraryCardRecord[] = [ - makeLibraryCard({ - id: 'tie-id', - title: 'Alpha title match', - tags: ['misc'], - summary: 'summary', - }), - makeLibraryCard({ - id: 'a-other', - title: 'Unrelated', - tags: ['alpha'], - summary: 'summary', - }), - makeLibraryCard({ - id: 'B-other', - title: 'Unrelated', - tags: ['misc'], - summary: 'Contains alpha in summary', - }), - ]; - const findings: FindingRecord[] = [ - makeFinding({ - id: 'tie-id', - title: 'Alpha finding title', - summary: 'summary', - }), - makeFinding({ - id: 'z-summary', - title: 'Unrelated finding', - summary: 'Mentions alpha here', - }), - ]; - const providerCaveats: ProviderCaveatRecord[] = [ - makeCaveat({ - id: 'tie-id', - provider: 'eodhd', - dataset: 'alpha_dataset', - caveat: 'caveat text', - }), - makeCaveat({ - id: 'c-provider', - provider: 'alpha-feed', - dataset: 'bars', - caveat: 'ordinary text', - }), - makeCaveat({ - id: 'd-caveat', - provider: 'other', - dataset: 'bars', - caveat: 'mentions alpha inside caveat', - }), - ]; - - const resA = await callReadKnowledge( - createFakeKnowledgePort({ libraryCards, findings, providerCaveats }), - { query: 'alpha' } - ); - const resB = await callReadKnowledge( - createFakeKnowledgePort({ - libraryCards: [...libraryCards].reverse(), - findings: [...findings].reverse(), - providerCaveats: [...providerCaveats].reverse(), - }), - { query: 'alpha' } - ); - - expect(resA.isError).toBe(false); - expect(resB.isError).toBe(false); - expect(resA.payload).toEqual(resB.payload); - - // Title/dataset matches first (all have id 'tie-id', broken by library -> findings -> provider_caveats), - // then other text matches ordered by ASCII/code-unit id ('B-other' < 'a-other' < 'c-provider' < 'd-caveat' < 'z-summary'). - expect(resA.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'library:tie-id', - 'findings:tie-id', - 'provider_caveats:tie-id', - 'library:B-other', - 'library:a-other', - 'provider_caveats:c-provider', - 'provider_caveats:d-caveat', - 'findings:z-summary', - ]); - }); - - test('enforces default limit 20, hard max 100, late best match, and post-limit source counts', async () => { - // 25 eligible records (22 library + 3 findings) with default limit 20: - // Findings have title matches so they rank ahead of library summary matches, pushing 5 library rows out. - const lib22: LibraryCardRecord[] = []; - for (let i = 1; i <= 22; i += 1) { - lib22.push( - makeLibraryCard({ - id: `lib-${String(i).padStart(2, '0')}`, - title: 'Generic Card', - summary: 'Contains needle in summary', - }) - ); - } - const fin3: FindingRecord[] = [ - makeFinding({ id: 'fin-01', title: 'Needle Title 1', summary: 's' }), - makeFinding({ id: 'fin-02', title: 'Needle Title 2', summary: 's' }), - makeFinding({ id: 'fin-03', title: 'Needle Title 3', summary: 's' }), - ]; - - const defaultRes = await callReadKnowledge( - createFakeKnowledgePort({ libraryCards: lib22, findings: fin3 }), - { query: 'needle' } - ); - expect(defaultRes.isError).toBe(false); - expect(defaultRes.payload?.rowCount).toBe(20); - expect(defaultRes.payload?.rows).toHaveLength(20); - expect(defaultRes.payload?.sources).toEqual({ - library: 17, - findings: 3, - provider_caveats: 0, - }); - - // Hard max 100 with 115 eligible records and the best match placed last in the fixture - const lib115: LibraryCardRecord[] = []; - for (let i = 1; i <= 114; i += 1) { - lib115.push( - makeLibraryCard({ - id: `rec-${String(i).padStart(3, '0')}`, - title: 'Other', - summary: 'Contains signal in summary', - }) - ); - } - lib115.push( - makeLibraryCard({ - id: 'zzz-best-late', - title: 'Signal Title Match Placed Last', - summary: 'summary', - }) - ); - - const maxRes = await callReadKnowledge(createFakeKnowledgePort({ libraryCards: lib115 }), { - source: 'library', - query: 'signal', - limit: READ_KNOWLEDGE_MAX_LIMIT, - }); - expect(maxRes.isError).toBe(false); - expect(maxRes.payload?.rowCount).toBe(100); - expect(maxRes.payload?.rows).toHaveLength(100); - expect(maxRes.payload?.rows[0]?.id).toBe('zzz-best-late'); - expect(maxRes.payload?.sources).toEqual({ - library: 100, - findings: 0, - provider_caveats: 0, - }); - }); - - test('truncates body, summary, and caveat independently at 4096 chars after matching', async () => { - const exactCap = 'x'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - const overCapWithTailNeedle = `${'y'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH)}NEEDLE`; - const overCapOne = 'z'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 1); - - const fake = createFakeKnowledgePort({ - libraryCards: [ - makeLibraryCard({ - id: 'lib-exact', - title: 'Exact Cap Card', - summary: exactCap, - body: exactCap, - }), - makeLibraryCard({ - id: 'lib-over-body', - title: 'Over Cap Body', - summary: 'short summary', - body: overCapOne, - }), - makeLibraryCard({ - id: 'lib-over-summary-needle', - title: 'Late Match Summary', - summary: overCapWithTailNeedle, - body: 'short body', - }), - ], - findings: [ - makeFinding({ - id: 'fin-exact', - title: 'Exact Finding', - summary: exactCap, - }), - makeFinding({ - id: 'fin-over-needle', - title: 'Late Match Finding', - summary: overCapWithTailNeedle, - }), - ], - providerCaveats: [ - makeCaveat({ - id: 'cav-exact', - dataset: 'exact_ds', - caveat: exactCap, - }), - makeCaveat({ - id: 'cav-over-needle', - dataset: 'over_ds', - caveat: overCapWithTailNeedle, - }), - ], - }); - - // Exact cap rows are not truncated - for (const id of ['lib-exact', 'fin-exact', 'cav-exact']) { - const res = await callReadKnowledge(fake, { id }); - expect(res.isError).toBe(false); - expect(res.payload?.rows).toHaveLength(1); - const row = res.payload?.rows[0]; - expect(row?.truncated).toBe(false); - if (row?.source === 'library') { - expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - expect(row.body).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } else if (row?.source === 'findings') { - expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } else if (row?.source === 'provider_caveats') { - expect(row.caveat).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } - } - - // Library body 1 char over cap is truncated independently while short summary is untouched - const overBodyRes = await callReadKnowledge(fake, { id: 'lib-over-body' }); - expect(overBodyRes.isError).toBe(false); - const bodyRow = overBodyRes.payload?.rows[0]; - expect(bodyRow?.source).toBe('library'); - if (bodyRow?.source === 'library') { - expect(bodyRow.truncated).toBe(true); - expect(bodyRow.summary).toBe('short summary'); - expect(bodyRow.body).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } - - // Query matching text beyond char 4096 still matches, then caps output to 4096 with truncated: true - const needleRes = await callReadKnowledge(fake, { query: 'needle' }); - expect(needleRes.isError).toBe(false); - expect(needleRes.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([ - 'provider_caveats:cav-over-needle', - 'findings:fin-over-needle', - 'library:lib-over-summary-needle', - ]); - for (const row of needleRes.payload?.rows ?? []) { - expect(row.truncated).toBe(true); - if (row.source === 'library') { - expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - expect(row.body).toBe('short body'); - } else if (row.source === 'findings') { - expect(row.summary).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } else { - expect(row.caveat).toHaveLength(READ_KNOWLEDGE_MAX_TEXT_LENGTH); - } - } - }); - - test('rejects strict input violations before invoking any port method', async () => { - const invalidInputs: Record[] = [ - { scope: 'vault_evaluation_only' }, - { vault_evaluation_only: true }, - { vaultCutoffTs: VAULT_CUTOFF_TS }, - { unexpectedKey: 'nope' }, - { query: 'A'.repeat(READ_KNOWLEDGE_MAX_QUERY_LENGTH + 1) }, - { query: '' }, - { query: ' \t\n ' }, - { id: '' }, - { id: ' ' }, - { provider: '' }, - { provider: ' ' }, - { tags: [] }, - { tags: ['valid', ' '] }, - { source: 'vault' }, - { source: 'LIBRARY' }, - { limit: 0 }, - { limit: -5 }, - { limit: READ_KNOWLEDGE_MAX_LIMIT + 1 }, - { limit: 1.5 }, - { limit: '10' }, - ]; - - for (const args of invalidInputs) { - expect(readKnowledgeInputSchema.safeParse(args).success).toBe(false); - const fake = createFakeKnowledgePort({ - libraryCards: [makeLibraryCard({ id: 'c1' })], - }); - const res = await callReadKnowledge(fake, args); - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "read_knowledge"'); - expect(fake.invokedMethods).toHaveLength(0); - } - }); - - test('returns sanitized isError without leaking connection strings or stack traces when port rejects', async () => { - const secretError = new Error( - 'postgres://admin:super-secret@10.0.0.51:5432/trading_bot connection refused' - ); - secretError.stack = - 'Error: postgres://admin:super-secret@10.0.0.51:5432/trading_bot\n at internalQuery (/srv/secret/db.ts:42:9)'; - - // Single source failure - const singleFake = createFakeKnowledgePort({ libraryError: secretError }); - const singleRes = await callReadKnowledge(singleFake, { source: 'library', query: 'alpha' }); - expect(singleRes.isError).toBe(true); - expect(singleRes.text).toBe('Error: Tool execution failed.'); - expect(singleRes.text).not.toContain('super-secret'); - expect(singleRes.text).not.toContain('10.0.0.51'); - expect(singleRes.text).not.toContain('trading_bot'); - expect(singleRes.text).not.toContain('/srv/secret/db.ts'); - - // Partial failure under source: 'all' when other selected sources succeed - const partialFake = createFakeKnowledgePort({ - libraryCards: [makeLibraryCard({ id: 'ok-1', title: 'Alpha' })], - findingsError: secretError, - providerCaveats: [makeCaveat({ id: 'ok-2', dataset: 'Alpha' })], - }); - const partialRes = await callReadKnowledge(partialFake, { source: 'all', query: 'alpha' }); - expect(partialRes.isError).toBe(true); - expect(partialRes.text).toBe('Error: Tool execution failed.'); - expect(partialRes.text).not.toContain('super-secret'); - expect(partialRes.text).not.toContain('10.0.0.51'); - expect(partialRes.text).not.toContain('db.ts'); - }); - - test('factory throws on missing or invalid port options', () => { - expect(() => - createReadKnowledgeTool(null as unknown as Parameters[0]) - ).toThrow(); - - expect(() => - createReadKnowledgeTool({ port: null as unknown as KnowledgePort }) - ).toThrow(); - - expect(() => - createReadKnowledgeTool({ port: {} as unknown as KnowledgePort }) - ).toThrow(); - }); -}); diff --git a/libs/research/test/mcp-search-symbols-qa.test.ts b/libs/research/test/mcp-search-symbols-qa.test.ts deleted file mode 100644 index 44d15be2..00000000 --- a/libs/research/test/mcp-search-symbols-qa.test.ts +++ /dev/null @@ -1,354 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - createMcpServer, - createSearchSymbolsTool, - SEARCH_SYMBOLS_MAX_QUERY_LENGTH, - type SearchSymbolsResultPayload, - type SymbolSearchPort, - type SymbolSearchQuery, - type SymbolSearchRow, -} from '../src/mcp/index'; - -// QA fixture: deterministic in-memory security-master port (no network, no -// Postgres, no MongoDB). Cutoffs are pinned epoch-ms values; no wall clock. -const MIDDAY_CUTOFF_TS = Date.UTC(2025, 2, 31, 15, 30, 0, 0); // 2025-03-31T15:30Z -const LAST_MS_CUTOFF_TS = Date.UTC(2025, 2, 31, 23, 59, 59, 999); // 2025-03-31T23:59:59.999Z -const CUTOFF_DATE = '2025-03-31'; - -function row( - overrides: Partial & { readonly listingId: number } -): SymbolSearchRow { - return { - instrumentId: overrides.listingId * 10, - ticker: `T${overrides.listingId}`, - classSuffix: null, - name: `Company ${overrides.listingId}`, - mic: 'XNAS', - currency: 'USD', - isin: null, - firstBarDate: '2020-01-02', - lastBarDate: '2025-03-28', - delistedAt: null, - ...overrides, - }; -} - -function fakePort(impl: (q: SymbolSearchQuery) => Promise | unknown): { - readonly calls: SymbolSearchQuery[]; - readonly port: SymbolSearchPort; -} { - const calls: SymbolSearchQuery[] = []; - return { - calls, - port: { - async searchSymbols(q) { - calls.push({ ...q }); - return (await impl(q)) as readonly SymbolSearchRow[]; - }, - }, - }; -} - -async function call( - port: SymbolSearchPort, - args: Record, - vaultCutoffTs: number -): Promise<{ isError: boolean; text: string; payload: SearchSymbolsResultPayload | null }> { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [createSearchSymbolsTool({ port, vaultContext: { vaultCutoffTs } })], - }); - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 7, - method: 'tools/call', - params: { name: 'search_symbols', arguments: args }, - }) - ); - const parsed = JSON.parse(raw as string) as { - result: { isError?: boolean; content: { text: string }[] }; - }; - const isError = parsed.result.isError === true; - const text = parsed.result.content[0]?.text ?? ''; - return { - isError, - text, - payload: isError ? null : (JSON.parse(text) as SearchSymbolsResultPayload), - }; -} - -describe('MCP search_symbols QA', () => { - test('intraday cutoff fences against the cutoff UTC calendar date (equal kept, next day dropped/clamped/masked)', async () => { - const rows = [ - row({ - listingId: 1, - ticker: 'QQ', - firstBarDate: CUTOFF_DATE, - lastBarDate: '2025-04-01', - delistedAt: '2025-04-01', - }), - row({ listingId: 2, ticker: 'QQ', firstBarDate: '2025-04-01', lastBarDate: '2025-04-02' }), - row({ listingId: 3, ticker: 'QQ', lastBarDate: CUTOFF_DATE, delistedAt: CUTOFF_DATE }), - ]; - for (const cutoff of [MIDDAY_CUTOFF_TS, LAST_MS_CUTOFF_TS]) { - const { port } = fakePort(() => rows); - const res = await call(port, { query: 'QQ' }, cutoff); - expect(res.isError).toBe(false); - expect(res.payload?.vaultCutoffTs).toBe(cutoff); - expect( - res.payload?.rows.map(r => [r.listingId, r.firstBarDate, r.lastBarDate, r.delistedAt]) - ).toEqual([ - [1, CUTOFF_DATE, CUTOFF_DATE, null], - [3, '2020-01-02', CUTOFF_DATE, CUTOFF_DATE], - ]); - } - }); - - test('cutoff one ms before midnight UTC uses the previous calendar date', async () => { - const cutoff = Date.UTC(2025, 2, 31, 0, 0, 0, 0) - 1; // 2025-03-30T23:59:59.999Z - const { port } = fakePort(() => [ - row({ listingId: 1, ticker: 'EDGE', firstBarDate: CUTOFF_DATE }), - row({ listingId: 2, ticker: 'EDGE', lastBarDate: CUTOFF_DATE, delistedAt: CUTOFF_DATE }), - ]); - const res = await call(port, { query: 'EDGE' }, cutoff); - expect(res.payload?.rows).toHaveLength(1); - expect(res.payload?.rows[0]).toMatchObject({ - listingId: 2, - lastBarDate: '2025-03-30', - delistedAt: null, - }); - }); - - test('a future delisting changes neither membership nor ranking relative to a never-delisted listing', async () => { - const base = [ - row({ listingId: 9, ticker: 'MSFT', name: 'Microsoft Corp' }), - row({ listingId: 4, ticker: 'MSFTX', name: 'Microsoft Tracker' }), - row({ listingId: 7, ticker: 'ZZZ', name: 'Old msft Holdings' }), - ]; - const withFutureDelisting = base.map(r => - r.listingId === 4 ? { ...r, delistedAt: '2026-01-15', lastBarDate: '2026-01-14' } : r - ); - for (const includeDelisted of [true, false]) { - const a = await call( - fakePort(() => base).port, - { query: 'msft', includeDelisted }, - MIDDAY_CUTOFF_TS - ); - const b = await call( - fakePort(() => withFutureDelisting).port, - { query: 'msft', includeDelisted }, - MIDDAY_CUTOFF_TS - ); - expect(a.payload?.rows.map(r => r.listingId)).toEqual([9, 4, 7]); - expect(b.payload?.rows.map(r => r.listingId)).toEqual([9, 4, 7]); - expect(b.payload?.rows[1]).toMatchObject({ delistedAt: null, lastBarDate: CUTOFF_DATE }); - } - }); - - test('truncation with includeDelisted: true ignores post-cutoff rows placed ahead of eligible matches', async () => { - const rows = [ - row({ listingId: 1, ticker: 'NEW', firstBarDate: '2025-06-01' }), - row({ listingId: 2, ticker: 'NEW', firstBarDate: '2025-04-01' }), - row({ listingId: 3, ticker: 'NEWA' }), - row({ listingId: 4, ticker: 'NEWB', delistedAt: '2021-05-05', lastBarDate: '2021-05-04' }), - ]; - const fit = await call(fakePort(() => rows).port, { query: 'new', limit: 2 }, MIDDAY_CUTOFF_TS); - expect(fit.payload).toMatchObject({ rowCount: 2, truncated: false }); - expect(fit.payload?.rows.map(r => r.listingId)).toEqual([3, 4]); - - const over = await call( - fakePort(() => rows).port, - { query: 'new', limit: 1 }, - MIDDAY_CUTOFF_TS - ); - expect(over.payload).toMatchObject({ rowCount: 1, truncated: true }); - expect(over.payload?.rows.map(r => r.listingId)).toEqual([3]); - }); - - test('a row matching both ticker prefix and name ranks by its best (ticker) match; name match is literal substring', async () => { - const rows = [ - row({ listingId: 1, ticker: 'ZED', name: 'A.B Industries' }), - row({ listingId: 2, ticker: 'A.BX', name: 'A.B Prefix Co' }), - row({ listingId: 3, ticker: 'AXB', name: 'Regex Bait AXB' }), - row({ listingId: 4, ticker: 'A.B', name: 'Exact Dot' }), - ]; - const res = await call(fakePort(() => rows).port, { query: 'a.b' }, MIDDAY_CUTOFF_TS); - // "a.b" must not behave like a regex: AXB (3) is not a match. - expect(res.payload?.rows.map(r => r.listingId)).toEqual([4, 2, 1]); - }); - - test('repeated calls on shuffled inputs give byte-identical payloads', async () => { - const rows = Array.from({ length: 30 }, (_, i) => - row({ listingId: 1000 - i * 7, ticker: i % 3 === 0 ? 'RY' : `RY${i}`, name: `Royal ${i}` }) - ); - // Deterministic Fisher-Yates with a fixed LCG seed. - let seed = 12345; - const shuffled = [...rows]; - for (let i = shuffled.length - 1; i > 0; i -= 1) { - seed = (seed * 1103515245 + 12345) % 2147483648; - const j = seed % (i + 1); - [shuffled[i], shuffled[j]] = [shuffled[j] as SymbolSearchRow, shuffled[i] as SymbolSearchRow]; - } - const a = await call(fakePort(() => rows).port, { query: 'RY', limit: 12 }, MIDDAY_CUTOFF_TS); - const b = await call( - fakePort(() => shuffled).port, - { query: 'RY', limit: 12 }, - MIDDAY_CUTOFF_TS - ); - expect(a.text).toBe(b.text); - const ids = a.payload?.rows.map(r => r.listingId) ?? []; - const exact = ids.slice(0, 10); - expect([...exact].sort((x, y) => x - y)).toEqual(exact); // 10 exact RY matches ascending - expect(a.payload?.truncated).toBe(true); - }); - - test('query of exactly 64 chars (and 64 chars after trimming) is accepted; whitespace is trimmed before the length check', async () => { - const q = 'B'.repeat(SEARCH_SYMBOLS_MAX_QUERY_LENGTH); - const fake = fakePort(() => []); - const exact = await call(fake.port, { query: q }, MIDDAY_CUTOFF_TS); - const padded = await call(fake.port, { query: ` ${q} ` }, MIDDAY_CUTOFF_TS); - expect(exact.isError).toBe(false); - expect(padded.isError).toBe(false); - expect(fake.calls.map(c => c.query)).toEqual([q, q]); - }); - - test('limit 1 and 100 accepted and forwarded as hints; non-number limit, null and non-boolean includeDelisted rejected without port call', async () => { - const fake = fakePort(() => []); - expect((await call(fake.port, { query: 'X', limit: 1 }, MIDDAY_CUTOFF_TS)).isError).toBe(false); - expect( - (await call(fake.port, { query: 'X', limit: 100, country: 'US' }, MIDDAY_CUTOFF_TS)).isError - ).toBe(false); - expect(fake.calls).toEqual([ - { query: 'X', limit: 1, includeDelisted: true, vaultCutoffTs: MIDDAY_CUTOFF_TS }, - { - query: 'X', - limit: 100, - country: 'US', - includeDelisted: true, - vaultCutoffTs: MIDDAY_CUTOFF_TS, - }, - ]); - - const bad = fakePort(() => []); - for (const args of [ - { query: 'X', limit: '20' }, - { query: 'X', limit: null }, - { query: 'X', limit: Number.NaN }, - { query: 42 }, - { query: 'X', country: null }, - { query: 'X', includeDelisted: 0 }, - { query: 'X', vaultCutoffTs: Date.UTC(2030, 0, 1) }, - ]) { - const res = await call(bad.port, args, MIDDAY_CUTOFF_TS); - expect(res.isError).toBe(true); - } - expect(bad.calls).toHaveLength(0); - }); - - test('malformed port responses yield a sanitized isError result', async () => { - const malformed: unknown[] = [ - null, - { rows: [] }, - 'not-an-array', - [null], - ['row'], - [{ ...row({ listingId: 1, ticker: 'M' }), listingId: '1' }], - [{ ...row({ listingId: 1, ticker: 'M' }), listingId: 1.5 }], - [{ ...row({ listingId: 1, ticker: 'M' }), instrumentId: undefined }], - [{ ...row({ listingId: 1, ticker: 'M' }), ticker: null }], - [{ ...row({ listingId: 1, ticker: 'M' }), name: undefined }], - [{ ...row({ listingId: 1, ticker: 'M' }), mic: 5 }], - [{ ...row({ listingId: 1, ticker: 'M' }), isin: 123 }], - [{ ...row({ listingId: 1, ticker: 'M' }), classSuffix: undefined }], - [{ ...row({ listingId: 1, ticker: 'M' }), firstBarDate: undefined }], - ]; - for (const response of malformed) { - const res = await call(fakePort(() => response).port, { query: 'M' }, MIDDAY_CUTOFF_TS); - expect(res.isError).toBe(true); - expect(res.text).toBe('Error: Tool execution failed.'); - } - }); - - test('non-Error port rejections are sanitized', async () => { - for (const thrown of ['password=hunter2', { secret: 'x' }, 42]) { - const res = await call( - fakePort(() => { - throw thrown; - }).port, - { query: 'AAPL' }, - MIDDAY_CUTOFF_TS - ); - expect(res.isError).toBe(true); - expect(res.text).toBe('Error: Tool execution failed.'); - expect(res.text).not.toContain('hunter2'); - } - }); - - test('returned rows are fresh projections: mutating port objects after the call does not alter output, and port input is not mutated', async () => { - const source = row({ listingId: 5, ticker: 'FRZ', lastBarDate: '2025-05-05' }); - const snapshot = JSON.stringify(source); - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createSearchSymbolsTool({ - port: { searchSymbols: async () => [source] }, - vaultContext: { vaultCutoffTs: MIDDAY_CUTOFF_TS }, - }), - ], - }); - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/call', - params: { name: 'search_symbols', arguments: { query: 'FRZ' } }, - }) - ); - expect(JSON.stringify(source)).toBe(snapshot); // clamping did not write back to the port row - const payload = JSON.parse( - (JSON.parse(raw as string) as { result: { content: { text: string }[] } }).result.content[0] - ?.text ?? '' - ) as SearchSymbolsResultPayload; - expect(payload.rows[0]?.lastBarDate).toBe(CUTOFF_DATE); - }); - - test('concurrent calls are independent and each respects its own arguments', async () => { - const rows = [ - row({ listingId: 1, ticker: 'TD', mic: 'XTSE', currency: 'CAD' }), - row({ listingId: 2, ticker: 'TD', mic: 'XNYS' }), - row({ listingId: 3, ticker: 'TDX', delistedAt: '2022-02-02', lastBarDate: '2022-02-01' }), - ]; - const fake = fakePort(q => - q.country === undefined ? rows : rows.filter(r => (q.country === 'CA') === (r.mic === 'XTSE')) - ); - const [all, ca, active] = await Promise.all([ - call(fake.port, { query: 'TD' }, MIDDAY_CUTOFF_TS), - call(fake.port, { query: 'TD', country: 'CA' }, MIDDAY_CUTOFF_TS), - call(fake.port, { query: 'TD', includeDelisted: false, limit: 1 }, MIDDAY_CUTOFF_TS), - ]); - expect(all.payload?.rows.map(r => r.listingId)).toEqual([1, 2, 3]); - expect(ca.payload?.rows.map(r => r.listingId)).toEqual([1]); - expect(active.payload).toMatchObject({ rowCount: 1, truncated: true }); - expect(active.payload?.rows.map(r => r.listingId)).toEqual([1]); - }); - - test('pre-1970 cutoff fences correctly', async () => { - const cutoff = Date.UTC(1965, 5, 30, 12, 0, 0, 0); - const rows = [ - row({ - listingId: 1, - ticker: 'IBM', - firstBarDate: '1962-01-02', - lastBarDate: '2025-03-28', - delistedAt: null, - }), - row({ listingId: 2, ticker: 'IBM', firstBarDate: '1970-01-02' }), - ]; - const res = await call(fakePort(() => rows).port, { query: 'IBM' }, cutoff); - expect(res.payload?.rows).toHaveLength(1); - expect(res.payload?.rows[0]).toMatchObject({ listingId: 1, lastBarDate: '1965-06-30' }); - }); -}); diff --git a/libs/research/test/mcp-search-symbols.test.ts b/libs/research/test/mcp-search-symbols.test.ts deleted file mode 100644 index 1db83564..00000000 --- a/libs/research/test/mcp-search-symbols.test.ts +++ /dev/null @@ -1,711 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type MarketDataStore, - MarketDataStoreValidationError, -} from '../src/market-data-store'; -import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb'; -import { - SEARCH_SYMBOLS_DEFAULT_LIMIT, - SEARCH_SYMBOLS_MAX_LIMIT, - SEARCH_SYMBOLS_MAX_QUERY_LENGTH, - type SearchSymbolsResultPayload, - type SymbolSearchPort, - type SymbolSearchQuery, - type SymbolSearchRow, - createAnalyzeSignalTool, - createEventStudyTool, - createMcpServer, - createQueryDataTool, - createSearchSymbolsTool, -} from '../src/mcp/index'; -import type { TrialLedgerExecutor } from '../src/trial-ledger'; - -const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); // 2025-03-31T00:00:00.000Z -const VAULT_CUTOFF_DATE = '2025-03-31'; - -interface FixtureRow extends SymbolSearchRow { - readonly country?: 'US' | 'CA'; -} - -function makeRow(overrides: Partial & { readonly listingId: number }): SymbolSearchRow { - return { - listingId: overrides.listingId, - instrumentId: overrides.instrumentId ?? overrides.listingId * 10, - ticker: overrides.ticker ?? `T${overrides.listingId}`, - classSuffix: overrides.classSuffix ?? null, - name: overrides.name ?? `Company ${overrides.listingId}`, - mic: overrides.mic ?? 'XNAS', - currency: overrides.currency ?? 'USD', - isin: overrides.isin ?? null, - firstBarDate: overrides.firstBarDate === undefined ? '2020-01-02' : overrides.firstBarDate, - lastBarDate: overrides.lastBarDate === undefined ? '2025-03-28' : overrides.lastBarDate, - delistedAt: overrides.delistedAt === undefined ? null : overrides.delistedAt, - }; -} - -interface FakePortState { - readonly calls: SymbolSearchQuery[]; - readonly port: SymbolSearchPort; -} - -function createFakePort(options?: { - readonly rows?: readonly FixtureRow[]; - readonly filterByCountry?: boolean; - readonly error?: unknown; - readonly rawReturn?: unknown; -}): FakePortState { - const calls: SymbolSearchQuery[] = []; - const rows = options?.rows ?? []; - - const port: SymbolSearchPort = { - async searchSymbols(q: SymbolSearchQuery): Promise { - calls.push({ ...q }); - if (options?.error !== undefined) { - throw options.error; - } - if (options?.rawReturn !== undefined) { - return options.rawReturn as readonly SymbolSearchRow[]; - } - if (options?.filterByCountry && q.country !== undefined) { - return rows.filter(row => row.country === q.country); - } - return [...rows]; - }, - }; - - return { calls, port }; -} - -function createMinimalStore(): MarketDataStore { - return { - bars() { - return { - async *[Symbol.asyncIterator]() { - // empty stream - }, - }; - }, - async universe() { - return []; - }, - 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'); - }, - }; -} - -function createMinimalLedger(): TrialLedgerExecutor { - return { - async query() { - return { rows: [] }; - }, - }; -} - -async function callSearchSymbols( - fake: FakePortState, - args: Record, - vaultCutoffTs = VAULT_CUTOFF_TS -): Promise<{ - readonly isError: boolean; - readonly text: string; - readonly payload: SearchSymbolsResultPayload | null; -}> { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createSearchSymbolsTool({ - port: fake.port, - vaultContext: { vaultCutoffTs }, - }), - ], - }); - - const raw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 'ss-1', - method: 'tools/call', - params: { - name: 'search_symbols', - arguments: args, - }, - }) - ); - - expect(raw).not.toBeNull(); - const parsed = JSON.parse(raw as string) as { - result: { - isError?: boolean; - content: { type: string; text: string }[]; - }; - }; - const isError = parsed.result.isError === true; - const text = parsed.result.content[0]?.text ?? ''; - - return { - isError, - text, - payload: isError ? null : (JSON.parse(text) as SearchSymbolsResultPayload), - }; -} - -describe('MCP search_symbols tool', () => { - test('registers alongside query_data, analyze_signal, and event_study and exposes strict schema via tools/list', async () => { - const store = createMinimalStore(); - const ledger = createMinimalLedger(); - const fake = createFakePort({ - rows: [ - makeRow({ - listingId: 42, - instrumentId: 420, - ticker: 'AAPL', - classSuffix: null, - name: 'Apple Inc.', - mic: 'XNAS', - currency: 'USD', - isin: 'US0378331005', - firstBarDate: '1980-12-12', - lastBarDate: '2025-03-28', - delistedAt: null, - }), - ], - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [ - createQueryDataTool({ - store, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - createAnalyzeSignalTool({ - store, - ledger, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - principalId: 'operator', - }), - createEventStudyTool({ - store, - ledger, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - principalId: 'operator', - resolveExchangeCalendars: () => ({}), - }), - createSearchSymbolsTool({ - port: fake.port, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }), - ], - }); - - const listRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 1, - method: 'tools/list', - }) - ); - expect(listRaw).not.toBeNull(); - - const listParsed = JSON.parse(listRaw as string) as { - result: { - tools: { - name: string; - description: string; - inputSchema: { - type: string; - properties: Record>; - required?: string[]; - additionalProperties: boolean; - }; - }[]; - }; - }; - - expect(listParsed.result.tools.map(t => t.name)).toEqual([ - 'query_data', - 'analyze_signal', - 'event_study', - 'search_symbols', - ]); - - const searchTool = listParsed.result.tools.find(t => t.name === 'search_symbols'); - expect(searchTool).toBeDefined(); - expect(searchTool?.inputSchema.type).toBe('object'); - expect(searchTool?.inputSchema.additionalProperties).toBe(false); - expect(searchTool?.inputSchema.required).toEqual(['query']); - expect(searchTool?.inputSchema.properties.query).toMatchObject({ - type: 'string', - minLength: 1, - maxLength: SEARCH_SYMBOLS_MAX_QUERY_LENGTH, - }); - expect(searchTool?.inputSchema.properties.limit).toMatchObject({ - type: 'integer', - minimum: 1, - maximum: SEARCH_SYMBOLS_MAX_LIMIT, - default: SEARCH_SYMBOLS_DEFAULT_LIMIT, - }); - expect(searchTool?.inputSchema.properties.country).toMatchObject({ - type: 'string', - enum: ['US', 'CA'], - }); - expect(searchTool?.inputSchema.properties.includeDelisted).toMatchObject({ - type: 'boolean', - default: true, - }); - expect(searchTool?.inputSchema.properties.scope).toBeUndefined(); - expect(searchTool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); - expect(searchTool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); - - // Exercise JSON-RPC tools/call end-to-end on the multi-tool server. - const callRaw = await server.handleMessage( - JSON.stringify({ - jsonrpc: '2.0', - id: 2, - method: 'tools/call', - params: { - name: 'search_symbols', - arguments: { query: 'AAPL' }, - }, - }) - ); - expect(callRaw).not.toBeNull(); - const callParsed = JSON.parse(callRaw as string) as { - result: { isError?: boolean; content: { type: string; text: string }[] }; - }; - expect(callParsed.result.isError).toBeUndefined(); - const payload = JSON.parse(callParsed.result.content[0]?.text ?? '') as SearchSymbolsResultPayload; - expect(payload).toEqual({ - scope: 'vault_fenced', - vaultCutoffTs: VAULT_CUTOFF_TS, - rowCount: 1, - truncated: false, - rows: [ - { - listingId: 42, - instrumentId: 420, - ticker: 'AAPL', - classSuffix: null, - name: 'Apple Inc.', - mic: 'XNAS', - currency: 'USD', - isin: 'US0378331005', - firstBarDate: '1980-12-12', - lastBarDate: '2025-03-28', - delistedAt: null, - }, - ], - }); - }); - - test('ranks exact ticker > ticker prefix > company name case-insensitively with numeric listingId tie-break', async () => { - const fixture: SymbolSearchRow[] = [ - makeRow({ listingId: 100, ticker: 'XYZ', name: 'Apple Blossom Holdings' }), - makeRow({ listingId: 10, ticker: 'AAPL', name: 'Apple Inc. Secondary' }), - makeRow({ listingId: 25, ticker: 'AAPLE', name: 'Apple Energy Corp' }), - makeRow({ listingId: 2, ticker: 'aapl', name: 'Apple Inc.' }), - makeRow({ listingId: 5, ticker: 'AAPLX', name: 'Apple Extended ETF' }), - makeRow({ listingId: 15, ticker: 'ZZZ', name: 'aapl Partners LP' }), - makeRow({ listingId: 30, ticker: 'OTHER', name: 'Unrelated Name' }), - ]; - - const fakeA = createFakePort({ rows: fixture }); - const fakeB = createFakePort({ rows: [...fixture].reverse() }); - - const resA = await callSearchSymbols(fakeA, { query: ' AaPl ' }); - const resB = await callSearchSymbols(fakeB, { query: ' AaPl ' }); - - expect(resA.isError).toBe(false); - expect(resB.isError).toBe(false); - expect(resA.payload).toEqual(resB.payload); - - // Exact ticker (2, 10) -> prefix (5, 25) -> name substring (15); unrelated candidates (30, 100) are excluded - expect(resA.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15]); - expect(resA.payload?.rowCount).toBe(5); - expect(resA.payload?.truncated).toBe(false); - - // Unrelated candidates must not trigger truncation when all actual matches fit within limit. - const exactFitRes = await callSearchSymbols(createFakePort({ rows: fixture }), { - query: 'AAPL', - limit: 5, - }); - expect(exactFitRes.isError).toBe(false); - expect(exactFitRes.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15]); - expect(exactFitRes.payload?.rowCount).toBe(5); - expect(exactFitRes.payload?.truncated).toBe(false); - - // When none of the port's returned candidates match, return an empty, non-truncated payload. - const noMatchRes = await callSearchSymbols(createFakePort({ rows: fixture }), { - query: 'UNMATCHED', - limit: 2, - }); - expect(noMatchRes.isError).toBe(false); - expect(noMatchRes.payload).toEqual({ - scope: 'vault_fenced', - vaultCutoffTs: VAULT_CUTOFF_TS, - rowCount: 0, - truncated: false, - rows: [], - }); - - // Verify trimmed query, default limit, includeDelisted: true, and vaultCutoffTs were passed to port. - expect(fakeA.calls).toHaveLength(1); - expect(fakeA.calls[0]).toEqual({ - query: 'AaPl', - limit: SEARCH_SYMBOLS_DEFAULT_LIMIT, - includeDelisted: true, - vaultCutoffTs: VAULT_CUTOFF_TS, - }); - }); - - test('forwards country filter and returns empty payload when no listings match', async () => { - const fake = createFakePort({ - filterByCountry: true, - rows: [ - { ...makeRow({ listingId: 1, ticker: 'SHOP', mic: 'XNYS', currency: 'USD' }), country: 'US' }, - { ...makeRow({ listingId: 2, ticker: 'SHOP', mic: 'XTSE', currency: 'CAD' }), country: 'CA' }, - ], - }); - - const caRes = await callSearchSymbols(fake, { query: 'SHOP', country: 'CA' }); - expect(caRes.isError).toBe(false); - expect(caRes.payload?.rows.map(r => r.listingId)).toEqual([2]); - expect(fake.calls[0]?.country).toBe('CA'); - - const emptyFake = createFakePort({ rows: [] }); - const emptyRes = await callSearchSymbols(emptyFake, { query: 'NO_SUCH_SYMBOL', country: 'US' }); - expect(emptyRes.isError).toBe(false); - expect(emptyRes.payload).toEqual({ - scope: 'vault_fenced', - vaultCutoffTs: VAULT_CUTOFF_TS, - rowCount: 0, - truncated: false, - rows: [], - }); - expect(emptyFake.calls[0]?.country).toBe('US'); - }); - - test('enforces default limit 20, hard max 100, exact-fit, and over-returning port truncation', async () => { - // 25 eligible rows with default limit (20) -> truncated: true - const rows25: SymbolSearchRow[] = []; - for (let i = 1; i <= 25; i += 1) { - rows25.push(makeRow({ listingId: i, ticker: `SYM${i}`, name: `Symbol ${i}` })); - } - const defaultOver = await callSearchSymbols(createFakePort({ rows: rows25 }), { query: 'SYM' }); - expect(defaultOver.isError).toBe(false); - expect(defaultOver.payload?.rowCount).toBe(20); - expect(defaultOver.payload?.rows).toHaveLength(20); - expect(defaultOver.payload?.truncated).toBe(true); - - // Exact fit of 20 eligible rows -> truncated: false - const defaultExact = await callSearchSymbols(createFakePort({ rows: rows25.slice(0, 20) }), { - query: 'SYM', - }); - expect(defaultExact.isError).toBe(false); - expect(defaultExact.payload?.rowCount).toBe(20); - expect(defaultExact.payload?.truncated).toBe(false); - - // Hard max 100 accepted; port over-returns 115 rows with late exact match at end - const rows115: SymbolSearchRow[] = []; - for (let i = 1; i <= 114; i += 1) { - rows115.push(makeRow({ listingId: i + 10, ticker: `ABC${i}`, name: `ABC Corp ${i}` })); - } - rows115.push(makeRow({ listingId: 999, ticker: 'ABC', name: 'Exact Match Late In Array' })); - - const maxOver = await callSearchSymbols(createFakePort({ rows: rows115 }), { - query: 'ABC', - limit: 100, - }); - expect(maxOver.isError).toBe(false); - expect(maxOver.payload?.rowCount).toBe(100); - expect(maxOver.payload?.rows).toHaveLength(100); - expect(maxOver.payload?.truncated).toBe(true); - // Late exact ticker match must still rank #1 before slicing - expect(maxOver.payload?.rows[0]?.listingId).toBe(999); - - // Exact fit at max 100 -> truncated: false - const maxExact = await callSearchSymbols(createFakePort({ rows: rows115.slice(0, 100) }), { - query: 'ABC', - limit: 100, - }); - expect(maxExact.isError).toBe(false); - expect(maxExact.payload?.rowCount).toBe(100); - expect(maxExact.payload?.truncated).toBe(false); - }); - - test('rows removed by Vault fencing or includeDelisted: false do not count toward truncation', async () => { - const rows: SymbolSearchRow[] = [ - // Post-cutoff listings placed ahead of eligible matches - makeRow({ listingId: 1, ticker: 'ACME', firstBarDate: '2025-04-01' }), - makeRow({ listingId: 2, ticker: 'ACME2', firstBarDate: '2025-05-15' }), - // Historically delisted listings - makeRow({ listingId: 3, ticker: 'ACME3', delistedAt: '2024-06-30', lastBarDate: '2024-06-28' }), - makeRow({ listingId: 4, ticker: 'ACME4', delistedAt: '2025-03-31', lastBarDate: '2025-03-31' }), - // Active as of cutoff (one active forever, one delisted after cutoff) - makeRow({ listingId: 5, ticker: 'ACME5', delistedAt: null }), - makeRow({ listingId: 6, ticker: 'ACME6', delistedAt: '2025-04-15', lastBarDate: '2025-04-14' }), - ]; - - const res = await callSearchSymbols(createFakePort({ rows }), { - query: 'ACME', - limit: 2, - includeDelisted: false, - }); - - expect(res.isError).toBe(false); - expect(res.payload?.rows.map(r => r.listingId)).toEqual([5, 6]); - expect(res.payload?.rowCount).toBe(2); - expect(res.payload?.truncated).toBe(false); - }); - - test('enforces Vault fencing on firstBarDate, lastBarDate, delistedAt, UTC cutoff equality, and null dates', async () => { - const extraFieldRow = { - ...makeRow({ - listingId: 10, - ticker: 'VLT', - classSuffix: 'A', - isin: 'US0000000010', - firstBarDate: '2024-02-29', // valid leap-year date - lastBarDate: '2025-06-01', // after cutoff -> clamp to 2025-03-31 - delistedAt: '2025-05-01', // after cutoff -> mask to null - }), - internalSecretField: 'must-not-leak', - } as unknown as SymbolSearchRow; - - const rows: SymbolSearchRow[] = [ - extraFieldRow, - // firstBarDate strictly after cutoff -> dropped - makeRow({ - listingId: 11, - ticker: 'VLT', - firstBarDate: '2025-04-01', - lastBarDate: '2025-06-01', - delistedAt: null, - }), - // firstBarDate / lastBarDate / delistedAt equal to cutoff -> kept as-is - makeRow({ - listingId: 12, - ticker: 'VLT', - firstBarDate: VAULT_CUTOFF_DATE, - lastBarDate: VAULT_CUTOFF_DATE, - delistedAt: VAULT_CUTOFF_DATE, - }), - // Null dates preserved - makeRow({ - listingId: 13, - ticker: 'VLT', - firstBarDate: null, - lastBarDate: null, - delistedAt: null, - }), - // Historical delisting before cutoff -> preserved by default - makeRow({ - listingId: 14, - ticker: 'VLT', - firstBarDate: '2019-01-03', - lastBarDate: '2023-10-12', - delistedAt: '2023-10-15', - }), - ]; - - const fakeDefault = createFakePort({ rows }); - const resDefault = await callSearchSymbols(fakeDefault, { query: 'VLT' }); - expect(resDefault.isError).toBe(false); - expect(resDefault.payload?.rows).toEqual([ - { - listingId: 10, - instrumentId: 100, - ticker: 'VLT', - classSuffix: 'A', - name: 'Company 10', - mic: 'XNAS', - currency: 'USD', - isin: 'US0000000010', - firstBarDate: '2024-02-29', - lastBarDate: VAULT_CUTOFF_DATE, - delistedAt: null, - }, - { - listingId: 12, - instrumentId: 120, - ticker: 'VLT', - classSuffix: null, - name: 'Company 12', - mic: 'XNAS', - currency: 'USD', - isin: null, - firstBarDate: VAULT_CUTOFF_DATE, - lastBarDate: VAULT_CUTOFF_DATE, - delistedAt: VAULT_CUTOFF_DATE, - }, - { - listingId: 13, - instrumentId: 130, - ticker: 'VLT', - classSuffix: null, - name: 'Company 13', - mic: 'XNAS', - currency: 'USD', - isin: null, - firstBarDate: null, - lastBarDate: null, - delistedAt: null, - }, - { - listingId: 14, - instrumentId: 140, - ticker: 'VLT', - classSuffix: null, - name: 'Company 14', - mic: 'XNAS', - currency: 'USD', - isin: null, - firstBarDate: '2019-01-03', - lastBarDate: '2023-10-12', - delistedAt: '2023-10-15', - }, - ]); - // Extra port property must not be projected - expect('internalSecretField' in (resDefault.payload?.rows[0] ?? {})).toBe(false); - - // With includeDelisted: false, historical delistings (12, 14) are excluded, - // while future delisting (10) remains eligible with delistedAt: null. - const fakeNoDelisted = createFakePort({ rows }); - const resNoDelisted = await callSearchSymbols(fakeNoDelisted, { - query: 'VLT', - includeDelisted: false, - }); - expect(resNoDelisted.isError).toBe(false); - expect(resNoDelisted.payload?.rows.map(r => r.listingId)).toEqual([10, 13]); - expect(resNoDelisted.payload?.rows[0]?.delistedAt).toBeNull(); - // Port must still be called with includeDelisted: true - expect(fakeNoDelisted.calls[0]?.includeDelisted).toBe(true); - }); - - test('rejects invalid port date strings with sanitized isError result', async () => { - const invalidDateCases: Partial[] = [ - { firstBarDate: '2025-02-29' }, // non-leap year Feb 29 - { lastBarDate: '2025-04-31' }, // April has 30 days - { delistedAt: '2025-13-01' }, // invalid month - { firstBarDate: '2025-03-31T00:00:00Z' }, // timestamp instead of YYYY-MM-DD - { lastBarDate: 'not-a-date' }, - { delistedAt: '' }, - ]; - - for (const badFields of invalidDateCases) { - const fake = createFakePort({ - rows: [makeRow({ listingId: 1, ticker: 'BAD', ...badFields })], - }); - const res = await callSearchSymbols(fake, { query: 'BAD' }); - expect(res.isError).toBe(true); - expect(res.text).toBe('Error: Tool execution failed.'); - } - }); - - test('factory throws MarketDataStoreValidationError on missing or invalid port or vaultCutoffTs', () => { - const validPort = createFakePort().port; - - expect(() => - createSearchSymbolsTool(null as unknown as Parameters[0]) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createSearchSymbolsTool({ - port: null as unknown as SymbolSearchPort, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }) - ).toThrow(MarketDataStoreValidationError); - - expect(() => - createSearchSymbolsTool({ - port: {} as unknown as SymbolSearchPort, - vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, - }) - ).toThrow(MarketDataStoreValidationError); - - const invalidCutoffs: unknown[] = [ - undefined, - null, - '2025-03-31', - Number.NaN, - Number.POSITIVE_INFINITY, - Number.NEGATIVE_INFINITY, - 123.45, - 8_640_000_000_000_000, - ]; - - for (const badCutoff of invalidCutoffs) { - expect(() => - createSearchSymbolsTool({ - port: validPort, - vaultContext: { vaultCutoffTs: badCutoff as number }, - }) - ).toThrow(MarketDataStoreValidationError); - } - - expect(() => - createSearchSymbolsTool({ - port: validPort, - vaultContext: undefined as unknown as { vaultCutoffTs: number }, - }) - ).toThrow(MarketDataStoreValidationError); - }); - - test('returns structured isError without calling port on invalid arguments', async () => { - const invalidInputs: Record[] = [ - {}, - { query: '' }, - { query: ' \t\n ' }, - { query: 'A'.repeat(SEARCH_SYMBOLS_MAX_QUERY_LENGTH + 1) }, - { query: 'AAPL', limit: 0 }, - { query: 'AAPL', limit: -5 }, - { query: 'AAPL', limit: SEARCH_SYMBOLS_MAX_LIMIT + 1 }, - { query: 'AAPL', limit: 1.5 }, - { query: 'AAPL', country: 'UK' }, - { query: 'AAPL', country: 'us' }, - { query: 'AAPL', includeDelisted: 'true' }, - { query: 'AAPL', scope: 'vault_evaluation_only' }, - { query: 'AAPL', unknownField: 123 }, - ]; - - for (const args of invalidInputs) { - const fake = createFakePort({ rows: [makeRow({ listingId: 1, ticker: 'AAPL' })] }); - const res = await callSearchSymbols(fake, args); - expect(res.isError).toBe(true); - expect(res.text).toContain('Invalid arguments for tool "search_symbols"'); - expect(fake.calls).toHaveLength(0); - } - }); - - test('returns sanitized isError without leaking error message when port rejects', async () => { - const fake = createFakePort({ - error: new Error('postgres://admin:super-secret@10.0.0.51:5432/trading_bot failed'), - }); - - const res = await callSearchSymbols(fake, { query: 'AAPL' }); - expect(res.isError).toBe(true); - expect(res.text).toBe('Error: Tool execution failed.'); - expect(res.text).not.toContain('super-secret'); - expect(res.text).not.toContain('10.0.0.51'); - expect(res.text).not.toContain('trading_bot'); - expect(fake.calls).toHaveLength(1); - }); -}); diff --git a/libs/research/test/mcp-stdio.test.ts b/libs/research/test/mcp-stdio.test.ts deleted file mode 100644 index 08d38bd5..00000000 --- a/libs/research/test/mcp-stdio.test.ts +++ /dev/null @@ -1,195 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { z } from 'zod'; -import { - JSON_RPC_ERROR_CODES, - type StdioOutput, - createMcpServer, - defineMcpTool, - runStdioServer, -} from '../src/mcp/index'; - -function createMemoryOutput(): { output: StdioOutput; chunks: string[]; text: () => string } { - const chunks: string[] = []; - const output: StdioOutput = { - write(chunk: string): boolean { - chunks.push(chunk); - return true; - }, - }; - return { - output, - chunks, - text: () => chunks.join(''), - }; -} - -async function* yieldChunks(chunks: readonly (Uint8Array | string)[]): AsyncGenerator { - for (const chunk of chunks) { - yield chunk; - } -} - -describe('MCP stdio transport', () => { - test('processes 3 messages (1 notification + 1 chunk-split multi-byte UTF-8 request) into exactly 2 newline-terminated responses', async () => { - const echoTool = defineMcpTool({ - name: 'echo_label', - description: 'Echoes a UTF-8 label.', - inputSchema: z.object({ label: z.string() }).strict(), - handler(input) { - return { - content: [{ type: 'text', text: input.label }], - }; - }, - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [echoTool], - }); - - const encoder = new TextEncoder(); - const msg1 = `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\n`; - const msg2 = `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`; - const msg3Bytes = encoder.encode( - `${JSON.stringify({ - jsonrpc: '2.0', - id: 'utf8-2', - method: 'tools/call', - params: { name: 'echo_label', arguments: { label: 'café-🚀-αβγ' } }, - })}\n` - ); - - // Split right in the middle of the multi-byte UTF-8 emoji sequence. - const rocketStart = msg3Bytes.indexOf(0xf0); - expect(rocketStart).toBeGreaterThan(0); - const splitPoint = rocketStart + 2; - - const input = yieldChunks([ - encoder.encode(msg1), - encoder.encode(msg2), - msg3Bytes.slice(0, splitPoint), - msg3Bytes.slice(splitPoint), - ]); - - const sink = createMemoryOutput(); - await runStdioServer(server, { input, output: sink.output }); - - const rawOut = sink.text(); - expect(rawOut.endsWith('\n')).toBe(true); - const lines = rawOut.slice(0, -1).split('\n'); - expect(lines).toHaveLength(2); - - const resp1 = JSON.parse(lines[0] ?? '') as { id: number; result: Record }; - const resp2 = JSON.parse(lines[1] ?? '') as { - id: string; - result: { content: { type: string; text: string }[] }; - }; - - expect(resp1.id).toBe(1); - expect(resp1.result).toEqual({}); - expect(resp2.id).toBe('utf8-2'); - expect(resp2.result.content[0]?.text).toBe('café-🚀-αβγ'); - }); - - test('preserves strict arrival order even when earlier async handler takes longer than later handler', async () => { - const delayedTool = defineMcpTool({ - name: 'delayed', - description: 'Resolves after deterministic microtask/timer delay.', - inputSchema: z.object({ tag: z.string(), delayMs: z.number().int().min(0) }).strict(), - async handler(input) { - await new Promise(resolve => { - setTimeout(resolve, input.delayMs); - }); - return { - content: [{ type: 'text', text: input.tag }], - }; - }, - }); - - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - tools: [delayedTool], - }); - - const payload = [ - JSON.stringify({ - jsonrpc: '2.0', - id: 'first-slow', - method: 'tools/call', - params: { name: 'delayed', arguments: { tag: 'first', delayMs: 25 } }, - }), - JSON.stringify({ - jsonrpc: '2.0', - id: 'second-fast', - method: 'tools/call', - params: { name: 'delayed', arguments: { tag: 'second', delayMs: 0 } }, - }), - ].join('\n'); - - const sink = createMemoryOutput(); - await runStdioServer(server, { - input: yieldChunks([`${payload}\n`]), - output: sink.output, - }); - - const lines = sink.text().trimEnd().split('\n'); - expect(lines).toHaveLength(2); - const first = JSON.parse(lines[0] ?? '') as { id: string }; - const second = JSON.parse(lines[1] ?? '') as { id: string }; - expect(first.id).toBe('first-slow'); - expect(second.id).toBe('second-fast'); - }); - - test('ignores blank lines, handles CRLF, and flushes a final non-newline-terminated line on EOF', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const input = yieldChunks([ - '\n \r\n', - `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\r\n`, - '\n', - JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' }), - ]); - - const sink = createMemoryOutput(); - await runStdioServer(server, { input, output: sink.output }); - - const lines = sink.text().trimEnd().split('\n'); - expect(lines).toHaveLength(2); - expect((JSON.parse(lines[0] ?? '') as { id: number }).id).toBe(1); - expect((JSON.parse(lines[1] ?? '') as { id: number }).id).toBe(2); - }); - - test('rejects oversized frames exceeding maxLineBytes with -32700 and recovers on the next line', async () => { - const server = createMcpServer({ - name: 'stock-bot-research', - version: '0.1.0', - }); - - const hugeLine = `{"jsonrpc":"2.0","id":1,"method":"ping","pad":"${'x'.repeat(300)}"}\n`; - const nextLine = `${JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' })}\n`; - - const sink = createMemoryOutput(); - await runStdioServer(server, { - input: yieldChunks([hugeLine, nextLine]), - output: sink.output, - maxLineBytes: 128, - }); - - const lines = sink.text().trimEnd().split('\n'); - expect(lines).toHaveLength(2); - const errResp = JSON.parse(lines[0] ?? '') as { - id: null; - error: { code: number }; - }; - const okResp = JSON.parse(lines[1] ?? '') as { id: number; result: Record }; - expect(errResp.id).toBeNull(); - expect(errResp.error.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR); - expect(okResp.id).toBe(2); - expect(okResp.result).toEqual({}); - }); -}); diff --git a/test/postgres/fresh-database-schema.test.ts b/test/postgres/fresh-database-schema.test.ts index 8bfb3325..df95c7b7 100644 --- a/test/postgres/fresh-database-schema.test.ts +++ b/test/postgres/fresh-database-schema.test.ts @@ -78,7 +78,6 @@ const RESEARCH_FILES = [ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', - '37-research-findings.sql', ]; const cleanup: (() => Promise | void)[] = []; @@ -139,13 +138,13 @@ async function createIsolatedFixture() { } describe.skipIf(!url)('fresh PostgreSQL database schema', () => { - test('Case A: init SQL 01-37 contain no CREATE DATABASE/\\c and create all master and research tables', async () => { + test('Case A: init SQL 01-36 contain no CREATE DATABASE/\\c and create all master and research tables', async () => { const f = await createIsolatedFixture(); const sqlFiles = readdirSync(initDir) .filter(file => file.endsWith('.sql')) .sort(); - expect(sqlFiles.length).toBeGreaterThanOrEqual(37); + expect(sqlFiles.length).toBeGreaterThanOrEqual(36); for (const file of sqlFiles) { const sql = readFileSync(join(initDir, file), 'utf8'); @@ -160,7 +159,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { ...LEGACY_MASTER_TABLES, // Security master tables (34) ...SECURITY_MASTER_TABLES, - // Research tables (06-33, 36-37, including representatives from 12, 16, 20, 22, 28, 30, 36, 37) + // Research tables (06-33, 36, including representatives from 12, 16, 20, 22, 28, 30, 36) 'backtests', 'backtest_results', 'runs', @@ -172,8 +171,6 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { 'paper_deployments', 'trial_ledger', 'vault_evaluations', - 'findings', - 'provider_caveats', ]) { expect(createdTables.has(expectedTable)).toBe(true); } @@ -196,8 +193,6 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { } expect(createdTables.has('trial_ledger')).toBe(false); expect(createdTables.has('vault_evaluations')).toBe(false); - expect(createdTables.has('findings')).toBe(false); - expect(createdTables.has('provider_caveats')).toBe(false); expect(await f.hasColumn('exchanges', 'visible')).toBe(true); const second = await runPostgresMigrations(f.postgres, { track: 'master' }); @@ -205,7 +200,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { expect(await f.recorded()).toEqual(MASTER_FILES); }); - test('Case C: all track with 06-08 pre-applied records master + research (including 36-37) and never records 06-08', async () => { + test('Case C: all track with 06-08 pre-applied records master + research (including 36) and never records 06-08', async () => { const f = await createIsolatedFixture(); for (const file of BOOTSTRAP_FILES) { @@ -228,8 +223,6 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => { } expect(createdTables.has('trial_ledger')).toBe(true); expect(createdTables.has('vault_evaluations')).toBe(true); - expect(createdTables.has('findings')).toBe(true); - expect(createdTables.has('provider_caveats')).toBe(true); const second = await runPostgresMigrations(f.postgres, { track: 'all' }); expect(second).toEqual([]); diff --git a/test/postgres/migration-runner.test.ts b/test/postgres/migration-runner.test.ts index 0e87eebb..6b43c3d3 100644 --- a/test/postgres/migration-runner.test.ts +++ b/test/postgres/migration-runner.test.ts @@ -37,7 +37,6 @@ const migrations = [ '32-candidate-parameter-defaults.sql', '33-candidate-decimal-normalization.sql', '36-trial-ledger.sql', - '37-research-findings.sql', ]; const cleanup: (() => Promise)[] = []; afterEach(async () => { @@ -385,22 +384,17 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { ]; // 1. research track must NOT apply 34-security-master.sql or 35-security-master-exchange-seed.sql, - // and MUST apply 36-trial-ledger.sql and 37-research-findings.sql; master track applies 34-35 (not 36-37) and is idempotent on re-run. + // and MUST apply 36-trial-ledger.sql; master track applies 34-35 (not 36) and is idempotent on re-run. const f1 = await fixture(); const runner1 = f1.startup(); const researchApplied = await runner1.runTrack('research'); expect(researchApplied).not.toContain('34-security-master.sql'); expect(researchApplied).not.toContain('35-security-master-exchange-seed.sql'); expect(researchApplied).toContain('36-trial-ledger.sql'); - expect(researchApplied).toContain('37-research-findings.sql'); - expect(researchApplied.indexOf('37-research-findings.sql')).toBe( - researchApplied.indexOf('36-trial-ledger.sql') + 1 - ); const recordedAfterResearch = await f1.recorded(); expect(recordedAfterResearch).not.toContain('34-security-master.sql'); expect(recordedAfterResearch).not.toContain('35-security-master-exchange-seed.sql'); expect(recordedAfterResearch).toContain('36-trial-ledger.sql'); - expect(recordedAfterResearch).toContain('37-research-findings.sql'); const tablesAfterResearch = new Set(await f1.relations()); for (const table of securityMasterTables) { @@ -408,14 +402,11 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { } expect(tablesAfterResearch.has('trial_ledger')).toBe(true); expect(tablesAfterResearch.has('vault_evaluations')).toBe(true); - expect(tablesAfterResearch.has('findings')).toBe(true); - expect(tablesAfterResearch.has('provider_caveats')).toBe(true); const masterApplied = await runner1.runTrack('master'); expect(masterApplied).toContain('34-security-master.sql'); expect(masterApplied).toContain('35-security-master-exchange-seed.sql'); expect(masterApplied).not.toContain('36-trial-ledger.sql'); - expect(masterApplied).not.toContain('37-research-findings.sql'); expect(masterApplied.indexOf('35-security-master-exchange-seed.sql')).toBe( masterApplied.indexOf('34-security-master.sql') + 1 ); @@ -430,7 +421,7 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { expect(await runner1.runTrack('master')).toEqual([]); - // 2. all track applies 34, 35, 36, and 37 alongside 01-05 and 09-33 and is idempotent. + // 2. all track applies 34, 35, and 36 alongside 01-05 and 09-33 and is idempotent. const f2 = await fixture(); const runner2 = f2.startup(); const allApplied = await runner2.runTrack('all'); @@ -441,12 +432,10 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { expect(allApplied).toContain('34-security-master.sql'); expect(allApplied).toContain('35-security-master-exchange-seed.sql'); expect(allApplied).toContain('36-trial-ledger.sql'); - expect(allApplied).toContain('37-research-findings.sql'); const recordedAfterAll = await f2.recorded(); expect(recordedAfterAll).toContain('34-security-master.sql'); expect(recordedAfterAll).toContain('35-security-master-exchange-seed.sql'); expect(recordedAfterAll).toContain('36-trial-ledger.sql'); - expect(recordedAfterAll).toContain('37-research-findings.sql'); const tablesAfterAll = new Set(await f2.relations()); for (const table of securityMasterTables) { @@ -454,8 +443,6 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => { } expect(tablesAfterAll.has('trial_ledger')).toBe(true); expect(tablesAfterAll.has('vault_evaluations')).toBe(true); - expect(tablesAfterAll.has('findings')).toBe(true); - expect(tablesAfterAll.has('provider_caveats')).toBe(true); expect(await runner2.runTrack('all')).toEqual([]); }); diff --git a/test/postgres/research-findings-contract.test.ts b/test/postgres/research-findings-contract.test.ts deleted file mode 100644 index 36c9d2e3..00000000 --- a/test/postgres/research-findings-contract.test.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { describe, expect, test } from 'bun:test'; -import { setLoggerConfig } from '@stock-bot/logger'; -import { runPostgresMigrations, type MigrationTrack } from '@stock-bot/postgres'; -import { - FILE_FINDING_INITIAL_STATUS, - FILE_FINDING_KINDS, - FILE_FINDING_MAX_EVIDENCE_REFS, - FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, - FILE_FINDING_MAX_REF_LENGTH, - FILE_FINDING_MAX_SUMMARY_LENGTH, - FILE_FINDING_MAX_TITLE_LENGTH, - FILE_FINDING_MAX_TRIAL_REFS, -} from '@stock-bot/research/mcp'; - -// Static contract checks for 37-research-findings.sql. No database needed, so these run in the -// sandbox as well as in Studio's unsandboxed run. They guard against drift between the SQL CHECKs, -// the MCP tool limits they mirror, and the design/DATA-CONTRACTS.md copy of the schema. - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); - -const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); -const sqlPath = `${initDir}37-research-findings.sql`; -const docPath = fileURLToPath(new URL('../../design/DATA-CONTRACTS.md', import.meta.url)); - -const readSql = () => readFileSync(sqlPath, 'utf8'); -const readDoc = () => readFileSync(docPath, 'utf8'); - -function stripComments(sql: string): string { - return sql - .split('\n') - .map(line => line.replace(/--.*$/, '').trimEnd()) - .join('\n'); -} - -function normalize(sql: string): string { - return stripComments(sql).replace(/\s+/g, ' ').trim(); -} - -function tableBlock(sql: string, table: string): string { - const match = new RegExp(`CREATE TABLE IF NOT EXISTS ${table} \\(\\n([\\s\\S]*?)\\n\\);`).exec( - stripComments(sql) - ); - if (!match?.[1]) { - throw new Error(`CREATE TABLE ${table} not found`); - } - return match[1].replace(/\s+/g, ' ').trim(); -} - -function docSqlBlock(): string { - const doc = readDoc(); - const tableStart = doc.indexOf('CREATE TABLE IF NOT EXISTS findings ('); - expect(tableStart).toBeGreaterThan(-1); - const fenceStart = doc.lastIndexOf('```sql', tableStart); - const fenceEnd = doc.indexOf('```', tableStart); - return doc.slice(fenceStart + '```sql'.length, fenceEnd).trim(); -} - -function trimCodePointsFromSql(): number[] { - const match = /U&'([^']*)'/.exec(stripComments(readSql())); - if (!match?.[1]) { - throw new Error('research_trim_ecmascript U& character set not found'); - } - return match[1] - .split('\\') - .filter(part => part.length > 0) - .map(part => { - expect(part).toMatch(/^[0-9A-F]{4}$/i); - return Number.parseInt(part, 16); - }); -} - -async function filesForTrack(track: MigrationTrack): Promise { - const postgres = { - transaction: async (callback: (client: { query: (sql: string) => unknown }) => Promise) => - callback({ query: async () => ({ rows: [] }) }), - }; - return runPostgresMigrations(postgres as never, { track }); -} - -describe('37-research-findings.sql static contract', () => { - test('creates exactly findings and provider_caveats with IF NOT EXISTS and no schema qualifiers', () => { - const sql = stripComments(readSql()); - const created = [...sql.matchAll(/CREATE TABLE\s+(IF NOT EXISTS\s+)?("?[\w.]+"?)/g)]; - expect(created.map(m => m[2])).toEqual(['findings', 'provider_caveats']); - expect(created.every(m => m[1] !== undefined)).toBe(true); - expect(sql).not.toMatch(/CREATE\s+DATABASE/i); - expect(sql).not.toMatch(/^\s*\\c\b/m); - expect(sql).not.toMatch(/\bSET\s+search_path\b/i); - expect(sql).not.toMatch(/\b(?:TABLE|EXISTS|ON|FROM)\s+"?\w+"?\."?\w+/i); - }); - - test('findings CHECKs mirror the file_finding tool limits exported from file-finding.ts', () => { - const findings = tableBlock(readSql(), 'findings'); - const kinds = FILE_FINDING_KINDS.map(kind => `'${kind}'`).join(', '); - - expect(findings).toContain(`CHECK (kind IN (${kinds}))`); - expect(findings).toContain(`DEFAULT '${FILE_FINDING_INITIAL_STATUS}'`); - expect(findings).toContain( - `CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND ${FILE_FINDING_MAX_TITLE_LENGTH})` - ); - expect(findings).toContain( - `CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND ${FILE_FINDING_MAX_SUMMARY_LENGTH})` - ); - expect(findings).toContain(`CHECK (cardinality(trial_refs) <= ${FILE_FINDING_MAX_TRIAL_REFS})`); - expect(findings).toContain( - `CHECK (cardinality(evidence_refs) <= ${FILE_FINDING_MAX_EVIDENCE_REFS})` - ); - expect(findings).toContain( - `CHECK (research_finding_refs_valid(trial_refs, ${FILE_FINDING_MAX_REF_LENGTH}))` - ); - expect(findings).toContain( - `CHECK (research_finding_refs_valid(evidence_refs, ${FILE_FINDING_MAX_REF_LENGTH}))` - ); - expect(findings).toContain( - `char_length(idempotency_key) BETWEEN 1 AND ${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH}` - ); - expect(findings).toContain('created_at TIMESTAMPTZ NOT NULL,'); - expect(findings).toMatch(/idempotency_key TEXT CHECK \(idempotency_key IS NULL OR/); - }); - - test('research_trim_ecmascript strips exactly the BMP code points String.prototype.trim() strips', () => { - const sqlSet = trimCodePointsFromSql(); - const jsSet: number[] = []; - for (let cp = 0; cp <= 0xffff; cp++) { - if (cp >= 0xd800 && cp <= 0xdfff) { - continue; - } - if (String.fromCharCode(cp).trim() === '') { - jsSet.push(cp); - } - } - - expect(new Set(sqlSet).size).toBe(sqlSet.length); - expect([...sqlSet].sort((a, b) => a - b)).toEqual(jsSet); - expect(sqlSet).toHaveLength(25); - }); - - test('both tables are append-only via reject_research_evidence_mutation row and TRUNCATE triggers', () => { - const sql = normalize(readSql()); - for (const table of ['findings', 'provider_caveats']) { - expect(sql).toContain( - `DROP TRIGGER IF EXISTS ${table}_retained ON ${table}; CREATE TRIGGER ${table}_retained BEFORE UPDATE OR DELETE ON ${table} FOR EACH ROW EXECUTE FUNCTION reject_research_evidence_mutation();` - ); - expect(sql).toContain( - `DROP TRIGGER IF EXISTS ${table}_no_truncate ON ${table}; CREATE TRIGGER ${table}_no_truncate BEFORE TRUNCATE ON ${table} FOR EACH STATEMENT EXECUTE FUNCTION reject_research_evidence_mutation();` - ); - } - // The migration must reuse the shared function, never redefine it. - expect(sql).not.toMatch(/FUNCTION reject_research_evidence_mutation\s*\(\s*\)\s*RETURNS/i); - }); - - test('design/DATA-CONTRACTS.md documents both tables and indexes exactly as the migration creates them', () => { - const doc = docSqlBlock(); - const sql = readSql(); - expect(tableBlock(doc, 'findings')).toBe(tableBlock(sql, 'findings')); - expect(tableBlock(doc, 'provider_caveats')).toBe(tableBlock(sql, 'provider_caveats')); - - const indexes = (text: string) => - [...normalize(text).matchAll(/CREATE (?:UNIQUE )?INDEX IF NOT EXISTS [^;]+;/g)].map( - m => m[0] - ); - expect(indexes(doc)).toEqual(indexes(sql)); - expect(indexes(sql)).toHaveLength(3); - }); - - test('37-research-findings.sql runs on research and all tracks right after 36 and never on master', async () => { - const research = await filesForTrack('research'); - const all = await filesForTrack('all'); - const master = await filesForTrack('master'); - - expect(research.indexOf('37-research-findings.sql')).toBe( - research.indexOf('36-trial-ledger.sql') + 1 - ); - expect(research.indexOf('36-trial-ledger.sql')).toBeGreaterThan(-1); - expect(all).toContain('37-research-findings.sql'); - expect(master).not.toContain('37-research-findings.sql'); - }); -}); diff --git a/test/postgres/research-findings-schema.test.ts b/test/postgres/research-findings-schema.test.ts deleted file mode 100644 index 60324763..00000000 --- a/test/postgres/research-findings-schema.test.ts +++ /dev/null @@ -1,700 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import { afterEach, describe, expect, test } from 'bun:test'; -import { Pool } from 'pg'; -import { getLogger, setLoggerConfig } from '@stock-bot/logger'; -import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; - -setLoggerConfig({ logLevel: 'fatal', logConsole: false }); -const logger = getLogger('research-findings-schema-test'); -const url = process.env.PIPELINE_TEST_DATABASE_URL; -const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); -const researchFindingsSqlPath = `${initDir}37-research-findings.sql`; - -const FIXED_TS = '2026-01-15T12:34:56.789Z'; -const EXPECTED_IMMUTABLE_MSG = /Retained research evidence cannot be rewritten or deleted/; - -const cleanup: (() => Promise | void)[] = []; -afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) { - await close(); - } -}); - -async function createIsolatedFixture() { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { - throw new Error('Dedicated stock_bot_safety database required'); - } - const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; - const admin = new Pool({ connectionString: url }); - await admin.query(`CREATE SCHEMA ${schema}`); - const poolUrl = new URL(url); - const existingOptions = poolUrl.searchParams.get('options')?.trim(); - const fixtureOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`; - poolUrl.searchParams.set( - 'options', - existingOptions ? `${existingOptions} ${fixtureOptions}` : fixtureOptions - ); - const pool = new Pool({ connectionString: poolUrl.toString() }); - cleanup.push(async () => { - await pool.end(); - await admin.query(`DROP SCHEMA ${schema} CASCADE`); - await admin.end(); - }); - - const activeSchema = (await pool.query<{ schema: string }>('SELECT current_schema() AS schema')) - .rows[0]?.schema; - if (activeSchema !== schema) { - throw new Error(`Expected active fixture schema ${schema}, got ${activeSchema ?? 'null'}`); - } - - // Bootstrap pre-additive tables needed by the research migration track. - for (const filename of [ - '06-create-backtest-tables.sql', - '07-fix-execution-time-type.sql', - '08-create-runs-table.sql', - ]) { - await pool.query(readFileSync(`${initDir}${filename}`, 'utf8')); - } - - const postgres = new PostgreSQLClient( - { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, - logger - ); - Object.defineProperty(postgres, 'connectionPool', { - get: () => ({ - connect: () => pool.connect(), - }), - }); - - await runPostgresMigrations(postgres, { track: 'research' }); - - return { pool, schema, postgres }; -} - -async function expectPgErrorCode( - operation: Promise, - expectedCode: string, - messagePattern?: RegExp -): Promise { - try { - await operation; - } catch (error) { - const pgError = error as { code?: string; message?: string } | null; - expect(pgError?.code).toBe(expectedCode); - if (messagePattern) { - expect(pgError?.message ?? '').toMatch(messagePattern); - } - return; - } - throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`); -} - -interface FindingInsertOverrides { - id?: string; - kind?: string; - title?: string; - summary?: string; - status?: string; - createdAt?: string; - trialRefs?: (string | null)[]; - evidenceRefs?: (string | null)[]; - idempotencyKey?: string | null; -} - -function insertFinding(pool: Pool, overrides: FindingInsertOverrides = {}) { - const id = overrides.id ?? `finding-${randomUUID()}`; - const kind = overrides.kind ?? 'finding'; - const title = overrides.title ?? 'Momentum factor decays after 5 sessions'; - const summary = overrides.summary ?? 'Cross-sectional rank IC turns negative past day 5.'; - const createdAt = overrides.createdAt ?? FIXED_TS; - const trialRefs = overrides.trialRefs ?? ['101', '102']; - const evidenceRefs = overrides.evidenceRefs ?? ['snap:2026-01-15:ic']; - const idempotencyKey = overrides.idempotencyKey === undefined ? null : overrides.idempotencyKey; - - if (overrides.status !== undefined) { - return pool.query( - `INSERT INTO findings ( - id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key - ) VALUES ($1, $2, $3, $4, $5, $6::timestamptz, $7::text[], $8::text[], $9) - RETURNING id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key`, - [ - id, - kind, - title, - summary, - overrides.status, - createdAt, - trialRefs, - evidenceRefs, - idempotencyKey, - ] - ); - } - - return pool.query( - `INSERT INTO findings ( - id, kind, title, summary, created_at, trial_refs, evidence_refs, idempotency_key - ) VALUES ($1, $2, $3, $4, $5::timestamptz, $6::text[], $7::text[], $8) - RETURNING id, kind, title, summary, status, created_at, trial_refs, evidence_refs, idempotency_key`, - [id, kind, title, summary, createdAt, trialRefs, evidenceRefs, idempotencyKey] - ); -} - -interface ProviderCaveatInsertOverrides { - id?: string; - provider?: string; - dataset?: string; - caveat?: string; - createdAt?: string; -} - -function insertProviderCaveat(pool: Pool, overrides: ProviderCaveatInsertOverrides = {}) { - const id = overrides.id ?? `caveat-${randomUUID()}`; - const provider = overrides.provider ?? 'EODHD'; - const dataset = overrides.dataset ?? 'eodIntraday1M'; - const caveat = - overrides.caveat ?? 'Intraday 1m OHLCV is retroactively split-adjusted; un-adjust before use.'; - - if (overrides.createdAt !== undefined) { - return pool.query( - `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) - VALUES ($1, $2, $3, $4, $5::timestamptz) - RETURNING id, provider, dataset, caveat, created_at`, - [id, provider, dataset, caveat, overrides.createdAt] - ); - } - - return pool.query( - `INSERT INTO provider_caveats (id, provider, dataset, caveat) - VALUES ($1, $2, $3, $4) - RETURNING id, provider, dataset, caveat, created_at`, - [id, provider, dataset, caveat] - ); -} - -interface ProtectionTriggerRow { - relname: string; - tgname: string; - proname: string; - tgenabled: string; -} - -const EXPECTED_PROTECTION_TRIGGERS: ProtectionTriggerRow[] = [ - { - relname: 'findings', - tgname: 'findings_no_truncate', - proname: 'reject_research_evidence_mutation', - tgenabled: 'O', - }, - { - relname: 'findings', - tgname: 'findings_retained', - proname: 'reject_research_evidence_mutation', - tgenabled: 'O', - }, - { - relname: 'provider_caveats', - tgname: 'provider_caveats_no_truncate', - proname: 'reject_research_evidence_mutation', - tgenabled: 'O', - }, - { - relname: 'provider_caveats', - tgname: 'provider_caveats_retained', - proname: 'reject_research_evidence_mutation', - tgenabled: 'O', - }, -]; - -async function listProtectionTriggers(pool: Pool, schema: string): Promise { - const result = await pool.query( - `SELECT c.relname, t.tgname, p.proname, t.tgenabled::text AS tgenabled - FROM pg_trigger t - JOIN pg_class c ON c.oid = t.tgrelid - JOIN pg_namespace n ON n.oid = c.relnamespace - JOIN pg_proc p ON p.oid = t.tgfoid - WHERE NOT t.tgisinternal - AND n.nspname = $1 - AND c.relname IN ('findings', 'provider_caveats') - ORDER BY c.relname COLLATE "C", t.tgname COLLATE "C"`, - [schema] - ); - return result.rows; -} - -describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema', () => { - test('creates tables, indexes, and triggers and is idempotent on runner re-run and raw SQL re-execution', async () => { - const f = await createIsolatedFixture(); - - const tables = new Set( - ( - await f.pool.query('SELECT tablename FROM pg_tables WHERE schemaname = $1', [f.schema]) - ).rows.map(row => row.tablename as string) - ); - expect(tables.has('findings')).toBe(true); - expect(tables.has('provider_caveats')).toBe(true); - - const indexDefs = new Map( - ( - await f.pool.query('SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = $1', [ - f.schema, - ]) - ).rows.map(row => [row.indexname as string, row.indexdef as string]) - ); - expect(indexDefs.get('idx_findings_idempotency_key')).toMatch( - /CREATE UNIQUE INDEX idx_findings_idempotency_key ON .*findings .* \(idempotency_key\) WHERE \(idempotency_key IS NOT NULL\)/ - ); - expect(indexDefs.get('idx_findings_created_at')).toMatch( - /CREATE INDEX idx_findings_created_at ON .*findings .* \(created_at\)/ - ); - expect(indexDefs.get('idx_provider_caveats_lower_provider')).toMatch( - /CREATE INDEX idx_provider_caveats_lower_provider ON .*provider_caveats .* \(lower\(provider\)\)/ - ); - - expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS); - - const insertedFinding = ( - await insertFinding(f.pool, { id: 'f-idempotent', idempotencyKey: 'idem-keep' }) - ).rows[0]; - const insertedCaveat = ( - await insertProviderCaveat(f.pool, { id: 'c-idempotent', createdAt: FIXED_TS }) - ).rows[0]; - - expect(await runPostgresMigrations(f.postgres, { track: 'research' })).toEqual([]); - - const rawSql = readFileSync(researchFindingsSqlPath, 'utf8'); - await f.pool.query(rawSql); - - expect(await listProtectionTriggers(f.pool, f.schema)).toEqual(EXPECTED_PROTECTION_TRIGGERS); - - const findingsAfter = (await f.pool.query('SELECT * FROM findings')).rows; - const caveatsAfter = (await f.pool.query('SELECT * FROM provider_caveats')).rows; - expect(findingsAfter).toEqual([insertedFinding]); - expect(caveatsAfter).toEqual([insertedCaveat]); - - await expectPgErrorCode( - f.pool.query("UPDATE findings SET title = 'mutated'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode(f.pool.query('DELETE FROM findings'), '23514', EXPECTED_IMMUTABLE_MSG); - await expectPgErrorCode(f.pool.query('TRUNCATE findings'), '23514', EXPECTED_IMMUTABLE_MSG); - - await expectPgErrorCode( - f.pool.query("UPDATE provider_caveats SET caveat = 'mutated'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode( - f.pool.query('DELETE FROM provider_caveats'), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode( - f.pool.query('TRUNCATE provider_caveats'), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - - expect((await f.pool.query('SELECT * FROM findings')).rows).toEqual([insertedFinding]); - expect((await f.pool.query('SELECT * FROM provider_caveats')).rows).toEqual([insertedCaveat]); - }); - - test('findings round-trips every FiledFindingRecord field, defaults status, and accepts exact limit boundaries', async () => { - const f = await createIsolatedFixture(); - - const first = ( - await insertFinding(f.pool, { - id: 'finding-001', - kind: 'finding', - title: 'Earnings drift persists through day 3', - summary: 'Post-announcement drift remains positive across US large caps.', - createdAt: FIXED_TS, - trialRefs: ['42', '43'], - evidenceRefs: ['artifact:drift-v1'], - idempotencyKey: 'req-001', - }) - ).rows[0]; - - expect(first.id).toBe('finding-001'); - expect(first.kind).toBe('finding'); - expect(first.title).toBe('Earnings drift persists through day 3'); - expect(first.summary).toBe('Post-announcement drift remains positive across US large caps.'); - expect(first.status).toBe('pending_review'); - expect((first.created_at as Date).toISOString()).toBe(FIXED_TS); - expect(first.trial_refs).toEqual(['42', '43']); - expect(first.evidence_refs).toEqual(['artifact:drift-v1']); - expect(first.idempotency_key).toBe('req-001'); - - // Second row exercises dead_end, empty evidence_refs, and exact boundary lengths/cardinalities - // including Unicode NBSP / ideographic-space padding around max-length title and summary. - const maxRefs = Array.from({ length: 32 }, (_, i) => `${i}`.padStart(256, 'r')); - const boundary = ( - await insertFinding(f.pool, { - id: 'finding-002', - kind: 'dead_end', - title: `\u00A0${'t'.repeat(256)}\u00A0`, - summary: `\u00A0\u3000${'s'.repeat(4096)}\u00A0`, - createdAt: '2026-02-01T00:00:00.000Z', - trialRefs: maxRefs, - evidenceRefs: [], - idempotencyKey: 'k'.repeat(128), - }) - ).rows[0]; - - expect(boundary.kind).toBe('dead_end'); - expect(boundary.status).toBe('pending_review'); - expect((boundary.created_at as Date).toISOString()).toBe('2026-02-01T00:00:00.000Z'); - expect(boundary.trial_refs).toEqual(maxRefs); - expect(boundary.evidence_refs).toEqual([]); - expect(boundary.idempotency_key).toBe('k'.repeat(128)); - - // 32 evidence_refs at 256 chars and 1-char idempotency key also succeed. - const maxEvidence = ( - await insertFinding(f.pool, { - id: 'finding-003', - trialRefs: [], - evidenceRefs: maxRefs, - idempotencyKey: 'x', - }) - ).rows[0]; - expect(maxEvidence.trial_refs).toEqual([]); - expect(maxEvidence.evidence_refs).toEqual(maxRefs); - expect(maxEvidence.idempotency_key).toBe('x'); - }); - - test('findings rejects invalid kind, blank or oversized fields, malformed ref arrays, and invalid idempotency keys', async () => { - const f = await createIsolatedFixture(); - - // Blank / whitespace-only (ASCII and ECMAScript Unicode) id and status - const unicodeBlanks = ['\u00A0', '\u00A0\u2003\u3000\uFEFF', '\u2028\u2029']; - await expectPgErrorCode(insertFinding(f.pool, { id: '' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { id: ' \t\n ' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { status: '' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { status: ' \t\r\n ' }), '23514'); - for (const blank of unicodeBlanks) { - await expectPgErrorCode(insertFinding(f.pool, { id: blank }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { status: blank }), '23514'); - } - - // Invalid kind - await expectPgErrorCode(insertFinding(f.pool, { kind: 'hypothesis' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { kind: 'FINDING' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { kind: '' }), '23514'); - - // Blank, whitespace-only (ASCII and ECMAScript Unicode), or oversized title / summary - await expectPgErrorCode(insertFinding(f.pool, { title: '' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { title: ' \t\n\r ' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { title: 't'.repeat(257) }), '23514'); - await expectPgErrorCode( - insertFinding(f.pool, { title: `\u00A0${'t'.repeat(257)}\u00A0` }), - '23514' - ); - await expectPgErrorCode(insertFinding(f.pool, { summary: '' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { summary: ' \t\n\r ' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { summary: 's'.repeat(4097) }), '23514'); - for (const blank of unicodeBlanks) { - await expectPgErrorCode(insertFinding(f.pool, { title: blank }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { summary: blank }), '23514'); - } - - // Cardinality > 32 - const refs33 = Array.from({ length: 33 }, (_, i) => `ref-${i}`); - await expectPgErrorCode(insertFinding(f.pool, { trialRefs: refs33 }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: refs33 }), '23514'); - - // Ref length > 256 - const ref257 = 'r'.repeat(257); - await expectPgErrorCode(insertFinding(f.pool, { trialRefs: [ref257] }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: ['ok', ref257] }), '23514'); - - // NULL array elements - await expectPgErrorCode(insertFinding(f.pool, { trialRefs: ['101', null] }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { evidenceRefs: [null] }), '23514'); - - // Multidimensional arrays - await expectPgErrorCode( - f.pool.query( - `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) - VALUES ('f-2d-trial', 'finding', 'Title', 'Summary', $1::timestamptz, '{{a,b},{c,d}}'::text[], '{}'::text[])`, - [FIXED_TS] - ), - '23514' - ); - await expectPgErrorCode( - f.pool.query( - `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) - VALUES ('f-2d-ev', 'finding', 'Title', 'Summary', $1::timestamptz, '{101}'::text[], '{{a,b},{c,d}}'::text[])`, - [FIXED_TS] - ), - '23514' - ); - - // Invalid idempotency_key (empty, whitespace-only, > 128 chars) - await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: '' }), '23514'); - await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: ' \t\n ' }), '23514'); - for (const blank of unicodeBlanks) { - await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: blank }), '23514'); - } - await expectPgErrorCode(insertFinding(f.pool, { idempotencyKey: 'k'.repeat(129) }), '23514'); - - expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0); - }); - - test('findings enforces unique non-NULL idempotency_key while allowing multiple NULL keys', async () => { - const f = await createIsolatedFixture(); - - await insertFinding(f.pool, { id: 'f-key-1', idempotencyKey: 'shared-key' }); - await expectPgErrorCode( - insertFinding(f.pool, { id: 'f-key-2', idempotencyKey: 'shared-key' }), - '23505' - ); - - await insertFinding(f.pool, { id: 'f-null-1', idempotencyKey: null }); - await insertFinding(f.pool, { id: 'f-null-2', idempotencyKey: null }); - - expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(3); - }); - - test('provider_caveats round-trips every ProviderCaveatRecord field, defaults created_at, and rejects blank fields', async () => { - const f = await createIsolatedFixture(); - - const explicit = ( - await insertProviderCaveat(f.pool, { - id: 'caveat-001', - provider: 'QuoteMedia', - dataset: 'qmSplits', - caveat: 'splitratio stores old_shares / new_shares; invert to canonical new / old.', - createdAt: FIXED_TS, - }) - ).rows[0]; - - expect(explicit.id).toBe('caveat-001'); - expect(explicit.provider).toBe('QuoteMedia'); - expect(explicit.dataset).toBe('qmSplits'); - expect(explicit.caveat).toBe( - 'splitratio stores old_shares / new_shares; invert to canonical new / old.' - ); - expect((explicit.created_at as Date).toISOString()).toBe(FIXED_TS); - - const defaulted = (await insertProviderCaveat(f.pool, { id: 'caveat-002' })).rows[0]; - expect(defaulted.created_at).toBeInstanceOf(Date); - - for (const blank of [ - '', - ' ', - '\t\n\r', - '\u00A0', - '\u00A0\u2003\u3000\uFEFF', - '\u2028\u2029', - ]) { - await expectPgErrorCode(insertProviderCaveat(f.pool, { id: blank }), '23514'); - await expectPgErrorCode(insertProviderCaveat(f.pool, { provider: blank }), '23514'); - await expectPgErrorCode(insertProviderCaveat(f.pool, { dataset: blank }), '23514'); - await expectPgErrorCode(insertProviderCaveat(f.pool, { caveat: blank }), '23514'); - } - - expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( - 2 - ); - }); - - test('UPDATE, DELETE, and TRUNCATE are blocked on both findings and provider_caveats', async () => { - const f = await createIsolatedFixture(); - - const findingBefore = (await insertFinding(f.pool, { id: 'f-immutable' })).rows[0]; - const caveatBefore = ( - await insertProviderCaveat(f.pool, { id: 'c-immutable', createdAt: FIXED_TS }) - ).rows[0]; - - await expectPgErrorCode( - f.pool.query("UPDATE findings SET status = 'approved'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode(f.pool.query('DELETE FROM findings'), '23514', EXPECTED_IMMUTABLE_MSG); - await expectPgErrorCode(f.pool.query('TRUNCATE findings'), '23514', EXPECTED_IMMUTABLE_MSG); - - await expectPgErrorCode( - f.pool.query("UPDATE provider_caveats SET provider = 'Other'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode( - f.pool.query('DELETE FROM provider_caveats'), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode( - f.pool.query('TRUNCATE provider_caveats'), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - - expect((await f.pool.query('SELECT * FROM findings')).rows).toEqual([findingBefore]); - expect((await f.pool.query('SELECT * FROM provider_caveats')).rows).toEqual([caveatBefore]); - }); -}); - -describe.skipIf(!url)('findings and provider_caveats PostgreSQL schema edge cases (QA)', () => { - test('research_trim_ecmascript matches String.prototype.trim() for every ECMAScript blank and for look-alike non-blanks', async () => { - const f = await createIsolatedFixture(); - // 25 ECMAScript WhiteSpace + LineTerminator code points, plus characters JS trim() keeps: - // ZERO WIDTH SPACE, NEXT LINE, MONGOLIAN VOWEL SEPARATOR, WORD JOINER. - const codePoints = [ - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0xa0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, - 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, - 0xfeff, 0x200b, 0x0085, 0x180e, 0x2060, - ]; - for (const cp of codePoints) { - const c = String.fromCodePoint(cp); - for (const input of [c, `${c}${c}a b${c}`]) { - const sqlTrimmed = ( - await f.pool.query<{ v: string }>('SELECT research_trim_ecmascript($1) AS v', [input]) - ).rows[0]?.v; - expect({ cp, input, trimmed: sqlTrimmed }).toEqual({ cp, input, trimmed: input.trim() }); - } - } - }); - - test('non-ECMAScript blanks the MCP tool accepts (U+200B, U+0085) are accepted, and text is stored untrimmed', async () => { - const f = await createIsolatedFixture(); - const paddedTitle = `\u00A0 Interior spacing\tkept \u3000`; - - const zwsp = (await insertFinding(f.pool, { id: 'f-zwsp', title: '\u200B' })).rows[0]; - const nel = (await insertFinding(f.pool, { id: 'f-nel', summary: '\u0085' })).rows[0]; - const padded = (await insertFinding(f.pool, { id: 'f-padded', title: paddedTitle })).rows[0]; - - expect(zwsp.title).toBe('\u200B'); - expect(nel.summary).toBe('\u0085'); - expect(padded.title).toBe(paddedTitle); - }); - - test('title/summary caps count code points: 256 astral characters accepted, 257 rejected', async () => { - const f = await createIsolatedFixture(); - const emoji = '\u{1F4C8}'; - - const ok = (await insertFinding(f.pool, { id: 'f-astral-ok', title: emoji.repeat(256) })) - .rows[0]; - expect(ok.title).toBe(emoji.repeat(256)); - await expectPgErrorCode( - insertFinding(f.pool, { id: 'f-astral-bad', title: emoji.repeat(257) }), - '23514' - ); - await expectPgErrorCode( - insertFinding(f.pool, { id: 'f-astral-ref', trialRefs: [emoji.repeat(257)] }), - '23514' - ); - }); - - test('NOT NULL columns reject NULL with SQLSTATE 23502 and leave no rows', async () => { - const f = await createIsolatedFixture(); - const base = { - id: 'f-null', - kind: 'finding', - title: 'Title', - summary: 'Summary', - created_at: FIXED_TS, - trial_refs: ['1'], - evidence_refs: [] as string[], - }; - for (const column of Object.keys(base) as (keyof typeof base)[]) { - const row = { ...base, [column]: null }; - await expectPgErrorCode( - f.pool.query( - `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs) - VALUES ($1, $2, $3, $4, $5::timestamptz, $6::text[], $7::text[])`, - [ - row.id, - row.kind, - row.title, - row.summary, - row.created_at, - row.trial_refs, - row.evidence_refs, - ] - ), - '23502' - ); - } - // created_at has no default on findings: the tool's clock must supply it. - await expectPgErrorCode( - f.pool.query( - `INSERT INTO findings (id, kind, title, summary, trial_refs, evidence_refs) - VALUES ('f-no-ts', 'finding', 'Title', 'Summary', '{1}', '{}')` - ), - '23502' - ); - await expectPgErrorCode( - f.pool.query( - `INSERT INTO findings (id, kind, title, summary, created_at, trial_refs, evidence_refs, status) - VALUES ('f-null-status', 'finding', 'Title', 'Summary', $1::timestamptz, '{1}', '{}', NULL)`, - [FIXED_TS] - ), - '23502' - ); - for (const column of ['id', 'provider', 'dataset', 'caveat', 'created_at']) { - const values: Record = { - id: 'c-null', - provider: 'EODHD', - dataset: 'eodPrices', - caveat: 'Caveat text', - created_at: FIXED_TS, - [column]: null, - }; - await expectPgErrorCode( - f.pool.query( - `INSERT INTO provider_caveats (id, provider, dataset, caveat, created_at) - VALUES ($1, $2, $3, $4, $5::timestamptz)`, - [values.id, values.provider, values.dataset, values.caveat, values.created_at] - ), - '23502' - ); - } - - expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(0); - expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( - 0 - ); - }); - - test('duplicate ids are rejected (23505) on both tables and idempotency keys are case-sensitive', async () => { - const f = await createIsolatedFixture(); - - await insertFinding(f.pool, { id: 'dup-finding' }); - await expectPgErrorCode(insertFinding(f.pool, { id: 'dup-finding' }), '23505'); - await insertProviderCaveat(f.pool, { id: 'dup-caveat' }); - await expectPgErrorCode(insertProviderCaveat(f.pool, { id: 'dup-caveat' }), '23505'); - - // file_finding compares idempotency keys exactly; the unique index must not fold case. - await insertFinding(f.pool, { id: 'f-case-1', idempotencyKey: 'Retry-Key' }); - await insertFinding(f.pool, { id: 'f-case-2', idempotencyKey: 'retry-key' }); - - expect((await f.pool.query('SELECT count(*)::int AS c FROM findings')).rows[0].c).toBe(3); - expect((await f.pool.query('SELECT count(*)::int AS c FROM provider_caveats')).rows[0].c).toBe( - 1 - ); - }); - - test('a rejected UPDATE matching one row leaves every other row and column untouched', async () => { - const f = await createIsolatedFixture(); - await insertFinding(f.pool, { id: 'f-a', createdAt: '2026-01-01T00:00:00.000Z' }); - await insertFinding(f.pool, { id: 'f-b', createdAt: '2026-01-02T00:00:00.000Z' }); - const before = (await f.pool.query('SELECT * FROM findings ORDER BY id')).rows; - - await expectPgErrorCode( - f.pool.query("UPDATE findings SET status = 'approved' WHERE id = 'f-b'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - await expectPgErrorCode( - f.pool.query("DELETE FROM findings WHERE id = 'f-a'"), - '23514', - EXPECTED_IMMUTABLE_MSG - ); - - expect((await f.pool.query('SELECT * FROM findings ORDER BY id')).rows).toEqual(before); - }); -}); diff --git a/test/postgres/security-master-contract.test.ts b/test/postgres/security-master-contract.test.ts index 292bca21..eb140bb2 100644 --- a/test/postgres/security-master-contract.test.ts +++ b/test/postgres/security-master-contract.test.ts @@ -274,13 +274,12 @@ describe('34-security-master.sql track registration', () => { expect(await runPostgresMigrations(postgres as never)).toEqual(research); }); - test('all track runs 33, 34, 35, 36, 37 last in exact order and skips 06-08', async () => { + test('all track runs 33, 34, 35, 36 last in exact order and skips 06-08', async () => { const all = await filesForTrack('all'); - expect(all.at(-5)).toBe('33-candidate-decimal-normalization.sql'); - expect(all.at(-4)).toBe('34-security-master.sql'); - expect(all.at(-3)).toBe('35-security-master-exchange-seed.sql'); - expect(all.at(-2)).toBe('36-trial-ledger.sql'); - expect(all.at(-1)).toBe('37-research-findings.sql'); + expect(all.at(-4)).toBe('33-candidate-decimal-normalization.sql'); + expect(all.at(-3)).toBe('34-security-master.sql'); + expect(all.at(-2)).toBe('35-security-master-exchange-seed.sql'); + expect(all.at(-1)).toBe('36-trial-ledger.sql'); for (const bootstrap of [ '06-create-backtest-tables.sql', '07-fix-execution-time-type.sql', diff --git a/test/unit/m2-baseline-report-doc.test.ts b/test/unit/m2-baseline-report-doc.test.ts deleted file mode 100644 index ca0504ba..00000000 --- a/test/unit/m2-baseline-report-doc.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { existsSync, readFileSync } from 'node:fs'; -import { join } from 'node:path'; - -// Guards the T-128 M2.0 baseline report (design/m2-baseline-report.md) against silent drift: it is -// the gate evidence the director reads before M2 starts, so its provenance SHAs, gate commands, -// exit codes and failure accounting must stay complete and internally consistent. Live repository -// facts it records (bun.lock contents, studio.config.json paths) are deliberately not pinned here: -// they are a point-in-time snapshot that M2 work is expected to change. -const repoRoot = join(import.meta.dir, '..', '..'); -const reportPath = join(repoRoot, 'design/m2-baseline-report.md'); -const doc = readFileSync(reportPath, 'utf8'); - -const M1_SHA = 'd52aa20bff3f5c259fb6e2bcfc2d3a78ad5224b1'; -const MASTER_SHA = '56b73b7e663d293079ab7bac264950dfa7a68b00'; -const STUDIO_TEST_COMMAND = - 'bun --env-file=/home/boki/.studio/test-env/stock-bot.env test && CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline'; - -function section(title: RegExp): string { - const lines = doc.split('\n'); - const start = lines.findIndex(line => /^## /.test(line) && title.test(line)); - expect(start).toBeGreaterThan(-1); - const rest = lines.slice(start + 1); - const end = rest.findIndex(line => /^## /.test(line)); - return rest.slice(0, end === -1 ? undefined : end).join('\n'); -} - -function subsection(body: string, title: RegExp): string { - const lines = body.split('\n'); - const start = lines.findIndex(line => /^### /.test(line) && title.test(line)); - expect(start).toBeGreaterThan(-1); - const rest = lines.slice(start + 1); - const end = rest.findIndex(line => /^### /.test(line)); - return rest.slice(0, end === -1 ? undefined : end).join('\n'); -} - -function tableRows(body: string): string[][] { - return body - .split('\n') - .filter(line => line.startsWith('|') && !/^\|\s*-/.test(line)) - .map(line => line.split('|').slice(1, -1).map(cell => cell.trim())) - .slice(1); // drop header row -} - -describe('M2 baseline verification report (T-128)', () => { - test('exists and leads with an explicit GREEN verdict and zero real failures', () => { - expect(existsSync(reportPath)).toBe(true); - const verdictLine = doc.split('\n').find(line => line.startsWith('**Verdict:**')); - expect(verdictLine).toBeDefined(); - expect(verdictLine).toContain('GREEN'); - expect(verdictLine).toContain('0 real failures'); - }); - - test('provenance records full M1 and master SHAs and the ancestry check exiting 0', () => { - const provenance = section(/^## 1\./); - expect(provenance).toContain(M1_SHA); - expect(provenance).toContain(MASTER_SHA); - const ancestry = tableRows(subsection(provenance, /Ancestry/)); - expect(ancestry.length).toBeGreaterThan(0); - for (const [command, , exitCode] of ancestry) { - expect(command).toContain(`git merge-base --is-ancestor ${M1_SHA} `); - expect(exitCode).toBe('`0`'); - } - expect(ancestry.some(([command]) => command!.includes(MASTER_SHA))).toBe(true); - }); - - test('sandbox git errors are preserved as exit 128, not reported as passes', () => { - const rows = tableRows(subsection(section(/^## 1\./), /Sandbox `git`/)); - expect(rows.map(r => r[0])).toEqual([ - '`git rev-parse HEAD`', - `\`git merge-base --is-ancestor ${M1_SHA} HEAD\``, - ]); - for (const row of rows) { - expect(row[1]).toBe('`128`'); - expect(row[2]).toContain('fatal:'); - } - }); - - test('every AGENTS.md sandbox gate is listed with exit code 0 and zero failures', () => { - const rows = tableRows(section(/^## 2\./)); - const gates = [ - 'bun run typecheck', - 'bun run test:contracts', - 'bun run lint:check', - 'CARGO_BUILD_JOBS=2 bun run test:native', - 'bun run test:utils', - 'bun run test:calculations', - 'CARGO_BUILD_JOBS=2 cargo test --workspace --lib --offline', - ]; - for (const gate of gates) { - const row = rows.find(cells => cells[0]!.startsWith(`\`${gate}\``)); - expect(row, gate).toBeDefined(); - expect(row![1]).toBe('`0`'); - expect(row![2]).toMatch(/^PASS/); - expect(row![2]).toMatch(/0 (errors|fail|failed)/); - } - }); - - test('sandbox failure classification sums to the reported 40 failures, all sandbox-only', () => { - const triage = section(/^## 3\./); - expect(triage).toMatch(/`40 fail`/); - expect(triage).toMatch(/\*\*Real failures:\*\* \*\*`0`\*\*/); - const rows = tableRows(subsection(triage, /Failure Classification Summary/)); - expect(rows).toHaveLength(10); - - let total = 0; - let gitBoundary = 0; - let postgresBoundary = 0; - for (const [file, fails, errorText, classification] of rows) { - const path = file!.replace(/`/g, ''); - expect(existsSync(join(repoRoot, path)), path).toBe(true); - const count = Number(fails!.match(/^(\d+)/)![1]); - total += count; - expect(classification).toContain('(a) Expected sandbox-only'); - if (/stock_bot_safety/.test(errorText!)) { - expect(path.startsWith('test/postgres/')).toBe(true); - postgresBoundary += count; - } else { - expect(errorText).toMatch(/git|Cannot inspect tracked files/); - gitBoundary += count; - } - } - expect(total).toBe(40); - expect(gitBoundary).toBe(38); - expect(postgresBoundary).toBe(2); - }); - - test('individual failing test names match the per-file counts in the classification table', () => { - const triage = section(/^## 3\./); - const summary = new Map( - tableRows(subsection(triage, /Failure Classification Summary/)).map(([file, fails]) => [ - file!.replace(/`/g, ''), - Number(fails!.match(/^(\d+)/)![1]), - ]), - ); - const lines = subsection(triage, /Individual Failing Test Names/).split('\n'); - const listed = new Map(); - let current: string | undefined; - for (const line of lines) { - const header = line.match(/^\d+\. \*\*`([^`]+)`\*\* \((\d+) fails?;/); - if (header) { - current = header[1]!; - expect(Number(header[2])).toBe(summary.get(current)!); - listed.set(current, []); - continue; - } - const name = line.match(/^\s+- `(.+)`$/); - if (name && current) {listed.get(current)!.push(name[1]!);} - } - expect([...listed.keys()].sort()).toEqual([...summary.keys()].sort()); - for (const [file, names] of listed) { - expect(names.length, file).toBe(summary.get(file)!); - expect(new Set(names).size, file).toBe(names.length); - } - }); - - test("Studio's authoritative build and test commands are recorded verbatim with exit 0", () => { - const rows = tableRows(section(/^## 4\./)); - const build = rows.find(r => r[0]!.includes('Build')); - const tests = rows.find(r => r[0]!.includes('Test')); - expect(build?.[2]).toBe('`bun run build`'); - expect(build?.[3]).toBe('`0`'); - expect(tests?.[2]).toBe(`\`${STUDIO_TEST_COMMAND}\``); - expect(tests?.[3]).toBe('`0`'); - for (const row of [build!, tests!]) {expect(row[4]).toContain('PASS');} - }); - - test('records all three M2 planning facts', () => { - const facts = section(/^## 5\./); - expect(facts).toContain('`@modelcontextprotocol/sdk` is **not present** in `bun.lock`'); - expect(facts).toContain('`crates.io`, `index.crates.io`, and `static.crates.io`'); - expect(facts).toContain('`python/tests/test_stockbot_sdk.py`'); - expect(facts).toContain('**is not invoked**'); - expect(facts).toContain('`docs/` does not exist'); - expect(facts).toContain('`design/MILESTONES.md` lines 83–103'); - expect(facts).toContain('left untouched'); - }); -}); diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index d47f9e02..1b9ab54e 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -131,19 +131,6 @@ Rules: Deferred out of `src/shorts.rs`: MongoDB `ceoShorts` BSON streaming, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, `rayon` sharding, and deriving `pct_float` from shares outstanding (values are passed through as supplied by the caller). -## `posts` Builder (`M2.2b`) - -`build_posts` (`src/posts.rs`) turns already-decoded `ceoPosts` rows (`CeoPost`) into two disjoint, deterministically sorted point-in-time `PostRow` streams (`newswire` and `retail`) aligned with `design/DATA-CONTRACTS.md` §1 (`ceoSymbols`, `ceoPosts`, `ceoShorts` row). - -Rules: -1. **Newswire vs. retail split:** `is_bot` is `true` iff `bot` is `"1"` after trimming whitespace; only `is_bot == true` rows route to `newswire`, and all other values (`None`, `"0"`, `""`, etc.) route to `retail`. -2. **Point-in-time `known_at` guard:** `posted_at = timestamp_ms * 1_000` (UTC microseconds) and `known_at = max(timestamp_ms, edited_ms) * 1_000` (`COALESCE(edited, timestamp)` clamped so `known_at >= posted_at` always holds). Any text-based feature MUST join on `known_at`, never `posted_at`. Rows with `edited_ms < timestamp_ms` clamp `known_at` to `posted_at` and increment `stats.edited_before_posted`. Both `stats.edited` and `stats.edited_before_posted` are counted on valid input rows before deduplication. Because `ceoPosts` overwrites `spiel` in place without version history, the builder retains one supplied version per `spiel_id` and cannot recover earlier pre-edit text. -3. **Validation & overflow:** Empty `spiel_id` or `timestamp_ms <= 0` rows are rejected before conversion and counted in `stats.rejected_invalid`. Overflow converting `timestamp_ms` or the selected `known_at` millisecond value to UTC microseconds returns `PostsError::TimestampOverflow`. -4. **Global `spiel_id` deduplication & deterministic tie-break:** Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail`. Within each `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties by the maximum lexicographic tuple `(posted_at, is_edited, is_bot, key, user_id, text)` (`None < Some` for `user_id`), with zero dependence on input order. The remaining `group_len - 1` rows are counted in `stats.duplicates_dropped`. -5. **Sort order & invariants:** Both `newswire` and `retail` are sorted strictly ascending by `(key, known_at, spiel_id)`. Any input permutation yields identical `newswire`, `retail`, and `stats`, and `input == newswire + retail + duplicates_dropped + rejected_invalid`. - -Deferred out of `src/posts.rs`: `ceoPosts` raw-BSON decoding (pending live `edited` BSON type verification), `provider_mapping` resolution, Parquet writing, CLI subcommand, and benchmarks. - ## `events` Builder (`M1.2g`) `build_events` (`src/events.rs`) turns raw `qmFilings` (`QmFiling`) and `qmEarnings` (`QmEarning`) streams into deterministically sorted point-in-time `EventRow` records matching `events/year=YYYY/part.parquet` in `design/DATA-CONTRACTS.md` (`listing_id, ts, known_at, known_at_source, kind, subtype, payload_json`), plus `partition_year_utc` / `EventRow::partition_year` for UTC `year=YYYY` partitioning. @@ -1566,48 +1553,6 @@ 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). -## Zero-Copy `eodIntraday1M` BSON Decoder (`M2.3d`) - -`src/bson_eod_intraday.rs` decodes raw `eodIntraday1M` MongoDB BSON documents in a single zero-copy forward pass (`RawEodIntradayBar<'a>`, `decode_eod_intraday_doc`, `decode_eod_intraday_bytes`, `decode_eod_intraday_buffer`, `BsonEodIntradayError`, `BsonEodIntradayDecodeStats`) with bounded-memory streaming helpers in `src/bson_stream.rs` (`decode_eod_intraday_chunks`, `decode_eod_intraday_stream`): - -- **Timestamp units:** `timestamp` is bar-start **UTC Unix seconds** (accepted in BSON `Int32`, `Int64`, or finite integral `Double` within `0..=i64::MAX / 1_000_000`) converted to UTC microseconds (`ts: i64`) via checked multiplication by `1_000_000`. It is bar start only (not a publication / `known_at` timestamp). -- **Split-adjusted passthrough:** `open`, `high`, `low`, `close` (finite and `> 0.0`) and `volume` (finite and `>= 0.0`, `-0.0` normalized to `+0.0`) are passed through untouched as the provider's retroactively split-adjusted values; downstream `bars_1m::build_bars_1m` performs split un-adjustment via `SplitTable`. -- **Conversion & zero-copy:** `eodSearchCode` is borrowed verbatim from the input `&RawDocument` slice; `into_eod_intraday_bar` / `try_into_eod_intraday_bar` map `(&'a str, i64)` directly into `bars_1m::EodIntradayBar`. - -## Point-in-Time Fundamentals Core (`M2.2a`) - -Pure, I/O-free, two-stage point-in-time fundamentals builder (`src/fundamentals.rs`, tested in `src/fundamentals_tests.rs`) generic over listing key `K`. BSON decoding, Zstd Parquet writing, CLI `curate-*` wiring, and `MarketDataStore.fundamentalsAsOf` are deferred to follow-up tasks. - -### Public API & Field Set - -- **Single field definition (`FundamentalsFields`):** - - Flow fields (4-quarter TTM-eligible): `revenue`, `net_income`, `operating_cash_flow`. - - Stock fields (point-in-time values, never summed for TTM): `total_assets`, `total_equity`, `shares_outstanding`. -- **Stage 1 (`build_fundamentals_rows`):** joins `FinancialObservation` against periodic `events::QmFiling` records (reusing `events::classify_form_type`, `FilingFormGroup::is_periodic_financial_report`, and `events::parse_filing_timefiled`) using an ordered `BTreeMap` (`UsTsx` vs `TsxvCse`). - - `10-Q` / SEDAR `Interim financial statements` map to `FiscalPeriod::Quarterly`; `10-K` / `40-F` / SEDAR `Annual financial statements` map to `FiscalPeriod::Annual`; non-periodic forms (`8-K`, `News release`, `MD&A`, etc.) are never linked. - - **Dated observations (`report_date: Some(rd)`):** links to the earliest matching periodic filing (amended or unamended) on that Eastern calendar date (`et_date == rd`, strictly after `period_end`), allowing late restatements/amendments beyond the inference window. If unlinked and `rd > lag_date`, the observation is dropped (`observations_dropped_unanchored_vintage`) rather than backdated. If a dated statutory-lag estimate for `(key, period_end, fiscal_period)` would become visible at or after a newer dated version (`rd_b > rd_a`, `known_at_b <= lag_micros`) of the same statement, the stale estimate is dropped (`observations_dropped_stale_estimate`) so an older vintage never rolls a newer filing backward. - - **Undated observations (`report_date: None`):** links to the earliest matching **non-amended** periodic filing strictly after `period_end` within inclusive heuristic windows of `QUARTERLY_FILING_LINK_WINDOW_DAYS = 75` or `ANNUAL_FILING_LINK_WINDOW_DAYS = 150` calendar days (sampled `qmFilings` carries no statement-period field). - - **Statutory-lag fallback:** unlinked rows receive `period_end + lag_days` (`+45d` Q / `+90d` FY for `UsTsx`; `+60d` Q / `+120d` FY for `TsxvCse`) at `16:05:00 America/Toronto` via `shorts::et_to_utc_micros`, tagged `known_at_source = "statutory_lag_estimate"`. - - **Validation, deduplication & determinism:** validates dates against `MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE` (`2008-01-01..=2030-12-31`), drops bad rows into per-category `FundamentalsStats` counters without panicking, normalizes `-0.0` to `0.0`, collapses exact duplicates, discards conflicting `(key, period_end, known_at_utc_micros)` groups, preserves distinct `known_at_utc_micros` restatement versions, and emits rows strictly sorted by `(key, period_end, known_at_utc_micros)`. -- **Stage 2 (`build_fundamentals_snapshots`, `fundamentals_as_of` / `fundamentals::as_of`):** - - Sweeps rows in `(key, known_at_utc_micros, period_end)` order, applying all updates at a timestamp before emitting one `FundamentalsSnapshot` with the latest `k` (`k >= 1`) visible periods in descending `period_end` order. - - Carries `None` fields forward only from the prior visible version of the same `(period_end, fiscal_period, currency)`, retaining per-field provenance so a snapshot is flagged `has_estimated_lag = true` (`known_at_source = "statutory_lag_estimate"`) whenever any visible slot or any quarter contributing to TTM used an estimate. - - 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`: diff --git a/tools/curate-etl/src/bars_1m.rs b/tools/curate-etl/src/bars_1m.rs deleted file mode 100644 index 88d2ad9d..00000000 --- a/tools/curate-etl/src/bars_1m.rs +++ /dev/null @@ -1,954 +0,0 @@ -//! 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"; - -/// Canonical provenance label written to [`Bar1mRow::source`] for raw `qmIntraday` bars. -pub const BARS_1M_SOURCE_QM: &str = "qm_raw"; - -/// Regular Trading Hours start minute in Eastern Time (`09:30 ET` = `570`). -pub const RTH_START_MINUTE_ET: u16 = 9 * 60 + 30; - -/// Regular Trading Hours exclusive end minute in Eastern Time (`16:00 ET` = `960`). -pub const RTH_END_MINUTE_ET: u16 = 16 * 60; - -/// Intraday market session classification in Eastern Time (`America/New_York` / `America/Toronto`). -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum IntradaySession { - /// Pre-market (`00:00..09:30 ET`, i.e., `minute_of_day < 570`). - Pre, - /// Regular trading hours (`09:30..16:00 ET`, i.e., `570 <= minute_of_day < 960`). - Rth, - /// Post-market / after-hours (`16:00..24:00 ET`, i.e., `minute_of_day >= 960`). - Post, -} - -impl IntradaySession { - /// Returns the canonical `bars_1m.session` string tag (`"PRE"`, `"RTH"`, or `"POST"`). - #[inline] - pub const fn as_str(self) -> &'static str { - match self { - Self::Pre => "PRE", - Self::Rth => "RTH", - Self::Post => "POST", - } - } - - /// Classifies an Eastern Time minute-of-day (`0..=1439`) into [`IntradaySession`]. - #[inline] - pub const fn from_et_minute(minute_of_day: u16) -> Self { - if minute_of_day < RTH_START_MINUTE_ET { - Self::Pre - } else if minute_of_day < RTH_END_MINUTE_ET { - Self::Rth - } else { - Self::Post - } - } -} - -/// A single raw `eodIntraday1M` 1-minute bar input. -/// -/// Per `design/DATA-CONTRACTS.md` §1, both OHLC and `volume` are retroactively split-adjusted. -#[derive(Debug, Clone, PartialEq)] -pub struct EodIntradayBar { - pub key: K, - /// Bar start timestamp in UTC microseconds since the Unix epoch. - pub ts: i64, - pub open: f64, - pub high: f64, - pub low: f64, - pub close: f64, - pub volume: f64, -} - -/// A single curated `bars_1m` row, sorted and unique by `(key, ts)`. -/// -/// Carries the `bars_1m` contract columns from `design/DATA-CONTRACTS.md` §B (`key`, `ts`, -/// raw un-adjusted OHLCV, `session`, `source`) plus the derived Eastern Time `session_date`. -/// Downstream writer columns (`vwap`, `known_at`) are intentionally left to the writer stage. -#[derive(Debug, Clone, PartialEq)] -pub struct Bar1mRow { - pub key: K, - /// Bar start timestamp in UTC microseconds since the Unix epoch. - pub ts: i64, - /// Local Eastern Time calendar date as days since `1970-01-01`. - pub session_date: i32, - pub open: f64, - pub high: f64, - pub low: f64, - pub close: f64, - pub volume: f64, - pub session: IntradaySession, - pub source: &'static str, -} - -/// Summary counters produced alongside [`Bars1mBuild::rows`]. -/// -/// Conservation invariants: -/// - `bars_in == rows_out + dropped_invalid_ohlc + dropped_inconsistent_ohlc + dropped_invalid_volume + dropped_ts_out_of_range + duplicate_collapsed + duplicate_conflict_dropped` -/// - `pre_rows_out + rth_rows_out + post_rows_out == rows_out` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Bars1mStats { - pub bars_in: usize, - pub rows_out: usize, - pub keys_out: usize, - pub pre_rows_out: usize, - pub rth_rows_out: usize, - pub post_rows_out: usize, - pub dropped_invalid_ohlc: usize, - pub dropped_inconsistent_ohlc: usize, - pub dropped_invalid_volume: usize, - pub dropped_ts_out_of_range: usize, - pub duplicate_collapsed: usize, - pub duplicate_conflict_dropped: usize, -} - -/// Output of [`build_bars_1m`]: sorted, unique 1m rows and build statistics. -#[derive(Debug, Clone, PartialEq)] -pub struct Bars1mBuild { - pub rows: Vec>, - pub stats: Bars1mStats, -} - -/// Typed caller errors returned by [`check_session_closes`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Bars1mError { - /// Caller-supplied `rel_tolerance` was non-finite (`NaN`, `+/-inf`) or `< 0.0`. - InvalidTolerance { rel_tolerance: f64 }, -} - -impl fmt::Display for Bars1mError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Self::InvalidTolerance { rel_tolerance } => write!( - f, - "invalid relative tolerance {rel_tolerance}: must be finite and >= 0" - ), - } - } -} - -impl Error for Bars1mError {} - -/// Daily raw close reference used by [`check_session_closes`]. -#[derive(Debug, Clone, PartialEq)] -pub struct DailySessionClose { - pub key: K, - /// Session date as days since `1970-01-01` (Eastern / trading calendar date). - pub session_date: i32, - pub close: f64, - /// Optional exclusive Eastern Time session-close cutoff in UTC microseconds. - /// - /// When `Some(cutoff_ts)`, only [`IntradaySession::Rth`] bars with `ts < cutoff_ts` are - /// eligible as the session's closing bar (for example, `13:00:00 ET` on an early-close half - /// day so post-close prints between `13:00` and `15:59 ET` do not displace the `12:59 ET` - /// closing bar while [`Bar1mRow::session`] retains the fixed `PRE`/`RTH`/`POST` tags). - /// When `None`, defaults to the standard `16:00:00 ET` RTH boundary. - pub session_close_ts: Option, -} - -impl DailySessionClose { - /// Creates a daily close reference using the standard `16:00:00 ET` RTH cutoff. - #[inline] - pub const fn new(key: K, session_date: i32, close: f64) -> Self { - Self { - key, - session_date, - close, - session_close_ts: None, - } - } - - /// Creates a daily close reference with an explicit exclusive UTC microsecond session-close - /// cutoff (for example, `13:00:00 ET` on a half-day early close). - #[inline] - pub const fn with_close_cutoff( - key: K, - session_date: i32, - close: f64, - session_close_ts: i64, - ) -> Self { - Self { - key, - session_date, - close, - session_close_ts: Some(session_close_ts), - } - } -} - -/// Explicit in-memory session-close cutoff policy required when resolving raw [`Bar1dRow`] -/// references for [`check_session_closes_against_bars_1d`] or [`DailySessionClose::from_bar_1d`]. -/// -/// Lookup precedence for `(key, session_date)`: -/// 1. Per-listing, per-date override (`Some(cutoff_ts)` or `None` to explicitly use standard -/// `16:00:00 ET` even when a market-wide per-date cutoff is configured, e.g., a TSX listing on -/// a US early-close day). -/// 2. Per-date cutoff (e.g., `13:00:00 ET` on the Friday after US Thanksgiving). -/// 3. Standard `16:00:00 ET` RTH boundary (`None`). -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SessionCloseCutoffPolicy -where - K: Eq + Hash, -{ - per_date: HashMap, - per_listing_date: HashMap>>, -} - -impl SessionCloseCutoffPolicy { - /// Creates an explicit policy using the standard `16:00:00 ET` RTH boundary for all listings - /// and dates (no early-close overrides). - pub fn standard_rth() -> Self { - Self { - per_date: HashMap::new(), - per_listing_date: HashMap::new(), - } - } - - /// Sets an exclusive UTC microsecond session-close cutoff for all listings on `session_date` - /// (unless overridden by a listing-specific rule). - pub fn set_date_cutoff(&mut self, session_date: i32, cutoff_ts: i64) { - self.per_date.insert(session_date, cutoff_ts); - } - - /// Builder-style variant of [`Self::set_date_cutoff`]. - pub fn with_date_cutoff(mut self, session_date: i32, cutoff_ts: i64) -> Self { - self.set_date_cutoff(session_date, cutoff_ts); - self - } - - /// Builder-style helper to populate multiple `(session_date, cutoff_ts)` per-date cutoffs. - pub fn with_date_cutoffs(mut self, cutoffs: I) -> Self - where - I: IntoIterator, - { - for (session_date, cutoff_ts) in cutoffs { - self.set_date_cutoff(session_date, cutoff_ts); - } - self - } - - /// Sets a per-listing, per-date cutoff override. - /// - /// Pass `Some(cutoff_ts)` for a listing-specific early close, or `None` to explicitly select - /// the standard `16:00:00 ET` cutoff for `key` on `session_date` even if a per-date cutoff is - /// configured. - pub fn set_listing_date_cutoff(&mut self, key: K, session_date: i32, cutoff_ts: Option) { - self.per_listing_date - .entry(key) - .or_default() - .insert(session_date, cutoff_ts); - } - - /// Builder-style variant of [`Self::set_listing_date_cutoff`]. - pub fn with_listing_date_cutoff( - mut self, - key: K, - session_date: i32, - cutoff_ts: Option, - ) -> Self { - self.set_listing_date_cutoff(key, session_date, cutoff_ts); - self - } - - /// Builder-style helper to populate multiple `(key, session_date, cutoff_ts)` listing - /// overrides. - pub fn with_listing_date_cutoffs(mut self, cutoffs: I) -> Self - where - I: IntoIterator)>, - { - for (key, session_date, cutoff_ts) in cutoffs { - self.set_listing_date_cutoff(key, session_date, cutoff_ts); - } - self - } - - /// Resolves the exclusive UTC microsecond session-close cutoff for `(key, session_date)`, - /// returning `None` when the standard `16:00:00 ET` RTH boundary applies. - #[inline] - pub fn cutoff_for(&self, key: &K, session_date: i32) -> Option { - if let Some(listing_cutoffs) = self.per_listing_date.get(key) { - if let Some(&override_cutoff) = listing_cutoffs.get(&session_date) { - return override_cutoff; - } - } - self.per_date.get(&session_date).copied() - } -} - -impl DailySessionClose { - /// Converts a raw [`Bar1dRow`] into a [`DailySessionClose`] using an explicit - /// [`SessionCloseCutoffPolicy`]. - #[inline] - pub fn from_bar_1d(row: Bar1dRow, cutoff_policy: &SessionCloseCutoffPolicy) -> Self { - let session_close_ts = cutoff_policy.cutoff_for(&row.key, row.session_date); - Self { - key: row.key, - session_date: row.session_date, - close: row.close, - session_close_ts, - } - } - - /// Converts a borrowed [`Bar1dRow`] into a [`DailySessionClose`] using an explicit - /// [`SessionCloseCutoffPolicy`]. - #[inline] - pub fn from_bar_1d_ref(row: &Bar1dRow, cutoff_policy: &SessionCloseCutoffPolicy) -> Self - where - K: Clone, - { - let session_close_ts = cutoff_policy.cutoff_for(&row.key, row.session_date); - Self { - key: row.key.clone(), - session_date: row.session_date, - close: row.close, - session_close_ts, - } - } -} - -/// A single session-close cross-check mismatch sample retained for downstream reporting. -#[derive(Debug, Clone, PartialEq)] -pub struct SessionCloseMismatchSample { - pub key: K, - pub session_date: i32, - pub last_rth_ts: i64, - pub close_1m: f64, - pub close_1d: f64, - pub rel: f64, -} - -/// Summary counters and mismatch metrics produced by [`check_session_closes`]. -/// -/// Conservation invariants: -/// - `checked + unchecked == rth_sessions` -/// - `within_tolerance + mismatched == checked` -/// - `daily_rows_in == daily_unique_partners + daily_invalid_close_dropped + daily_duplicate_collapsed + daily_duplicate_conflict_dropped` -#[derive(Debug, Clone, Copy, Default, PartialEq)] -pub struct SessionCloseStats { - pub rth_sessions: usize, - pub checked: usize, - pub within_tolerance: usize, - pub mismatched: usize, - pub unchecked: usize, - pub max_rel_diff: f64, - pub daily_rows_in: usize, - pub daily_unique_partners: usize, - pub daily_invalid_close_dropped: usize, - pub daily_duplicate_collapsed: usize, - pub daily_duplicate_conflict_dropped: usize, -} - -/// Output of [`check_session_closes`]: summary statistics and capped worst mismatch samples. -#[derive(Debug, Clone, PartialEq)] -pub struct SessionCloseCheck { - pub stats: SessionCloseStats, - pub mismatch_samples: Vec>, -} - -#[inline] -fn is_valid_price(price: f64) -> bool { - price.is_finite() && price > 0.0 -} - -#[inline] -fn is_consistent_ohlc(open: f64, high: f64, low: f64, close: f64) -> bool { - high >= low && open >= low && open <= high && close >= low && close <= high -} - -struct ValidatedIntradayBar { - key: K, - ts: i64, - session_date: i32, - session: IntradaySession, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -} - -#[inline] -fn validated_bar_values_bit_eq( - a: &ValidatedIntradayBar, - b: &ValidatedIntradayBar, -) -> bool { - a.open.to_bits() == b.open.to_bits() - && a.high.to_bits() == b.high.to_bits() - && a.low.to_bits() == b.low.to_bits() - && a.close.to_bits() == b.close.to_bits() - && a.volume.to_bits() == b.volume.to_bits() -} - -/// Builds sorted, unique `bars_1m` rows from split-adjusted `eodIntraday1M` bars. -/// -/// - Validates each input bar without panicking in strict priority order: -/// `dropped_invalid_ohlc` -> `dropped_inconsistent_ohlc` -> `dropped_invalid_volume` -> -/// `dropped_ts_out_of_range`. -/// - Normalizes `-0.0` volume to `+0.0`, sorts surviving bars by `(key, ts)`, collapses -/// bitwise-identical `(key, ts)` duplicates (`duplicate_collapsed`), and drops conflicting -/// duplicate groups (`duplicate_conflict_dropped`). -/// - Looks up the cumulative split factor on the strict `ex_date > session_date` boundary using -/// each bar's **Eastern Time** `session_date`, un-adjusts full OHLCV via [`unadjust_ohlcv`], -/// and re-validates post-unadjust values against floating-point overflow/underflow. -/// - Tags each emitted row with [`IntradaySession`] (`PRE`/`RTH`/`POST`) and -/// [`BARS_1M_SOURCE_EOD`]. -pub fn build_bars_1m(bars: B, splits: &SplitTable) -> Bars1mBuild -where - K: Ord + Eq + Hash + Clone, - B: IntoIterator>, -{ - let bars_iter = bars.into_iter(); - let mut valid_bars: Vec> = Vec::with_capacity(bars_iter.size_hint().0); - let mut stats = Bars1mStats::default(); - - for bar in bars_iter { - stats.bars_in += 1; - - if !is_valid_price(bar.open) - || !is_valid_price(bar.high) - || !is_valid_price(bar.low) - || !is_valid_price(bar.close) - { - stats.dropped_invalid_ohlc += 1; - continue; - } - if !is_consistent_ohlc(bar.open, bar.high, bar.low, bar.close) { - stats.dropped_inconsistent_ohlc += 1; - continue; - } - if !bar.volume.is_finite() || bar.volume < 0.0 { - stats.dropped_invalid_volume += 1; - continue; - } - let Ok(et_local) = utc_micros_to_et_local(bar.ts) else { - stats.dropped_ts_out_of_range += 1; - continue; - }; - - let volume = if bar.volume == 0.0 { 0.0 } else { bar.volume }; - valid_bars.push(ValidatedIntradayBar { - key: bar.key, - ts: bar.ts, - session_date: et_local.session_date, - session: IntradaySession::from_et_minute(et_local.minute_of_day), - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume, - }); - } - - valid_bars.sort_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.ts.cmp(&b.ts))); - - let mut rows: Vec> = Vec::with_capacity(valid_bars.len()); - let total_valid = valid_bars.len(); - let mut idx = 0usize; - - while idx < total_valid { - let key_start = idx; - let key = valid_bars[key_start].key.clone(); - while idx < total_valid && valid_bars[idx].key == key { - idx += 1; - } - let key_end = idx; - - let key_splits = splits.splits_for(&key); - let mut split_idx = 0usize; - let key_rows_start = rows.len(); - - let mut bar_idx = key_start; - while bar_idx < key_end { - let ts = valid_bars[bar_idx].ts; - let group_start = bar_idx; - while bar_idx < key_end && valid_bars[bar_idx].ts == ts { - bar_idx += 1; - } - let group_end = bar_idx; - let group_len = group_end - group_start; - - let first = &valid_bars[group_start]; - let all_identical = valid_bars[group_start + 1..group_end] - .iter() - .all(|other| validated_bar_values_bit_eq(first, other)); - - if !all_identical { - stats.duplicate_conflict_dropped += group_len; - continue; - } - - stats.duplicate_collapsed += group_len - 1; - - // `session_date` is monotonically non-decreasing with UTC `ts` (DST transitions - // happen at 02:00 local, never crossing midnight), so this two-pointer scan matches - // `SplitTable::cum_factor_after(&key, first.session_date)` bitwise. - while split_idx < key_splits.len() - && key_splits[split_idx].ex_date <= first.session_date - { - split_idx += 1; - } - - let factor = key_splits.get(split_idx).map_or(1.0, |e| e.suffix_factor); - let mut unadj = unadjust_ohlcv( - OhlcvBar { - open: first.open, - high: first.high, - low: first.low, - close: first.close, - volume: first.volume, - }, - factor, - ); - - if !is_valid_price(unadj.open) - || !is_valid_price(unadj.high) - || !is_valid_price(unadj.low) - || !is_valid_price(unadj.close) - { - stats.dropped_invalid_ohlc += 1; - continue; - } - if !is_consistent_ohlc(unadj.open, unadj.high, unadj.low, unadj.close) { - stats.dropped_inconsistent_ohlc += 1; - continue; - } - if !unadj.volume.is_finite() - || unadj.volume < 0.0 - || (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(SessionCloseMismatchSample); - -impl Ord for HeapSessionCloseMismatch { - #[inline] - fn cmp(&self, other: &Self) -> Ordering { - other - .0 - .rel - .total_cmp(&self.0.rel) - .then_with(|| self.0.key.cmp(&other.0.key)) - .then_with(|| self.0.session_date.cmp(&other.0.session_date)) - } -} - -impl PartialOrd for HeapSessionCloseMismatch { - #[inline] - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl PartialEq for HeapSessionCloseMismatch { - #[inline] - fn eq(&self, other: &Self) -> bool { - self.cmp(other) == Ordering::Equal - } -} - -impl Eq for HeapSessionCloseMismatch {} - -struct LastRthBar<'a, K> { - key: &'a K, - session_date: i32, - ts: i64, - close: f64, - /// `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], -) -> Vec> -where - K: Ord + 'a, - I: IntoIterator, -{ - let mut result: Vec> = Vec::new(); - let mut daily_idx = 0usize; - - let mut cur_group: Option<(&'a K, i32, Option)> = None; - let mut cur_best: Option> = None; - - for (key, session_date, ts, close) in rth_sorted { - let cutoff = match cur_group { - Some((gk, gd, cutoff)) if gk == key && gd == session_date => cutoff, - _ => { - if let Some(best) = cur_best.take() { - result.push(best); - } - while daily_idx < valid_daily.len() { - match valid_daily[daily_idx] - .key - .cmp(key) - .then_with(|| valid_daily[daily_idx].session_date.cmp(&session_date)) - { - Ordering::Less => daily_idx += 1, - Ordering::Equal | Ordering::Greater => break, - } - } - let cutoff = if daily_idx < valid_daily.len() - && &valid_daily[daily_idx].key == key - && valid_daily[daily_idx].session_date == session_date - { - valid_daily[daily_idx].session_close_ts - } else { - None - }; - cur_group = Some((key, session_date, cutoff)); - cutoff - } - }; - - if let Some(cutoff_ts) = cutoff { - if ts >= cutoff_ts { - continue; - } - } - - match &mut cur_best { - Some(best) => match ts.cmp(&best.ts) { - Ordering::Greater => { - best.ts = ts; - best.close = close; - best.conflicting_last_ts = false; - } - Ordering::Equal => { - if close.to_bits() != best.close.to_bits() { - best.conflicting_last_ts = true; - } - } - Ordering::Less => {} - }, - None => { - cur_best = Some(LastRthBar { - key, - session_date, - ts, - close, - conflicting_last_ts: false, - }); - } - } - } - - if let Some(best) = cur_best { - result.push(best); - } - result -} - -fn collect_last_rth_bars<'a, K: Ord>( - rows_1m: &'a [Bar1mRow], - valid_daily: &[DailySessionClose], -) -> Vec> { - let is_sorted = rows_1m.windows(2).all(|w| { - w[0].key - .cmp(&w[1].key) - .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( - rows_1m: &[Bar1mRow], - bars_1d_closes: I, - rel_tolerance: f64, -) -> Result, Bars1mError> -where - K: Ord + Clone, - D: Into>, - I: IntoIterator, -{ - if !rel_tolerance.is_finite() || rel_tolerance < 0.0 { - return Err(Bars1mError::InvalidTolerance { rel_tolerance }); - } - - let mut stats = SessionCloseStats::default(); - - let daily_iter = bars_1d_closes.into_iter(); - let mut valid_daily: Vec> = Vec::with_capacity(daily_iter.size_hint().0); - for item in daily_iter { - let daily: DailySessionClose = item.into(); - stats.daily_rows_in += 1; - if !is_valid_price(daily.close) { - stats.daily_invalid_close_dropped += 1; - continue; - } - valid_daily.push(daily); - } - - valid_daily.sort_unstable_by(|a, b| { - a.key - .cmp(&b.key) - .then_with(|| a.session_date.cmp(&b.session_date)) - }); - - let mut write_idx = 0usize; - let mut read_idx = 0usize; - let daily_valid_len = valid_daily.len(); - while read_idx < daily_valid_len { - let mut group_end = read_idx + 1; - while group_end < daily_valid_len - && valid_daily[group_end].key == valid_daily[read_idx].key - && valid_daily[group_end].session_date == valid_daily[read_idx].session_date - { - group_end += 1; - } - let group_len = group_end - read_idx; - let first_bits = valid_daily[read_idx].close.to_bits(); - let 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> = - 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> = - 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( - rows_1m: &[Bar1mRow], - bars_1d: I, - cutoff_policy: &SessionCloseCutoffPolicy, - rel_tolerance: f64, -) -> Result, Bars1mError> -where - K: Ord + Eq + Hash + Clone, - R: Borrow>, - I: IntoIterator, -{ - check_session_closes( - rows_1m, - bars_1d - .into_iter() - .map(|row| DailySessionClose::from_bar_1d_ref(row.borrow(), cutoff_policy)), - rel_tolerance, - ) -} - -#[cfg(test)] -#[path = "bars_1m_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bars_1m_tests.rs b/tools/curate-etl/src/bars_1m_tests.rs deleted file mode 100644 index de8e7d68..00000000 --- a/tools/curate-etl/src/bars_1m_tests.rs +++ /dev/null @@ -1,878 +0,0 @@ -use super::*; -use crate::bars::Bar1dRow; -use crate::session_close::{SESSION_MAX_SUPPORTED_UTC_MICROS, SESSION_MIN_SUPPORTED_UTC_MICROS}; -use crate::shorts::et_to_utc_micros; -use crate::split::{ymd_to_epoch_days, SplitEvent}; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn et_ts(y: i32, m: u32, d: u32, hour: u8, minute: u8) -> i64 { - et_to_utc_micros(day(y, m, d), hour, minute, 0).expect("valid ET timestamp") -} - -fn utc_ts(y: i32, m: u32, d: u32, hour: i64, minute: i64) -> i64 { - (i64::from(day(y, m, d)) * 86_400 + hour * 3_600 + minute * 60) * 1_000_000 -} - -fn bar_1m( - key: K, - ts: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> EodIntradayBar { - EodIntradayBar { - key, - ts, - open, - high, - low, - close, - volume, - } -} - -fn daily_row(key: K, session_date: i32, close: f64) -> Bar1dRow { - Bar1dRow { - key, - session_date, - open: close, - high: close, - low: close, - close, - volume: 100_000.0, - } -} - -fn assert_rel_eq(actual: f64, expected: f64, rel_tol: f64) { - let diff = (actual - expected).abs(); - let scale = expected.abs().max(1.0); - assert!( - diff <= rel_tol * scale, - "actual={actual} expected={expected} diff={diff} rel_tol={rel_tol}" - ); -} - -fn assert_bars_1m_invariants(stats: &Bars1mStats) { - assert_eq!( - stats.bars_in, - stats.rows_out - + stats.dropped_invalid_ohlc - + stats.dropped_inconsistent_ohlc - + stats.dropped_invalid_volume - + stats.dropped_ts_out_of_range - + stats.duplicate_collapsed - + stats.duplicate_conflict_dropped, - "bars_1m conservation invariant failed: {stats:?}" - ); - assert_eq!( - stats.rows_out, - stats.pre_rows_out + stats.rth_rows_out + stats.post_rows_out, - "session breakdown != rows_out: {stats:?}" - ); -} - -fn assert_close_check_invariants(stats: &SessionCloseStats) { - assert_eq!( - stats.checked + stats.unchecked, - stats.rth_sessions, - "checked + unchecked != rth_sessions: {stats:?}" - ); - assert_eq!( - stats.within_tolerance + stats.mismatched, - stats.checked, - "within_tolerance + mismatched != checked: {stats:?}" - ); - assert_eq!( - stats.daily_rows_in, - stats.daily_unique_partners - + stats.daily_invalid_close_dropped - + stats.daily_duplicate_collapsed - + stats.daily_duplicate_conflict_dropped, - "daily partner conservation failed: {stats:?}" - ); -} - -#[test] -fn nexm_reverse_split_1_for_20_unadjusts_pre_split_preserves_ex_date_and_matches_bars_1d() { - let pre_day = day(2025, 6, 17); - let ex_date = day(2025, 6, 18); - let post_day = day(2025, 6, 19); - - let splits = SplitTable::from_events([( - "NEXM.V".to_string(), - SplitEvent { - ex_date, - ratio: 0.05, - }, - )]) - .unwrap(); - - // Adjusted 1m bars from eodIntraday1M: - // Pre-split close = 24.29 -> un-adjusted = 24.29 * 0.05 = 1.2145, volume = 5000 / 0.05 = 100_000. - let pre_open_bar = bar_1m( - "NEXM.V".to_string(), - et_ts(2025, 6, 17, 9, 30), - 24.00, - 24.60, - 23.80, - 24.20, - 2_000.0, - ); - let pre_close_bar = bar_1m( - "NEXM.V".to_string(), - et_ts(2025, 6, 17, 15, 59), - 24.20, - 24.40, - 24.10, - 24.29, - 5_000.0, - ); - let ex_bar = bar_1m( - "NEXM.V".to_string(), - et_ts(2025, 6, 18, 15, 59), - 24.10, - 24.50, - 23.90, - 24.30, - 12_500.0, - ); - let post_bar = bar_1m( - "NEXM.V".to_string(), - et_ts(2025, 6, 19, 15, 59), - 24.30, - 24.80, - 24.00, - 24.65, - 9_800.0, - ); - - let built = build_bars_1m( - [ - pre_open_bar.clone(), - pre_close_bar.clone(), - ex_bar.clone(), - post_bar.clone(), - ], - &splits, - ); - assert_bars_1m_invariants(&built.stats); - assert_eq!(built.rows.len(), 4); - assert_eq!(built.stats.keys_out, 1); - assert_eq!(built.stats.rth_rows_out, 4); - - // Pre-split close bar un-adjusted: price * 0.05, volume / 0.05, dollar volume invariant. - let pre_close_out = &built.rows[1]; - assert_eq!(pre_close_out.session_date, pre_day); - assert_eq!(pre_close_out.session, IntradaySession::Rth); - assert_eq!(pre_close_out.source, BARS_1M_SOURCE_EOD); - assert_rel_eq(pre_close_out.open, 1.21, 1e-12); - assert_rel_eq(pre_close_out.high, 1.22, 1e-12); - assert_rel_eq(pre_close_out.low, 1.205, 1e-12); - assert_rel_eq(pre_close_out.close, 1.2145, 1e-12); - assert_rel_eq(pre_close_out.volume, 100_000.0, 1e-12); - assert_rel_eq( - pre_close_out.close * pre_close_out.volume, - pre_close_bar.close * pre_close_bar.volume, - 1e-12, - ); - - // Ex-date and post-split bars must be bit-for-bit unchanged. - for (actual, expected) in [(&built.rows[2], &ex_bar), (&built.rows[3], &post_bar)] { - assert_eq!(actual.open.to_bits(), expected.open.to_bits()); - assert_eq!(actual.high.to_bits(), expected.high.to_bits()); - assert_eq!(actual.low.to_bits(), expected.low.to_bits()); - assert_eq!(actual.close.to_bits(), expected.close.to_bits()); - assert_eq!(actual.volume.to_bits(), expected.volume.to_bits()); - } - - // Raw bars_1d closes match within 0.5% (0 mismatches). - let daily_closes = [ - daily_row("NEXM.V".to_string(), pre_day, 1.215), // ~0.041% diff vs 1.2145 - daily_row("NEXM.V".to_string(), ex_date, 24.30), - daily_row("NEXM.V".to_string(), post_day, 24.65), - ]; - let 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 = 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::, _>( - &[], - 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 = 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> = 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()); -} diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 4c352817..084869fd 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -1,7 +1,6 @@ //! Fixed-seed, std-only benchmark for the split-factor lookup and un-adjustment hot loop. use std::borrow::Cow; -use std::collections::BTreeMap; use std::fs::{self, File}; use std::hint::black_box; use std::io; @@ -17,10 +16,6 @@ use parquet::file::reader::{FileReader, SerializedFileReader}; use crate::adj::{build_adj_factors, AdjBuildStats, AdjError, DividendEvent}; use crate::bars::{build_bars_1d, Bars1dStats, BarsError, EodDailyBar, QmRawVolume}; -use crate::bars_1m::{ - build_bars_1m, check_session_closes, Bar1mRow, Bars1mError, Bars1mStats, DailySessionClose, - EodIntradayBar, IntradaySession, SessionCloseStats, BARS_1M_SOURCE_EOD, -}; use crate::bson_eod_prices::{decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats}; use crate::bson_qm_actions::{ decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, @@ -39,12 +34,7 @@ use crate::events::{ EventsStats, QmEarning, QmFiling, EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, }; -use crate::fundamentals::{ - build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, - FundamentalsError, FundamentalsFields, FundamentalsStats, StatutoryLagVenue, -}; use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar, FxSource, FX_PAIR_USDCAD}; -use crate::ilp::{IlpShardedWriter, IlpWriterError, IlpWriterOptions}; use crate::parquet_adj::{ write_adj_factors_dataset, AdjFactorsParquetRow, AdjFactorsWriteOptions, ParquetAdjError, }; @@ -65,7 +55,6 @@ use crate::parquet_shorts::{ write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, }; use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable}; -use crate::session_close::{et_session_close_utc_micros, SESSION_MIN_SUPPORTED_UTC_MICROS}; use crate::shorts::{ add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, CeoShortReport, ShortsError, ShortsStats, SHORTS_DISSEMINATION_HOUR_ET, SHORTS_DISSEMINATION_MINUTE_ET, @@ -77,14 +66,10 @@ pub const DEFAULT_BENCH_ROWS: usize = 10_000_000; pub const DEFAULT_ADJ_BENCH_EVENTS: usize = 1_000_000; pub const DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS: usize = 1_000_000; pub const DEFAULT_BARS_BENCH_ROWS: usize = 10_000_000; -pub const DEFAULT_BARS_1M_BENCH_ROWS: usize = 10_000_000; -pub const DEFAULT_ILP_BARS_1M_BENCH_ROWS: usize = DEFAULT_BARS_1M_BENCH_ROWS; -pub const ILP_BARS_1M_BENCH_SHARDS: usize = 4; pub const DEFAULT_FX_BENCH_ROWS: usize = 20_000; pub const DEFAULT_FX_BENCH_LOOKUPS: usize = 1_000_000; pub const DEFAULT_SHORTS_BENCH_ROWS: usize = 700_000; pub const DEFAULT_EVENTS_BENCH_ROWS: usize = 500_000; -pub const DEFAULT_FUNDAMENTALS_BENCH_ROWS: usize = 100_000; pub const DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS: usize = 10_000_000; pub const DEFAULT_PARQUET_BARS_BENCH_ROWS: usize = 5_000_000; pub const PARQUET_BARS_RAW_ROW_BYTES: usize = 84; @@ -120,16 +105,9 @@ const BENCH_SEED: u64 = 0x570C_4B07_5171_7E57; const ADJ_BENCH_SEED: u64 = 0x570C_4B07_AD7F_AC70; const CORPORATE_ACTIONS_BENCH_SEED: u64 = 0x570C_4B07_C049_AC71; const BARS_BENCH_SEED: u64 = 0x570C_4B07_BA45_1D00; -const BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_BA45_0100; -const ILP_BARS_1M_BENCH_SEED: u64 = 0x570C_4B07_119B_A451; -const BARS_1M_BENCH_KEY_COUNT: usize = 2_000; -const BARS_1M_BENCH_EVENT_COUNT: usize = 2_000; const FX_BENCH_SEED: u64 = 0x570C_4B07_F81D_CADE; const SHORTS_BENCH_SEED: u64 = 0x570C_4B07_5404_7500; const EVENTS_BENCH_SEED: u64 = 0x570C_4B07_E7E4_7500; -const FUNDAMENTALS_BENCH_SEED: u64 = 0x570C_4B07_F04D_A001; -const FUNDAMENTALS_BENCH_TARGET_OBS_PER_KEY: usize = 40; -const FUNDAMENTALS_BENCH_SNAPSHOT_K: usize = 4; const PROVIDER_MAPPING_BENCH_SEED: u64 = 0x570C_4B07_9407_1D00; const PARQUET_BARS_BENCH_SEED: u64 = 0x570C_4B07_9A49_BA45; const PARQUET_SHORTS_BENCH_SEED: u64 = 0x570C_4B07_9A49_5404; @@ -711,578 +689,6 @@ pub fn run_bars_benchmark(rows: usize) -> Result { }) } -/// Summary metrics produced by [`run_bars_1m_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Bars1mBenchReport { - pub rows: usize, - pub key_count: usize, - pub split_event_count: usize, - pub daily_rows_in: usize, - pub rows_out: usize, - pub keys_out: usize, - pub mismatch_samples_out: usize, - pub build_elapsed_ms: f64, - pub check_elapsed_ms: f64, - pub total_elapsed_ms: f64, - pub rows_per_sec: f64, - pub ns_per_row: f64, - pub checksum: u64, - pub build_stats: Bars1mStats, - pub close_stats: SessionCloseStats, -} - -fn verify_bars_1m_bench_self_check() -> Result<(), Bars1mError> { - let nexm_ex = ymd_to_epoch_days(2025, 6, 18).unwrap_or(20_257); - let nvda_ex = ymd_to_epoch_days(2024, 6, 10).unwrap_or(19_884); - let splits = SplitTable::from_events([ - ( - "NEXM.V", - SplitEvent { - ex_date: nexm_ex, - ratio: 0.05, - }, - ), - ( - "NVDA.US", - SplitEvent { - ex_date: nvda_ex, - ratio: 10.0, - }, - ), - ]) - .expect("valid bench self-check splits"); - - let nexm_pre_ts = et_to_utc_micros(nexm_ex - 1, 15, 59, 0).expect("valid ET"); - let nexm_ex_ts = et_to_utc_micros(nexm_ex, 15, 59, 0).expect("valid ET"); - let nvda_pre_ts = et_to_utc_micros(nvda_ex - 3, 15, 59, 0).expect("valid ET"); - let nvda_ex_ts = et_to_utc_micros(nvda_ex, 15, 59, 0).expect("valid ET"); - let est_day = ymd_to_epoch_days(2025, 1, 15).expect("valid date"); - let est_pre_ts = et_to_utc_micros(est_day, 9, 29, 0).expect("valid ET"); - let est_rth_ts = et_to_utc_micros(est_day, 9, 30, 0).expect("valid ET"); - let est_post_ts = et_to_utc_micros(est_day, 16, 0, 0).expect("valid ET"); - - let built = build_bars_1m( - [ - EodIntradayBar { - key: "NEXM.V", - ts: nexm_pre_ts, - open: 24.0, - high: 24.5, - low: 23.9, - close: 24.29, - volume: 5_000.0, - }, - EodIntradayBar { - key: "NEXM.V", - ts: nexm_ex_ts, - open: 24.1, - high: 24.4, - low: 24.0, - close: 24.30, - volume: 10_000.0, - }, - EodIntradayBar { - key: "NVDA.US", - ts: nvda_pre_ts, - open: 120.5, - high: 121.0, - low: 120.4, - close: 120.888, - volume: 412_390.0, - }, - EodIntradayBar { - key: "NVDA.US", - ts: nvda_ex_ts, - open: 121.5, - high: 121.9, - low: 121.4, - close: 121.79, - volume: 300_000.0, - }, - EodIntradayBar { - key: "SESS", - ts: est_pre_ts, - open: 10.0, - high: 10.1, - low: 9.9, - close: 10.0, - volume: 100.0, - }, - EodIntradayBar { - key: "SESS", - ts: est_rth_ts, - open: 10.0, - high: 10.1, - low: 9.9, - close: 10.0, - volume: 100.0, - }, - EodIntradayBar { - key: "SESS", - ts: est_post_ts, - open: 10.0, - high: 10.1, - low: 9.9, - close: 10.0, - volume: 100.0, - }, - ], - &splits, - ); - - assert_eq!(built.rows.len(), 7, "self-check expected 7 bars"); - assert!( - (built.rows[0].close - 1.2145).abs() < 1e-9, - "NEXM.V pre-split self-check failed" - ); - assert_eq!(built.rows[1].close.to_bits(), 24.30_f64.to_bits()); - assert!( - (built.rows[2].close - 1_208.88).abs() < 1e-9, - "NVDA.US pre-split close self-check failed" - ); - assert!( - (built.rows[2].volume - 41_239.0).abs() < 1e-9, - "NVDA.US pre-split volume self-check failed" - ); - assert_eq!(built.rows[3].close.to_bits(), 121.79_f64.to_bits()); - assert_eq!(built.rows[4].session, IntradaySession::Pre); - assert_eq!(built.rows[5].session, IntradaySession::Rth); - assert_eq!(built.rows[6].session, IntradaySession::Post); - - let daily = [ - DailySessionClose::new("NEXM.V", nexm_ex - 1, 1.2145), - DailySessionClose::new("NEXM.V", nexm_ex, 24.30), - DailySessionClose::new("NVDA.US", nvda_ex - 3, 1_208.88), - DailySessionClose::new("NVDA.US", nvda_ex, 121.79), - ]; - let check = check_session_closes(&built.rows, daily, 0.005)?; - assert_eq!(check.stats.checked, 4, "self-check expected 4 checked sessions"); - assert_eq!(check.stats.mismatched, 0, "self-check expected 0 mismatches"); - Ok(()) -} - -/// Runs the fixed-seed `build_bars_1m` + `check_session_closes` benchmark for `rows` 1-minute bars. -/// -/// Executes a pre-timing correctness self-check (NEXM.V 1:20 reverse split, NVDA.US 10:1 forward -/// split, EST/EDT session tagging, and `check_session_closes`), then generates `rows` deterministic -/// multi-session EST/EDT 1m bars across `2_000` `i32` keys with forward/reverse splits, a small -/// share of invalid/inconsistent/out-of-range/duplicate bars, and one daily close reference per -/// sampled synthetic session derived from its expected last valid RTH minute (with deliberate -/// mismatches and duplicate conflicts injected separately). Times [`build_bars_1m`] and -/// [`check_session_closes`] and returns throughput plus a deterministic `u64` checksum. -pub fn run_bars_1m_benchmark(rows: usize) -> Result { - verify_bars_1m_bench_self_check()?; - - let min_date = ymd_to_epoch_days(2024, 1, 2).unwrap_or(19_724); - let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); - let date_span = (max_date - min_date + 1) as u64; - - let mut rng = SplitMix64::new(BARS_1M_BENCH_SEED); - - let mut split_events = Vec::with_capacity(BARS_1M_BENCH_EVENT_COUNT); - for _ in 0..BARS_1M_BENCH_EVENT_COUNT { - let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1; - let ex_date = min_date + (rng.next_u64() % date_span) as i32; - let ratio = SAMPLE_RATIOS[(rng.next_u64() % (SAMPLE_RATIOS.len() as u64)) as usize]; - split_events.push((key, SplitEvent { ex_date, ratio })); - } - let splits = SplitTable::from_events(split_events).unwrap_or_default(); - let split_event_count = splits.event_count(); - - struct BenchRthCandidate { - key: i32, - session_date: i32, - ts: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, - } - - #[inline] - fn to_bench_rth_candidate(bar: &EodIntradayBar, session_date: i32) -> BenchRthCandidate { - BenchRthCandidate { - key: bar.key, - session_date, - ts: bar.ts, - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: if bar.volume == 0.0 { 0.0 } else { bar.volume }, - } - } - - #[inline] - fn bench_rth_values_bit_eq(a: &BenchRthCandidate, b: &BenchRthCandidate) -> bool { - a.open.to_bits() == b.open.to_bits() - && a.high.to_bits() == b.high.to_bits() - && a.low.to_bits() == b.low.to_bits() - && a.close.to_bits() == b.close.to_bits() - && a.volume.to_bits() == b.volume.to_bits() - } - - let mut bars: Vec> = Vec::with_capacity(rows); - // Track every valid RTH candidate with all five normalized OHLCV fields (including exact and - // conflicting duplicates) so we match `build_bars_1m`'s duplicate-conflict drop rule when - // deriving each session's expected last surviving valid RTH bar before timing. - let mut valid_rth_candidates: Vec = Vec::with_capacity(rows / 2 + 64); - - let mut last_valid: Option<(EodIntradayBar, i32, bool)> = None; - for _ in 0..rows { - let roll = rng.next_u64() % 1_000; - if roll < 5 { - if let Some((prev, prev_date, prev_is_rth)) = last_valid.clone() { - if prev_is_rth { - valid_rth_candidates.push(to_bench_rth_candidate(&prev, prev_date)); - } - bars.push(prev); - continue; - } - } else if roll < 7 { - if let Some((mut prev, prev_date, prev_is_rth)) = last_valid.clone() { - let orig_close_bits = prev.close.to_bits(); - prev.close = (prev.close + 0.05).min(prev.high); - if prev.close.to_bits() == orig_close_bits { - prev.close = (prev.close - 0.05).max(prev.low); - } - if prev_is_rth { - valid_rth_candidates.push(to_bench_rth_candidate(&prev, prev_date)); - } - bars.push(prev); - continue; - } - } - - let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1; - let session_date = min_date + (rng.next_u64() % date_span) as i32; - // 08:00..=19:59 ET (minutes 480..1200) -> spans PRE, RTH, and POST on both EST and EDT. - let et_minute = 480 + (rng.next_u64() % 720) as i64; - let is_rth = (570..960).contains(&et_minute); - let close_1600_utc = et_session_close_utc_micros(session_date).unwrap_or(0); - let ts = close_1600_utc + (et_minute - 960) * 60_000_000; - - let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01; - let spread = ((rng.next_u64() % 300) + 5) as f64 * 0.01; - let high = low + spread; - let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - let volume = ((rng.next_u64() % 500_000) + 10) as f64; - - let bar = match roll { - 7..=8 => EodIntradayBar { - key, - ts, - open: -1.0, - high, - low, - close, - volume, - }, - 9..=10 => EodIntradayBar { - key, - ts, - open, - high: low - 0.5, - low, - close, - volume, - }, - 11..=12 => EodIntradayBar { - key, - ts, - open, - high, - low, - close, - volume: -10.0, - }, - 13..=14 => EodIntradayBar { - key, - ts: SESSION_MIN_SUPPORTED_UTC_MICROS - 60_000_000, - open, - high, - low, - close, - volume, - }, - 15..=17 => { - let b = EodIntradayBar { - key, - ts, - open, - high, - low, - close, - volume: 0.0, - }; - if is_rth { - valid_rth_candidates.push(to_bench_rth_candidate(&b, session_date)); - } - last_valid = Some((b.clone(), session_date, is_rth)); - b - } - _ => { - let b = EodIntradayBar { - key, - ts, - open, - high, - low, - close, - volume, - }; - if is_rth { - valid_rth_candidates.push(to_bench_rth_candidate(&b, session_date)); - } - last_valid = Some((b.clone(), session_date, is_rth)); - b - } - }; - bars.push(bar); - } - - // Derive one daily reference close per sampled synthetic session from its expected last - // surviving valid RTH bar, then inject deliberate mismatches and conflicts separately. - valid_rth_candidates.sort_unstable_by(|a, b| { - a.key - .cmp(&b.key) - .then_with(|| a.session_date.cmp(&b.session_date)) - .then_with(|| a.ts.cmp(&b.ts)) - }); - - let mut daily_closes: Vec> = - Vec::with_capacity(valid_rth_candidates.len() / 4 + 64); - let mut idx = 0usize; - while idx < valid_rth_candidates.len() { - let key = valid_rth_candidates[idx].key; - let session_date = valid_rth_candidates[idx].session_date; - let mut session_end = idx + 1; - while session_end < valid_rth_candidates.len() - && valid_rth_candidates[session_end].key == key - && valid_rth_candidates[session_end].session_date == session_date - { - session_end += 1; - } - - // Find the last non-conflicted `(key, ts)` subgroup within this `(key, session_date)`. - let mut expected_last_close: Option = None; - let mut g = idx; - while g < session_end { - let ts = valid_rth_candidates[g].ts; - let mut g_end = g + 1; - while g_end < session_end && valid_rth_candidates[g_end].ts == ts { - g_end += 1; - } - let first = &valid_rth_candidates[g]; - let all_same = valid_rth_candidates[g + 1..g_end] - .iter() - .all(|c| bench_rth_values_bit_eq(first, c)); - if all_same { - expected_last_close = Some(first.close); - } - g = g_end; - } - idx = session_end; - - let Some(adj_close) = expected_last_close else { - continue; - }; - if (rng.next_u64() % 4) != 0 { - continue; - } - - let factor = splits.cum_factor_after(&key, session_date); - let raw_close = adj_close * factor; - let case_roll = rng.next_u64() % 200; - match case_roll { - 0..=1 => { - // Deliberate 5% mismatch (> 0.5% tolerance). - daily_closes.push(DailySessionClose::new(key, session_date, raw_close * 1.05)); - } - 2 => { - // Deliberate conflicting duplicate daily reference. - daily_closes.push(DailySessionClose::new(key, session_date, raw_close)); - daily_closes.push(DailySessionClose::new(key, session_date, raw_close * 1.03)); - } - 3 => { - // Deliberate identical duplicate daily reference. - daily_closes.push(DailySessionClose::new(key, session_date, raw_close)); - daily_closes.push(DailySessionClose::new(key, session_date, raw_close)); - } - _ => { - // Within-tolerance reference (-0.20%..+0.20%). - let jitter_bp = (rng.next_u64() % 41) as f64 - 20.0; - daily_closes.push(DailySessionClose::new( - key, - session_date, - raw_close * (1.0 + jitter_bp * 0.0001), - )); - } - } - } - drop(valid_rth_candidates); - - let daily_rows_in = daily_closes.len(); - - let build_start = Instant::now(); - let built = build_bars_1m(bars, &splits); - let build_elapsed_secs = build_start.elapsed().as_secs_f64(); - - let check_start = Instant::now(); - let checked = check_session_closes(&built.rows, daily_closes, 0.005)?; - let check_elapsed_secs = check_start.elapsed().as_secs_f64(); - - let total_elapsed_secs = build_elapsed_secs + check_elapsed_secs; - let build_elapsed_ms = build_elapsed_secs * 1_000.0; - let check_elapsed_ms = check_elapsed_secs * 1_000.0; - let total_elapsed_ms = total_elapsed_secs * 1_000.0; - - let mut hash = 0u64; - for row in &built.rows { - hash = mix_u64(hash, row.key as u64); - hash = mix_u64(hash, row.ts as u64); - hash = mix_u64(hash, row.session_date as u64); - hash = mix_u64(hash, row.session as u64); - hash = mix_u64(hash, row.open.to_bits()); - hash = mix_u64(hash, row.high.to_bits()); - hash = mix_u64(hash, row.low.to_bits()); - hash = mix_u64(hash, row.close.to_bits()); - hash = mix_u64(hash, row.volume.to_bits()); - } - for sample in &checked.mismatch_samples { - hash = mix_u64(hash, sample.key as u64); - hash = mix_u64(hash, sample.session_date as u64); - hash = mix_u64(hash, sample.last_rth_ts as u64); - hash = mix_u64(hash, sample.close_1m.to_bits()); - hash = mix_u64(hash, sample.close_1d.to_bits()); - hash = mix_u64(hash, sample.rel.to_bits()); - } - let checksum = black_box(hash); - let (rows_per_sec, ns_per_row) = compute_rates(rows, total_elapsed_secs); - - Ok(Bars1mBenchReport { - rows, - key_count: BARS_1M_BENCH_KEY_COUNT, - split_event_count, - daily_rows_in, - rows_out: built.stats.rows_out, - keys_out: built.stats.keys_out, - mismatch_samples_out: checked.mismatch_samples.len(), - build_elapsed_ms, - check_elapsed_ms, - total_elapsed_ms, - rows_per_sec, - ns_per_row, - checksum, - build_stats: built.stats, - close_stats: checked.stats, - }) -} - -/// Summary metrics produced by [`run_ilp_bars_1m_benchmark`]. -#[derive(Debug, Clone, PartialEq)] -pub struct IlpBars1mBenchReport { - pub rows: usize, - pub rows_encoded: usize, - pub key_count: usize, - pub shards: usize, - pub bytes: usize, - pub flushes: usize, - pub elapsed_ms: f64, - pub rows_per_sec: f64, - pub ns_per_row: f64, - pub bytes_per_row: f64, - pub mb_per_sec: f64, - pub per_shard_rows: Vec, -} - -/// Runs the fixed-seed QuestDB ILP v2 `bars_1m` encoding + sharded batching benchmark for `rows` -/// curated 1-minute equity bars across four `std::io::sink()` shards. -/// -/// Generates `rows` deterministic curated [`Bar1mRow`] records and `known_at` timestamps -/// across `2_000` `i32` listing IDs spanning `2024-01-02..=2025-12-31` (`PRE`/`RTH`/`POST`), then -/// times encoding and batching through [`IlpShardedWriter`] including [`IlpShardedWriter::finish`]. -pub fn run_ilp_bars_1m_benchmark(rows: usize) -> Result { - let min_date = ymd_to_epoch_days(2024, 1, 2).unwrap_or(19_724); - let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); - let date_span = (max_date - min_date + 1) as u64; - - let mut rng = SplitMix64::new(ILP_BARS_1M_BENCH_SEED); - let mut input_rows: Vec<(Bar1mRow, i64)> = Vec::with_capacity(rows); - - for _ in 0..rows { - let key = (rng.next_u64() % (BARS_1M_BENCH_KEY_COUNT as u64)) as i32 + 1; - let session_date = min_date + (rng.next_u64() % date_span) as i32; - let et_minute = (480 + (rng.next_u64() % 720)) as u16; - let close_1600_utc = et_session_close_utc_micros(session_date).unwrap_or(0); - let ts = close_1600_utc + (i64::from(et_minute) - 960) * 60_000_000; - let known_at = ts + 60_000_000; - - let low = ((rng.next_u64() % 40_000) + 100) as f64 * 0.01; - let spread = ((rng.next_u64() % 300) + 5) as f64 * 0.01; - let high = low + spread; - let open = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - let close = low + spread * ((rng.next_u64() % 100) as f64 * 0.01); - let volume = ((rng.next_u64() % 500_000) + 10) as f64; - - input_rows.push(( - Bar1mRow { - key, - ts, - session_date, - open, - high, - low, - close, - volume, - session: IntradaySession::from_et_minute(et_minute), - source: BARS_1M_SOURCE_EOD, - }, - known_at, - )); - } - - let sinks: Vec = (0..ILP_BARS_1M_BENCH_SHARDS).map(|_| io::sink()).collect(); - let mut writer = IlpShardedWriter::new(sinks, IlpWriterOptions::default())?; - - let start = Instant::now(); - for (row, known_at) in &input_rows { - writer.write_bar_1m(row, *known_at)?; - } - let stats = black_box(writer.finish()?); - let elapsed_secs = start.elapsed().as_secs_f64(); - let elapsed_ms = elapsed_secs * 1_000.0; - - let (rows_per_sec, ns_per_row) = compute_rates(stats.rows, elapsed_secs); - let bytes_per_row = if stats.rows == 0 { - 0.0 - } else { - stats.bytes as f64 / stats.rows as f64 - }; - let mb_per_sec = if elapsed_secs <= 0.0 || !elapsed_secs.is_finite() { - 0.0 - } else { - (stats.bytes as f64 / 1_000_000.0) / elapsed_secs - }; - - Ok(IlpBars1mBenchReport { - rows, - rows_encoded: stats.rows, - key_count: BARS_1M_BENCH_KEY_COUNT, - shards: ILP_BARS_1M_BENCH_SHARDS, - bytes: stats.bytes, - flushes: stats.flushes, - elapsed_ms, - rows_per_sec, - ns_per_row, - bytes_per_row, - mb_per_sec, - per_shard_rows: stats.per_shard_rows, - }) -} - /// Summary metrics produced by [`run_fx_benchmark`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct FxBenchReport { @@ -11049,316 +10455,6 @@ pub fn run_curate_events_cmd_benchmark( Ok(report) } -/// Summary metrics produced by [`run_fundamentals_benchmark`]. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct FundamentalsBenchReport { - pub rows: usize, - pub filings_in: usize, - pub key_count: usize, - pub rows_out: usize, - pub keys_out: usize, - pub snapshots_out: usize, - pub rows_elapsed_ms: f64, - pub snapshots_elapsed_ms: f64, - pub total_elapsed_ms: f64, - pub rows_per_sec: f64, - pub ns_per_row: f64, - pub checksum: u64, - pub stats: FundamentalsStats, -} - -fn format_bench_filing_timefiled(epoch_day: i32, hour: u8, minute: u8, second: u8) -> String { - let (y, m, d) = epoch_days_to_ymd(epoch_day); - let zone = if (4..=10).contains(&m) { "EDT" } else { "EST" }; - format!("{y:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02} {zone}") -} - -/// Runs the fixed-seed two-stage `fundamentals` benchmark (`build_fundamentals_rows` + -/// `build_fundamentals_snapshots`) for `rows` synthetic statement observations. -/// -/// Generates filings and observations before timing, exercising both `UsTsx` and `TsxvCse` venue -/// classes, linked periodic filings (10-Q/10-K/40-F/SEDAR), statutory-lag fallback, exact -/// duplicates, complete 4-quarter histories for TTM, and late Q1-style amendments. -pub fn run_fundamentals_benchmark( - rows: usize, -) -> Result { - if rows == 0 { - return Ok(FundamentalsBenchReport { - rows: 0, - filings_in: 0, - key_count: 0, - rows_out: 0, - keys_out: 0, - snapshots_out: 0, - rows_elapsed_ms: 0.0, - snapshots_elapsed_ms: 0.0, - total_elapsed_ms: 0.0, - rows_per_sec: 0.0, - ns_per_row: 0.0, - checksum: 0, - stats: FundamentalsStats::default(), - }); - } - - let key_count = (rows / FUNDAMENTALS_BENCH_TARGET_OBS_PER_KEY).max(1); - let mut venues: BTreeMap = BTreeMap::new(); - for k in 1..=(key_count as i32) { - let venue = if k % 10 < 7 { - StatutoryLagVenue::UsTsx - } else { - StatutoryLagVenue::TsxvCse - }; - venues.insert(k, venue); - } - - let base_start = ymd_to_epoch_days(2015, 3, 31).unwrap_or(16_525); - let mut rng = SplitMix64::new(FUNDAMENTALS_BENCH_SEED); - let mut observations: Vec> = Vec::with_capacity(rows); - let mut filings: Vec> = Vec::with_capacity(rows); - - let mut period_step: i32 = 0; - while observations.len() < rows { - for key in 1..=(key_count as i32) { - if observations.len() >= rows { - break; - } - let venue = venues[&key]; - let currency = match venue { - StatutoryLagVenue::UsTsx => { - if key % 5 == 0 { - "CAD" - } else { - "USD" - } - } - StatutoryLagVenue::TsxvCse => "CAD", - }; - - let is_annual = period_step % 5 == 4; - let quarter_index = period_step - (period_step / 5); - let period_end = if is_annual { - base_start + (quarter_index - 1) * 91 + 1 - } else { - base_start + quarter_index * 91 - }; - let fiscal_period = if is_annual { - FiscalPeriod::Annual - } else { - FiscalPeriod::Quarterly - }; - - let rev = ((rng.next_u64() % 50_000) + 1_000) as f64; - let fields = FundamentalsFields { - revenue: Some(rev), - net_income: Some(rev * 0.12), - operating_cash_flow: Some(rev * 0.18), - total_assets: Some(rev * 4.5), - total_equity: Some(rev * 2.1), - shares_outstanding: Some(1_000_000.0 + (key as f64) * 100.0), - }; - - let roll = rng.next_u64() % 100; - let report_date = if roll < 75 { - let lag = 25 + (rng.next_u64() % 30) as i32; - let file_day = period_end + lag; - let form_type = match (venue, fiscal_period) { - (StatutoryLagVenue::UsTsx, FiscalPeriod::Quarterly) => "10-Q", - (StatutoryLagVenue::UsTsx, FiscalPeriod::Annual) => { - if key % 5 == 0 { - "40-F" - } else { - "10-K" - } - } - (StatutoryLagVenue::TsxvCse, FiscalPeriod::Quarterly) => { - "Interim financial statements/report - English" - } - (StatutoryLagVenue::TsxvCse, FiscalPeriod::Annual) => { - "Annual financial statements - English" - } - }; - let hour = 8 + (rng.next_u64() % 10) as u8; - let minute = (rng.next_u64() % 60) as u8; - filings.push(QmFiling { - key, - timefiled: format_bench_filing_timefiled(file_day, hour, minute, 0), - form_type: form_type.to_string(), - filing_id: None, - url: None, - }); - if roll < 50 { - Some(file_day) - } else { - None - } - } else { - None - }; - - if roll % 19 == 0 { - filings.push(QmFiling { - key, - timefiled: format_bench_filing_timefiled(period_end + 10, 16, 15, 0), - form_type: "8-K".to_string(), - filing_id: None, - url: None, - }); - } - - let obs = FinancialObservation { - key, - period_end, - fiscal_period, - currency: currency.to_string(), - report_date, - fields, - }; - observations.push(obs.clone()); - - // ~3% exact duplicate - if observations.len() < rows && roll < 3 { - observations.push(obs); - } - - // ~2% late amendment of prior quarter (after current quarter's filing) - if observations.len() < rows && !is_annual && quarter_index >= 1 && (3..5).contains(&roll) - { - let prior_pe = period_end - 91; - let amend_day = period_end + 60; - filings.push(QmFiling { - key, - timefiled: format_bench_filing_timefiled(amend_day, 17, 0, 0), - form_type: "10-Q/A".to_string(), - filing_id: None, - url: None, - }); - observations.push(FinancialObservation { - key, - period_end: prior_pe, - fiscal_period: FiscalPeriod::Quarterly, - currency: currency.to_string(), - report_date: Some(amend_day), - fields: FundamentalsFields { - revenue: Some(rev * 1.03), - net_income: Some(rev * 0.13), - operating_cash_flow: None, - total_assets: None, - total_equity: Some(rev * 2.15), - shares_outstanding: None, - }, - }); - } - } - period_step += 1; - } - - let filings_in = filings.len(); - - let rows_start = Instant::now(); - let built = build_fundamentals_rows(observations, filings, &venues); - let rows_elapsed_secs = rows_start.elapsed().as_secs_f64(); - - let snaps_start = Instant::now(); - let snapshots = build_fundamentals_snapshots(&built.rows, FUNDAMENTALS_BENCH_SNAPSHOT_K)?; - let snaps_elapsed_secs = snaps_start.elapsed().as_secs_f64(); - - let total_elapsed_secs = rows_elapsed_secs + snaps_elapsed_secs; - let (rows_per_sec, ns_per_row) = compute_rates(rows, total_elapsed_secs); - - let checksum = black_box(hash_fundamentals_outputs(&built.rows, &snapshots)); - - Ok(FundamentalsBenchReport { - rows, - filings_in, - key_count, - rows_out: built.stats.rows_out, - keys_out: built.stats.keys_out, - snapshots_out: snapshots.len(), - rows_elapsed_ms: rows_elapsed_secs * 1_000.0, - snapshots_elapsed_ms: snaps_elapsed_secs * 1_000.0, - total_elapsed_ms: total_elapsed_secs * 1_000.0, - rows_per_sec, - ns_per_row, - checksum, - stats: built.stats, - }) -} - -#[inline] -fn mix_opt_f64(hash: u64, value: Option) -> u64 { - match value { - None => mix_u64(hash, 0), - Some(v) => mix_u64(mix_u64(hash, 1), v.to_bits()), - } -} - -#[inline] -fn mix_str(mut hash: u64, value: &str) -> u64 { - hash = mix_u64(hash, value.len() as u64); - for byte in value.bytes() { - hash = mix_u64(hash, u64::from(byte)); - } - hash -} - -#[inline] -fn mix_fundamentals_fields(mut hash: u64, fields: &FundamentalsFields) -> u64 { - hash = mix_opt_f64(hash, fields.revenue); - hash = mix_opt_f64(hash, fields.net_income); - hash = mix_opt_f64(hash, fields.operating_cash_flow); - hash = mix_opt_f64(hash, fields.total_assets); - hash = mix_opt_f64(hash, fields.total_equity); - hash = mix_opt_f64(hash, fields.shares_outstanding); - hash -} - -fn hash_fundamentals_outputs( - rows: &[crate::fundamentals::FundamentalsRow], - snapshots: &[crate::fundamentals::FundamentalsSnapshot], -) -> u64 { - let mut hash = 0u64; - for row in rows { - hash = mix_u64(hash, row.key as u64); - hash = mix_u64(hash, row.period_end as u64); - hash = mix_u64(hash, row.fiscal_period as u64); - hash = mix_str(hash, &row.currency); - hash = mix_u64(hash, row.known_at_utc_micros as u64); - hash = mix_str(hash, row.known_at_source); - hash = mix_fundamentals_fields(hash, &row.fields); - } - for snap in snapshots { - hash = mix_u64(hash, snap.key as u64); - hash = mix_u64(hash, snap.effective_known_at_utc_micros as u64); - hash = mix_str(hash, snap.known_at_source); - hash = mix_u64(hash, u64::from(snap.has_estimated_lag)); - hash = mix_u64(hash, snap.periods.len() as u64); - for slot in &snap.periods { - hash = mix_u64(hash, slot.period_end as u64); - hash = mix_u64(hash, slot.fiscal_period as u64); - hash = mix_str(hash, &slot.currency); - hash = mix_u64(hash, slot.known_at_utc_micros as u64); - hash = mix_str(hash, slot.known_at_source); - hash = mix_u64(hash, u64::from(slot.has_estimated_lag)); - hash = mix_fundamentals_fields(hash, &slot.fields); - } - match &snap.ttm { - None => { - hash = mix_u64(hash, 0); - } - Some(ttm) => { - hash = mix_u64(hash, 1); - hash = mix_u64(hash, ttm.ending_period_end as u64); - hash = mix_str(hash, &ttm.currency); - hash = mix_u64(hash, u64::from(ttm.has_estimated_lag)); - hash = mix_opt_f64(hash, ttm.flows.revenue); - hash = mix_opt_f64(hash, ttm.flows.net_income); - hash = mix_opt_f64(hash, ttm.flows.operating_cash_flow); - } - } - } - hash -} - #[cfg(test)] mod tests { use super::*; @@ -13443,194 +12539,4 @@ mod tests { assert_eq!(report.read_back_rows, 0); assert_eq!(report.checksum, 0); } - - #[test] - fn bars_1m_benchmark_small_run_is_deterministic_and_conserves_counts() { - let a = run_bars_1m_benchmark(5_000).unwrap(); - let b = run_bars_1m_benchmark(5_000).unwrap(); - - assert_eq!(a.rows, 5_000); - assert_eq!(a.checksum, b.checksum); - assert_ne!(a.checksum, 0); - assert_eq!(a.rows_out, b.rows_out); - assert_eq!(a.build_stats, b.build_stats); - assert_eq!(a.close_stats, b.close_stats); - assert!(a.rows_out > 0); - assert!(a.build_stats.pre_rows_out > 0); - assert!(a.build_stats.rth_rows_out > 0); - assert!(a.build_stats.post_rows_out > 0); - assert!(a.build_stats.dropped_invalid_ohlc > 0); - assert!(a.build_stats.dropped_inconsistent_ohlc > 0); - assert!(a.build_stats.dropped_invalid_volume > 0); - assert!(a.build_stats.dropped_ts_out_of_range > 0); - assert!(a.close_stats.checked > 0); - - // Conservation invariants - assert_eq!( - a.build_stats.bars_in, - a.build_stats.rows_out - + a.build_stats.dropped_invalid_ohlc - + a.build_stats.dropped_inconsistent_ohlc - + a.build_stats.dropped_invalid_volume - + a.build_stats.dropped_ts_out_of_range - + a.build_stats.duplicate_collapsed - + a.build_stats.duplicate_conflict_dropped - ); - assert_eq!( - a.build_stats.rows_out, - a.build_stats.pre_rows_out + a.build_stats.rth_rows_out + a.build_stats.post_rows_out - ); - assert_eq!( - a.close_stats.checked + a.close_stats.unchecked, - a.close_stats.rth_sessions - ); - assert_eq!( - a.close_stats.within_tolerance + a.close_stats.mismatched, - a.close_stats.checked - ); - } - - #[test] - fn bars_1m_benchmark_zero_rows_handles_cleanly() { - let report = run_bars_1m_benchmark(0).unwrap(); - assert_eq!(report.rows, 0); - assert_eq!(report.rows_out, 0); - assert_eq!(report.keys_out, 0); - assert_eq!(report.daily_rows_in, 0); - assert_eq!(report.mismatch_samples_out, 0); - assert_eq!(report.checksum, 0); - assert_eq!(report.rows_per_sec, 0.0); - assert_eq!(report.ns_per_row, 0.0); - } - - #[test] - fn ilp_bars_1m_benchmark_small_run_is_deterministic_and_conserves_counts() { - let a = run_ilp_bars_1m_benchmark(5_000).unwrap(); - let b = run_ilp_bars_1m_benchmark(5_000).unwrap(); - - assert_eq!(a.rows, 5_000); - assert_eq!(a.rows_encoded, a.rows); - assert_eq!(a.shards, ILP_BARS_1M_BENCH_SHARDS); - assert_eq!(a.bytes, b.bytes); - assert_eq!(a.flushes, b.flushes); - assert_eq!(a.per_shard_rows, b.per_shard_rows); - assert_eq!(a.per_shard_rows.len(), ILP_BARS_1M_BENCH_SHARDS); - assert_eq!(a.per_shard_rows.iter().sum::(), a.rows_encoded); - assert!(a.bytes > 0); - assert!(a.bytes_per_row > 100.0); - assert!(a.flushes >= ILP_BARS_1M_BENCH_SHARDS); - } - - #[test] - fn ilp_bars_1m_benchmark_zero_rows_handles_cleanly() { - let report = run_ilp_bars_1m_benchmark(0).unwrap(); - assert_eq!(report.rows, 0); - assert_eq!(report.rows_encoded, 0); - assert_eq!(report.bytes, 0); - assert_eq!(report.flushes, 0); - assert_eq!(report.bytes_per_row, 0.0); - assert_eq!(report.rows_per_sec, 0.0); - assert_eq!(report.ns_per_row, 0.0); - assert_eq!(report.per_shard_rows, vec![0; ILP_BARS_1M_BENCH_SHARDS]); - } - - #[test] - fn fundamentals_benchmark_small_run_is_deterministic_and_conserves_counts() { - let a = run_fundamentals_benchmark(1_000).unwrap(); - let b = run_fundamentals_benchmark(1_000).unwrap(); - - assert_eq!(a.rows, 1_000); - assert_eq!(a.checksum, b.checksum); - assert_ne!(a.checksum, 0); - assert_eq!(a.rows_out, b.rows_out); - assert_eq!(a.snapshots_out, b.snapshots_out); - assert_eq!(a.stats, b.stats); - assert!(a.rows_out > 0); - assert!(a.snapshots_out > 0); - assert!(a.stats.rows_linked_to_filing > 0); - assert!(a.stats.rows_statutory_lag_estimate > 0); - assert!(a.stats.duplicate_collapsed > 0); - assert_eq!( - a.stats.observations_in, - a.stats.rows_out - + a.stats.observations_dropped_unknown_key - + a.stats.observations_dropped_non_finite - + a.stats.observations_dropped_date_out_of_range - + a.stats.observations_dropped_report_date_not_after_period_end - + a.stats.observations_dropped_unanchored_vintage - + a.stats.observations_dropped_stale_estimate - + a.stats.duplicate_collapsed - + a.stats.duplicate_conflict_dropped - ); - } - - #[test] - fn fundamentals_checksum_distinguishes_none_zero_slots_and_non_revenue_ttm() { - use crate::fundamentals::{ - FundamentalsPeriodSlot, FundamentalsSnapshot, FundamentalsTtm, TtmFlowFields, - }; - - let base_slot = FundamentalsPeriodSlot { - period_end: 19_000, - fiscal_period: FiscalPeriod::Quarterly, - currency: "USD".to_string(), - known_at_utc_micros: 1_000, - known_at_source: crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP, - has_estimated_lag: false, - fields: FundamentalsFields { - revenue: Some(10.0), - net_income: None, - operating_cash_flow: Some(5.0), - total_assets: Some(100.0), - total_equity: Some(50.0), - shares_outstanding: Some(1_000.0), - }, - }; - let base_snap = FundamentalsSnapshot { - key: 1, - effective_known_at_utc_micros: 1_000, - known_at_source: crate::events::KNOWN_AT_SOURCE_FILING_TIMESTAMP, - has_estimated_lag: false, - periods: vec![base_slot], - ttm: Some(FundamentalsTtm { - ending_period_end: 19_000, - currency: "USD".to_string(), - flows: TtmFlowFields { - revenue: Some(40.0), - net_income: None, - operating_cash_flow: Some(20.0), - }, - has_estimated_lag: false, - }), - }; - - let h_base = hash_fundamentals_outputs(&[], &[base_snap.clone()]); - - // None vs Some(0.0) in slot net_income - let mut s_zero = base_snap.clone(); - s_zero.periods[0].fields.net_income = Some(0.0); - assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_zero])); - - // Non-revenue TTM flow change (operating_cash_flow) - let mut s_ttm = base_snap.clone(); - s_ttm.ttm.as_mut().unwrap().flows.operating_cash_flow = Some(21.0); - assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_ttm])); - - // Carried-forward slot provenance change - let mut s_prov = base_snap; - s_prov.periods[0].has_estimated_lag = true; - assert_ne!(h_base, hash_fundamentals_outputs(&[], &[s_prov])); - } - - #[test] - fn fundamentals_benchmark_zero_rows_handles_cleanly() { - let report = run_fundamentals_benchmark(0).unwrap(); - assert_eq!(report.rows, 0); - assert_eq!(report.filings_in, 0); - assert_eq!(report.rows_out, 0); - assert_eq!(report.snapshots_out, 0); - assert_eq!(report.checksum, 0); - assert_eq!(report.rows_per_sec, 0.0); - assert_eq!(report.ns_per_row, 0.0); - } } diff --git a/tools/curate-etl/src/bson_eod_intraday.rs b/tools/curate-etl/src/bson_eod_intraday.rs deleted file mode 100644 index c8b9237b..00000000 --- a/tools/curate-etl/src/bson_eod_intraday.rs +++ /dev/null @@ -1,663 +0,0 @@ -//! Zero-copy raw BSON decoder for MongoDB `eodIntraday1M` documents (`M2.3d`). -//! -//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into -//! borrowed [`RawEodIntradayBar`] views without allocating a `String` or `bson::Document` per row. -//! Callers convert borrowed views into [`crate::bars_1m::EodIntradayBar`] via a caller-supplied -//! key mapper (for example [`crate::provider_mapping::ProviderMappingTable::resolve`] or an -//! interned integer symbol ID), keeping the 3.40B-document path free of per-row `String` -//! allocations. -//! -//! # Empirical Field Contract & Cited Sources -//! -//! Field names and semantics are grounded in the repository's ingestion writer, historical reader, -//! and empirical data contract: -//! - `apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts:565-585` (`fetchIntraday` -//! writes `symbol`, `exchange`, `eodSearchCode`, `datetime`, `timestamp`, `gmtoffset`, `open`, -//! `high`, `low`, `close`, `volume`, `source` into `eodIntraday1M`, keyed by -//! `['timestamp', 'eodSearchCode']`) -//! - `libs/trading-runtime/src/historical-storage.ts:265-298` (`timestamp` is bar-start **UTC -//! Unix seconds**, not a local `datetime` label and not a publication / `known_at` time) -//! - `design/DATA-CONTRACTS.md` §1: `eodIntraday1M` (~3.40B docs) stores retroactively -//! split-adjusted OHLC and volume. This decoder passes those split-adjusted values through -//! untouched; split un-adjustment happens downstream in [`crate::bars_1m::build_bars_1m`]. -//! -//! # Accepted BSON Representations & Daily-Decoder Conventions -//! -//! Where a rule is ambiguous, this module follows [`crate::bson_eod_prices`]: -//! - `eodSearchCode`: BSON UTF-8 `String`, borrowed verbatim (never trimmed). Empty or -//! whitespace-only strings are rejected as [`BsonEodIntradayError::EmptyField`]; non-string -//! values (including BSON `Null`) are rejected as [`BsonEodIntradayError::WrongType`]. -//! - `timestamp`: bar-start UTC Unix seconds in BSON `Int32`, `Int64`, or finite integral `Double` -//! within `0..=i64::MAX / 1_000_000`, converted to UTC microseconds via checked multiplication -//! by `1_000_000`. Non-numeric types (including `Null` and `DateTime`) are rejected as -//! [`BsonEodIntradayError::WrongType`]; negative, fractional, non-finite, or microsecond-overflow -//! values are rejected as [`BsonEodIntradayError::InvalidTimestamp`]. -//! - `open`, `high`, `low`, `close`: BSON `Double`, `Int32`, or `Int64`; must be finite and -//! strictly positive (`> 0.0`). Non-numeric types (including `Null`) are rejected as -//! [`BsonEodIntradayError::WrongType`]; `NaN`, `±inf`, `0.0`, `-0.0`, and `< 0.0` are rejected -//! as [`BsonEodIntradayError::InvalidNumber`]. -//! - `volume`: BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` is -//! normalized to `+0.0`). Non-numeric types (including `Null`) are rejected as -//! [`BsonEodIntradayError::WrongType`]; `NaN`, `±inf`, and `< 0.0` are rejected as -//! [`BsonEodIntradayError::InvalidNumber`]. -//! - Unknown extra fields (`_id`, `symbol`, `exchange`, `datetime`, `gmtoffset`, `source`, nested -//! objects/arrays, etc.) are validated as borrowed `RawBsonRef` views (zero allocation) and -//! otherwise ignored, so malformed payloads (such as invalid UTF-8 in `datetime`) still surface -//! as [`BsonEodIntradayError::CorruptBson`]. -//! - Error precedence: retains the first semantic error while continuing to scan remaining -//! top-level elements so any malformed BSON bytes surface immediately as `CorruptBson`. - -use std::error::Error; -use std::fmt; - -use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement}; -use bson::spec::ElementType; - -use crate::bars_1m::EodIntradayBar; -use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError}; - -const MICROS_PER_SECOND: i64 = 1_000_000; -/// Largest whole Unix-second timestamp that fits in signed `i64` microseconds (`9_223_372_036_854`). -pub(crate) const MAX_TIMESTAMP_SECONDS: i64 = i64::MAX / MICROS_PER_SECOND; - -/// Borrowed zero-copy view of a single decoded `eodIntraday1M` BSON document. -/// -/// Borrows `eod_search_code` directly from the underlying `&RawDocument` byte slice. -/// `open`, `high`, `low`, `close`, and `volume` are passed through as the provider's -/// split-adjusted values so [`crate::bars_1m::build_bars_1m`] can apply split un-adjustment. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct RawEodIntradayBar<'a> { - pub eod_search_code: &'a str, - /// 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, -} - -impl<'a> RawEodIntradayBar<'a> { - /// Converts this borrowed view into an [`EodIntradayBar`] using a caller-supplied key - /// mapper. - /// - /// `map_key` receives `(eod_search_code, ts)` (provider code and UTC bar-start microseconds) - /// so callers can resolve an integer `listing_id` or interned key without allocating a per-row - /// `String`. - #[inline] - pub fn into_eod_intraday_bar(self, map_key: F) -> EodIntradayBar - where - F: FnOnce(&'a str, i64) -> K, - { - EodIntradayBar { - key: map_key(self.eod_search_code, self.ts), - ts: self.ts, - open: self.open, - high: self.high, - low: self.low, - close: self.close, - volume: self.volume, - } - } - - /// Fallible conversion into [`EodIntradayBar`] using a caller-supplied key resolver. - #[inline] - pub fn try_into_eod_intraday_bar(self, map_key: F) -> Option> - where - F: FnOnce(&'a str, i64) -> Option, - { - let key = map_key(self.eod_search_code, self.ts)?; - Some(EodIntradayBar { - key, - ts: self.ts, - open: self.open, - high: self.high, - low: self.low, - close: self.close, - volume: self.volume, - }) - } -} - -/// Typed errors returned while decoding raw `eodIntraday1M` BSON documents or length-prefixed -/// buffers. -/// -/// Every field-level error names the offending BSON field in both its structure and `Display` -/// output; framing errors carry byte offsets; no input path panics. -#[derive(Debug, Clone, PartialEq)] -pub enum BsonEodIntradayError { - /// A required field was absent from the document. - MissingField { field: &'static str }, - /// A required string field was empty or contained only whitespace. - EmptyField { field: &'static str }, - /// A required field had an unexpected BSON element type (including `Null`). - WrongType { - field: &'static str, - actual: ElementType, - }, - /// `timestamp` was negative, non-integral, non-finite, or overflowed `i64` microseconds. - InvalidTimestamp { field: &'static str }, - /// An OHLC field was non-finite or `<= 0.0`, or `volume` was non-finite or `< 0.0`. - InvalidNumber { field: &'static str, value: f64 }, - /// Buffer ended before a complete 4-byte length prefix or declared document body. - TruncatedDocument { - offset: usize, - remaining: usize, - declared_len: Option, - }, - /// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single - /// document slice). - CorruptDocumentLength { offset: usize, declared_len: i32 }, - /// Underlying BSON framing or element bytes were malformed. - CorruptBson { offset: usize, detail: String }, -} - -impl fmt::Display for BsonEodIntradayError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::MissingField { field } => { - write!(f, "eodIntraday1M BSON missing required field '{field}'") - } - Self::EmptyField { field } => { - write!( - f, - "eodIntraday1M BSON field '{field}' must not be empty or blank" - ) - } - Self::WrongType { field, actual } => { - write!( - f, - "eodIntraday1M BSON field '{field}' has unexpected BSON type {actual:?}" - ) - } - Self::InvalidTimestamp { field } => { - write!( - f, - "eodIntraday1M BSON field '{field}' is not a valid non-negative integral Unix-seconds timestamp within i64 microsecond range" - ) - } - Self::InvalidNumber { field, value } => { - if *field == "volume" { - write!( - f, - "eodIntraday1M BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0" - ) - } else { - write!( - f, - "eodIntraday1M BSON field '{field}' has invalid numeric value {value}: must be finite and > 0" - ) - } - } - Self::TruncatedDocument { - offset, - remaining, - declared_len, - } => match declared_len { - Some(len) => write!( - f, - "truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes" - ), - None => write!( - f, - "truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining" - ), - }, - Self::CorruptDocumentLength { - offset, - declared_len, - } => write!( - f, - "corrupt BSON document length {declared_len} at byte offset {offset}" - ), - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - } - } -} - -impl Error for BsonEodIntradayError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonEodIntradayError { - match err { - BsonEodPriceError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonEodIntradayError::TruncatedDocument { - offset, - remaining, - declared_len, - }, - BsonEodPriceError::CorruptDocumentLength { - offset, - declared_len, - } => BsonEodIntradayError::CorruptDocumentLength { - offset, - declared_len, - }, - BsonEodPriceError::CorruptBson { offset, detail } => { - BsonEodIntradayError::CorruptBson { offset, detail } - } - BsonEodPriceError::MissingField { field } => BsonEodIntradayError::MissingField { field }, - BsonEodPriceError::EmptyField { field } => BsonEodIntradayError::EmptyField { field }, - BsonEodPriceError::WrongType { field, actual } => { - BsonEodIntradayError::WrongType { field, actual } - } - BsonEodPriceError::MalformedDate { field } => { - BsonEodIntradayError::InvalidTimestamp { field } - } - BsonEodPriceError::InvalidNumber { field, value } => { - BsonEodIntradayError::InvalidNumber { field, value } - } - } -} - -/// Per-batch decode and rejection accounting for [`decode_eod_intraday_buffer`]. -/// -/// Conservation invariant: `rows_decoded + rejected_total() == docs_seen`. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonEodIntradayDecodeStats { - pub docs_seen: usize, - pub rows_decoded: usize, - pub rejected_missing_field: usize, - pub rejected_empty_field: usize, - pub rejected_wrong_type: usize, - pub rejected_invalid_timestamp: usize, - pub rejected_invalid_number: usize, - pub rejected_corrupt_document: usize, -} - -impl BsonEodIntradayDecodeStats { - /// Total number of rejected documents across all error categories. - #[inline] - pub fn rejected_total(&self) -> usize { - self.rejected_missing_field - + self.rejected_empty_field - + self.rejected_wrong_type - + self.rejected_invalid_timestamp - + self.rejected_invalid_number - + self.rejected_corrupt_document - } - - /// Increments the rejection counter corresponding to `err`. - #[inline] - pub fn record_error(&mut self, err: &BsonEodIntradayError) { - match err { - BsonEodIntradayError::MissingField { .. } => self.rejected_missing_field += 1, - BsonEodIntradayError::EmptyField { .. } => self.rejected_empty_field += 1, - BsonEodIntradayError::WrongType { .. } => self.rejected_wrong_type += 1, - BsonEodIntradayError::InvalidTimestamp { .. } => self.rejected_invalid_timestamp += 1, - BsonEodIntradayError::InvalidNumber { .. } => self.rejected_invalid_number += 1, - BsonEodIntradayError::TruncatedDocument { .. } - | BsonEodIntradayError::CorruptDocumentLength { .. } - | BsonEodIntradayError::CorruptBson { .. } => self.rejected_corrupt_document += 1, - } - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_seen += other.docs_seen; - self.rows_decoded += other.rows_decoded; - self.rejected_missing_field += other.rejected_missing_field; - self.rejected_empty_field += other.rejected_empty_field; - self.rejected_wrong_type += other.rejected_wrong_type; - self.rejected_invalid_timestamp += other.rejected_invalid_timestamp; - self.rejected_invalid_number += other.rejected_invalid_number; - self.rejected_corrupt_document += other.rejected_corrupt_document; - } -} - -impl std::ops::AddAssign for BsonEodIntradayDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -#[inline] -fn decode_element_value<'a>( - field: &'static str, - elem: RawElement<'a>, - offset: usize, -) -> Result, BsonEodIntradayError> { - elem.value().map_err(|err| BsonEodIntradayError::CorruptBson { - offset, - detail: format!("field '{field}': {err}"), - }) -} - -#[inline] -fn decode_timestamp_seconds_to_micros(val: RawBsonRef<'_>) -> Result { - let secs = match val { - RawBsonRef::Int32(v) => { - if v < 0 { - return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }); - } - i64::from(v) - } - RawBsonRef::Int64(v) => { - if v < 0 { - return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }); - } - v - } - RawBsonRef::Double(v) => { - // `MAX_TIMESTAMP_SECONDS` (9_223_372_036_854 < 2^44) is well within `f64`'s exact - // 53-bit integer range, so both the upper bound and the cast are exact. - if !v.is_finite() - || v < 0.0 - || v.fract() != 0.0 - || v > MAX_TIMESTAMP_SECONDS as f64 - { - return Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }); - } - v as i64 - } - other => { - return Err(BsonEodIntradayError::WrongType { - field: "timestamp", - actual: other.element_type(), - }); - } - }; - - secs.checked_mul(MICROS_PER_SECOND) - .ok_or(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }) -} - -#[inline] -fn decode_positive_number( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => { - if !v.is_finite() || v <= 0.0 { - return Err(BsonEodIntradayError::InvalidNumber { field, value: v }); - } - Ok(v) - } - RawBsonRef::Int32(v) => { - if v <= 0 { - return Err(BsonEodIntradayError::InvalidNumber { - field, - value: f64::from(v), - }); - } - Ok(f64::from(v)) - } - RawBsonRef::Int64(v) => { - if v <= 0 { - return Err(BsonEodIntradayError::InvalidNumber { - field, - value: v as f64, - }); - } - Ok(v as f64) - } - other => Err(BsonEodIntradayError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_non_negative_number( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => { - if !v.is_finite() || v < 0.0 { - return Err(BsonEodIntradayError::InvalidNumber { field, value: v }); - } - if v == 0.0 { - Ok(0.0) - } else { - Ok(v) - } - } - RawBsonRef::Int32(v) => { - if v < 0 { - return Err(BsonEodIntradayError::InvalidNumber { - field, - value: f64::from(v), - }); - } - Ok(f64::from(v)) - } - RawBsonRef::Int64(v) => { - if v < 0 { - return Err(BsonEodIntradayError::InvalidNumber { - field, - value: v as f64, - }); - } - Ok(v as f64) - } - other => Err(BsonEodIntradayError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -fn decode_eod_intraday_doc_at<'a>( - doc: &'a RawDocument, - offset: usize, -) -> Result, BsonEodIntradayError> { - let mut eod_search_code: Option<&'a str> = None; - let mut ts: Option = None; - let mut open: Option = None; - let mut high: Option = None; - let mut low: Option = None; - let mut close: Option = None; - let mut volume: Option = None; - let mut first_semantic_err: Option = None; - - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonEodIntradayError::CorruptBson { - offset, - detail: err.to_string(), - })?; - let key = elem.key(); - - if key == cstr!("eodSearchCode") { - match decode_element_value("eodSearchCode", elem, offset)? { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonEodIntradayError::EmptyField { - field: "eodSearchCode", - }); - } - } else { - eod_search_code = Some(s); - } - } - other => { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonEodIntradayError::WrongType { - field: "eodSearchCode", - actual: other.element_type(), - }); - } - } - } - } else if key == cstr!("timestamp") { - let val = decode_element_value("timestamp", elem, offset)?; - match decode_timestamp_seconds_to_micros(val) { - Ok(micros) => ts = Some(micros), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("open") { - let val = decode_element_value("open", elem, offset)?; - match decode_positive_number("open", val) { - Ok(v) => open = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("high") { - let val = decode_element_value("high", elem, offset)?; - match decode_positive_number("high", val) { - Ok(v) => high = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("low") { - let val = decode_element_value("low", elem, offset)?; - match decode_positive_number("low", val) { - Ok(v) => low = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("close") { - let val = decode_element_value("close", elem, offset)?; - match decode_positive_number("close", val) { - Ok(v) => close = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("volume") { - let val = decode_element_value("volume", elem, offset)?; - match decode_non_negative_number("volume", val) { - Ok(v) => volume = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else { - // Validate skipped top-level payloads via borrowed `RawBsonRef` views (zero - // allocation) so malformed bytes (e.g. invalid UTF-8 in `datetime`) still reject the - // document as `CorruptBson` at its frame offset. - elem.value().map_err(|err| BsonEodIntradayError::CorruptBson { - offset, - detail: format!("field '{}': {err}", key.as_str()), - })?; - } - } - - if let Some(err) = first_semantic_err { - return Err(err); - } - - let Some(eod_search_code) = eod_search_code else { - return Err(BsonEodIntradayError::MissingField { - field: "eodSearchCode", - }); - }; - let Some(ts) = ts else { - return Err(BsonEodIntradayError::MissingField { field: "timestamp" }); - }; - let Some(open) = open else { - return Err(BsonEodIntradayError::MissingField { field: "open" }); - }; - let Some(high) = high else { - return Err(BsonEodIntradayError::MissingField { field: "high" }); - }; - let Some(low) = low else { - return Err(BsonEodIntradayError::MissingField { field: "low" }); - }; - let Some(close) = close else { - return Err(BsonEodIntradayError::MissingField { field: "close" }); - }; - let Some(volume) = volume else { - return Err(BsonEodIntradayError::MissingField { field: "volume" }); - }; - - Ok(RawEodIntradayBar { - eod_search_code, - ts, - open, - high, - low, - close, - volume, - }) -} - -/// Decodes a single `&RawDocument` representing an `eodIntraday1M` MongoDB document in one forward -/// pass without allocating a `String` or owned `bson::Document`. -#[inline] -pub fn decode_eod_intraday_doc<'a>( - doc: &'a RawDocument, -) -> Result, BsonEodIntradayError> { - decode_eod_intraday_doc_at(doc, 0) -} - -/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed -/// [`RawEodIntradayBar`]. -pub fn decode_eod_intraday_bytes<'a>( - bytes: &'a [u8], -) -> Result, BsonEodIntradayError> { - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_eod_intraday_doc_at(doc, 0) -} - -/// Streams a concatenated length-prefixed BSON buffer through [`decode_eod_intraday_doc`], -/// invoking `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected -/// document without aborting the stream on per-document errors. -/// -/// Always maintains `stats.rows_decoded + stats.rejected_total() == stats.docs_seen`. -pub fn decode_eod_intraday_buffer<'a, F, E>( - buf: &'a [u8], - mut on_bar: F, - mut on_error: E, -) -> BsonEodIntradayDecodeStats -where - F: FnMut(RawEodIntradayBar<'a>), - E: FnMut(usize, BsonEodIntradayError), -{ - let mut stats = BsonEodIntradayDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - - while let Some(item) = iter.next_with_offset() { - stats.docs_seen += 1; - match item { - Ok((doc_offset, doc)) => match decode_eod_intraday_doc_at(doc, doc_offset) { - Ok(bar) => { - stats.rows_decoded += 1; - on_bar(bar); - } - Err(err) => { - stats.record_error(&err); - on_error(doc_offset, err); - } - }, - Err((doc_offset, err)) => { - let mapped = map_framing_error(err); - stats.record_error(&mapped); - on_error(doc_offset, mapped); - } - } - } - - stats -} - -#[cfg(test)] -#[path = "bson_eod_intraday_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_eod_intraday_tests.rs b/tools/curate-etl/src/bson_eod_intraday_tests.rs deleted file mode 100644 index 6374d2b8..00000000 --- a/tools/curate-etl/src/bson_eod_intraday_tests.rs +++ /dev/null @@ -1,896 +0,0 @@ -use bson::oid::ObjectId; -use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; -use bson::spec::ElementType; -use bson::DateTime; - -use super::*; -use crate::bars_1m::{build_bars_1m, IntradaySession, BARS_1M_SOURCE_EOD}; -use crate::split::{ymd_to_epoch_days, SplitEvent, SplitTable}; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).unwrap() -} - -fn make_valid_doc( - code: &str, - timestamp_sec: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), timestamp_sec); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc -} - -fn make_doc_with_timestamp(timestamp: RawBsonRef<'_>) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("timestamp"), timestamp); - doc.append(cstr!("open"), 120.15_f64); - doc.append(cstr!("high"), 120.42_f64); - doc.append(cstr!("low"), 120.05_f64); - doc.append(cstr!("close"), 120.38_f64); - doc.append(cstr!("volume"), 842_500.0_f64); - doc -} - -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}" - ); -} - -#[test] -fn decodes_nvda_fixture_across_int32_int64_double_timestamps_and_ignores_metadata() { - const TS_SEC: i32 = 1_717_767_000; - const EXPECTED_TS_MICROS: i64 = 1_717_767_000_000_000; - - let mut nested = RawDocumentBuf::new(); - nested.append(cstr!("provider"), "eodhd"); - nested.append(cstr!("interval"), "1m"); - - let mut tags = RawArrayBuf::new(); - tags.push("us"); - tags.push("intraday"); - - let mut doc_i32 = RawDocumentBuf::new(); - doc_i32.append( - cstr!("_id"), - ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), - ); - doc_i32.append(cstr!("symbol"), "NVDA"); - doc_i32.append(cstr!("exchange"), "US"); - doc_i32.append(cstr!("eodSearchCode"), "NVDA.US"); - doc_i32.append(cstr!("datetime"), "2024-06-07 13:30:00"); - doc_i32.append(cstr!("timestamp"), TS_SEC); - doc_i32.append(cstr!("gmtoffset"), 0_i32); - doc_i32.append(cstr!("open"), 119.77_f64); - doc_i32.append(cstr!("high"), 121.692_f64); - doc_i32.append(cstr!("low"), 118.022_f64); - doc_i32.append(cstr!("close"), 120.888_f64); - doc_i32.append(cstr!("volume"), 412_390.0_f64); - doc_i32.append(cstr!("source"), "eod"); - doc_i32.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); - doc_i32.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); - - let bar_i32 = decode_eod_intraday_doc(&doc_i32).unwrap(); - assert_eq!(bar_i32.eod_search_code, "NVDA.US"); - assert_eq!(bar_i32.ts, EXPECTED_TS_MICROS); - assert_eq!(bar_i32.open.to_bits(), 119.77_f64.to_bits()); - assert_eq!(bar_i32.high.to_bits(), 121.692_f64.to_bits()); - assert_eq!(bar_i32.low.to_bits(), 118.022_f64.to_bits()); - assert_eq!(bar_i32.close.to_bits(), 120.888_f64.to_bits()); - assert_eq!(bar_i32.volume.to_bits(), 412_390.0_f64.to_bits()); - - // decode_eod_intraday_bytes matches decode_eod_intraday_doc bit-for-bit. - let from_bytes = decode_eod_intraday_bytes(doc_i32.as_bytes()).unwrap(); - assert_eq!(from_bytes, bar_i32); - - // Same document with timestamp as Int64 and as integral Double decodes identically. - let mut doc_i64 = RawDocumentBuf::new(); - doc_i64.append(cstr!("eodSearchCode"), "NVDA.US"); - doc_i64.append(cstr!("timestamp"), i64::from(TS_SEC)); - doc_i64.append(cstr!("open"), 119.77_f64); - doc_i64.append(cstr!("high"), 121.692_f64); - doc_i64.append(cstr!("low"), 118.022_f64); - doc_i64.append(cstr!("close"), 120.888_f64); - doc_i64.append(cstr!("volume"), 412_390.0_f64); - - let mut doc_f64 = RawDocumentBuf::new(); - doc_f64.append(cstr!("eodSearchCode"), "NVDA.US"); - doc_f64.append(cstr!("timestamp"), f64::from(TS_SEC)); - doc_f64.append(cstr!("open"), 119.77_f64); - doc_f64.append(cstr!("high"), 121.692_f64); - doc_f64.append(cstr!("low"), 118.022_f64); - doc_f64.append(cstr!("close"), 120.888_f64); - doc_f64.append(cstr!("volume"), 412_390.0_f64); - - let bar_i64 = decode_eod_intraday_doc(&doc_i64).unwrap(); - let bar_f64 = decode_eod_intraday_doc(&doc_f64).unwrap(); - assert_eq!(bar_i64, bar_i32); - assert_eq!(bar_f64, bar_i32); - - // Verify into_eod_intraday_bar and try_into_eod_intraday_bar pass exact (code, ts). - let mut seen_into: Option<(&str, i64)> = None; - let mapped = bar_i32.into_eod_intraday_bar(|code, ts| { - seen_into = Some((code, ts)); - 42_u64 - }); - assert_eq!(seen_into, Some(("NVDA.US", EXPECTED_TS_MICROS))); - assert_eq!(mapped.key, 42_u64); - assert_eq!(mapped.ts, EXPECTED_TS_MICROS); - assert_eq!(mapped.close.to_bits(), 120.888_f64.to_bits()); - - let mut seen_try_some: Option<(&str, i64)> = None; - let try_some = bar_i32.try_into_eod_intraday_bar(|code, ts| { - seen_try_some = Some((code, ts)); - Some(99_u64) - }); - assert_eq!(seen_try_some, Some(("NVDA.US", EXPECTED_TS_MICROS))); - assert_eq!(try_some.unwrap().key, 99_u64); - - let try_none: Option> = bar_i32.try_into_eod_intraday_bar(|code, ts| { - assert_eq!(code, "NVDA.US"); - assert_eq!(ts, EXPECTED_TS_MICROS); - None - }); - assert!(try_none.is_none()); -} - -#[test] -fn borrows_eod_search_code_zero_copy_from_input_buffer() { - let doc = make_valid_doc("NVDA.US", 1_717_767_000, 120.0, 121.0, 119.5, 120.5, 1000.0); - let bytes = doc.as_bytes(); - let buf_start = bytes.as_ptr() as usize; - let buf_end = buf_start + bytes.len(); - - let bar = decode_eod_intraday_bytes(bytes).unwrap(); - let code_start = bar.eod_search_code.as_ptr() as usize; - let code_end = code_start + bar.eod_search_code.len(); - assert!( - code_start >= buf_start && code_end <= buf_end, - "expected eod_search_code pointer {code_start:#x}..{code_end:#x} inside input buffer {buf_start:#x}..{buf_end:#x}" - ); - assert_eq!(bar.eod_search_code, "NVDA.US"); -} - -#[test] -fn accepts_mixed_numeric_types_zero_volume_and_timestamp_boundaries() { - let mut mixed = RawDocumentBuf::new(); - mixed.append(cstr!("eodSearchCode"), "SHOP.TO"); - mixed.append(cstr!("timestamp"), 0_i32); - mixed.append(cstr!("open"), 100_i32); - mixed.append(cstr!("high"), 105_i64); - mixed.append(cstr!("low"), 99.5_f64); - mixed.append(cstr!("close"), 104_i32); - mixed.append(cstr!("volume"), 5_000_000_000_i64); - - let bar = decode_eod_intraday_doc(&mixed).unwrap(); - assert_eq!(bar.eod_search_code, "SHOP.TO"); - assert_eq!(bar.ts, 0); - assert_eq!(bar.open.to_bits(), 100.0_f64.to_bits()); - assert_eq!(bar.high.to_bits(), 105.0_f64.to_bits()); - assert_eq!(bar.low.to_bits(), 99.5_f64.to_bits()); - assert_eq!(bar.close.to_bits(), 104.0_f64.to_bits()); - assert_eq!(bar.volume.to_bits(), 5_000_000_000.0_f64.to_bits()); - - // Epoch zero in Int32, Int64, Double (+0.0 and -0.0). - for zero_ts in [ - RawBsonRef::Int32(0), - RawBsonRef::Int64(0), - RawBsonRef::Double(0.0), - RawBsonRef::Double(-0.0), - ] { - let doc = make_doc_with_timestamp(zero_ts); - let decoded = decode_eod_intraday_doc(&doc).unwrap(); - assert_eq!(decoded.ts, 0); - } - - // Largest accepted whole second in Int64 and Double. - let expected_max_micros = MAX_TIMESTAMP_SECONDS * 1_000_000; - for max_ts in [ - RawBsonRef::Int64(MAX_TIMESTAMP_SECONDS), - RawBsonRef::Double(MAX_TIMESTAMP_SECONDS as f64), - ] { - let doc = make_doc_with_timestamp(max_ts); - let decoded = decode_eod_intraday_doc(&doc).unwrap(); - assert_eq!(decoded.ts, expected_max_micros); - } - - // Zero volume in Double (+0.0, -0.0), Int32 (0), Int64 (0) normalizes to +0.0. - for zero_vol in [ - RawBsonRef::Double(0.0), - RawBsonRef::Double(-0.0), - RawBsonRef::Int32(0), - RawBsonRef::Int64(0), - ] { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("timestamp"), 1_717_767_000_i64); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.5_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), zero_vol); - - let decoded = decode_eod_intraday_doc(&doc).unwrap(); - assert_eq!(decoded.volume.to_bits(), 0.0_f64.to_bits()); - } -} - -#[test] -fn rejects_invalid_eod_search_code_variants_with_matching_stats() { - // Missing eodSearchCode - let mut missing = RawDocumentBuf::new(); - missing.append(cstr!("timestamp"), 1_717_767_000_i64); - missing.append(cstr!("open"), 10.0_f64); - missing.append(cstr!("high"), 11.0_f64); - missing.append(cstr!("low"), 9.0_f64); - missing.append(cstr!("close"), 10.5_f64); - missing.append(cstr!("volume"), 100.0_f64); - let err = decode_eod_intraday_doc(&missing).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::MissingField { - field: "eodSearchCode" - } - ); - let mut stats = BsonEodIntradayDecodeStats::default(); - stats.record_error(&err); - assert_eq!(stats.rejected_missing_field, 1); - assert_eq!(stats.rejected_total(), 1); - - // Empty and whitespace-only keys - for blank in ["", " ", "\t\n\r "] { - let doc = make_valid_doc(blank, 1_717_767_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::EmptyField { - field: "eodSearchCode" - } - ); - let mut s = BsonEodIntradayDecodeStats::default(); - s.record_error(&err); - assert_eq!(s.rejected_empty_field, 1); - assert_eq!(s.rejected_total(), 1); - } - - // Wrong BSON types for eodSearchCode - let wrong_types: [(RawBsonRef<'_>, ElementType); 3] = [ - (RawBsonRef::Null, ElementType::Null), - (RawBsonRef::Int32(123), ElementType::Int32), - (RawBsonRef::Boolean(true), ElementType::Boolean), - ]; - for (val, expected_type) in wrong_types { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), val); - doc.append(cstr!("timestamp"), 1_717_767_000_i64); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), 100.0_f64); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::WrongType { - field: "eodSearchCode", - actual: expected_type, - } - ); - let mut s = BsonEodIntradayDecodeStats::default(); - s.record_error(&err); - assert_eq!(s.rejected_wrong_type, 1); - assert_eq!(s.rejected_total(), 1); - } -} - -#[test] -fn rejects_invalid_timestamp_variants_with_matching_stats() { - // Missing timestamp - let mut missing = RawDocumentBuf::new(); - missing.append(cstr!("eodSearchCode"), "NVDA.US"); - missing.append(cstr!("open"), 10.0_f64); - missing.append(cstr!("high"), 11.0_f64); - missing.append(cstr!("low"), 9.0_f64); - missing.append(cstr!("close"), 10.5_f64); - missing.append(cstr!("volume"), 100.0_f64); - let err = decode_eod_intraday_doc(&missing).unwrap_err(); - assert_eq!(err, BsonEodIntradayError::MissingField { field: "timestamp" }); - let mut stats = BsonEodIntradayDecodeStats::default(); - stats.record_error(&err); - assert_eq!(stats.rejected_missing_field, 1); - assert_eq!(stats.rejected_total(), 1); - - // Wrong BSON types for timestamp - let wrong_types: [(RawBsonRef<'_>, ElementType); 4] = [ - (RawBsonRef::Null, ElementType::Null), - (RawBsonRef::String("1717767000"), ElementType::String), - ( - RawBsonRef::DateTime(DateTime::from_millis(1_717_767_000_000)), - ElementType::DateTime, - ), - (RawBsonRef::Boolean(false), ElementType::Boolean), - ]; - for (val, expected_type) in wrong_types { - let doc = make_doc_with_timestamp(val); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::WrongType { - field: "timestamp", - actual: expected_type, - } - ); - let mut s = BsonEodIntradayDecodeStats::default(); - s.record_error(&err); - assert_eq!(s.rejected_wrong_type, 1); - assert_eq!(s.rejected_total(), 1); - } - - // Invalid numeric timestamps: fractional, NaN, inf, -inf, negative, overflowing - let invalid_timestamps: [RawBsonRef<'_>; 11] = [ - RawBsonRef::Double(1_717_767_000.5), - RawBsonRef::Double(0.25), - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Int32(-1), - RawBsonRef::Int64(-1), - RawBsonRef::Double(-1.0), - RawBsonRef::Int64(MAX_TIMESTAMP_SECONDS + 1), - RawBsonRef::Int64(i64::MAX), - RawBsonRef::Double((MAX_TIMESTAMP_SECONDS + 1) as f64), - ]; - for bad_ts in invalid_timestamps { - let doc = make_doc_with_timestamp(bad_ts); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::InvalidTimestamp { field: "timestamp" } - ); - let mut s = BsonEodIntradayDecodeStats::default(); - s.record_error(&err); - assert_eq!(s.rejected_invalid_timestamp, 1); - assert_eq!(s.rejected_total(), 1); - } -} - -#[test] -fn rejects_invalid_ohlc_and_volume_variants_with_matching_stats() { - let ohlc_fields = ["open", "high", "low", "close"]; - - for target in ohlc_fields { - // Missing field - let mut missing = RawDocumentBuf::new(); - missing.append(cstr!("eodSearchCode"), "NVDA.US"); - missing.append(cstr!("timestamp"), 1_717_767_000_i64); - for (f, key) in [ - ("open", cstr!("open")), - ("high", cstr!("high")), - ("low", cstr!("low")), - ("close", cstr!("close")), - ("volume", cstr!("volume")), - ] { - if f != target { - missing.append(key, 10.0_f64); - } - } - let err = decode_eod_intraday_doc(&missing).unwrap_err(); - assert_eq!(err, BsonEodIntradayError::MissingField { field: target }); - let mut s = BsonEodIntradayDecodeStats::default(); - s.record_error(&err); - assert_eq!(s.rejected_missing_field, 1); - assert_eq!(s.rejected_total(), 1); - - let build_with_field = |val: RawBsonRef<'_>| { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("timestamp"), 1_717_767_000_i64); - for (name, key) in [ - ("open", cstr!("open")), - ("high", cstr!("high")), - ("low", cstr!("low")), - ("close", cstr!("close")), - ("volume", cstr!("volume")), - ] { - if name == target { - doc.append(key, val); - } else { - doc.append(key, 10.0_f64); - } - } - doc - }; - - // Null and wrong types -> WrongType - for (val, expected_type) in [ - (RawBsonRef::Null, ElementType::Null), - (RawBsonRef::String("10.0"), ElementType::String), - (RawBsonRef::Boolean(true), ElementType::Boolean), - ] { - let doc = build_with_field(val); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::WrongType { - field: target, - actual: expected_type, - } - ); - let mut st = BsonEodIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_wrong_type, 1); - assert_eq!(st.rejected_total(), 1); - } - - // Non-finite, zero, and negative -> InvalidNumber - for bad_num in [ - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Double(0.0), - RawBsonRef::Double(-0.0), - RawBsonRef::Double(-1.25), - RawBsonRef::Int32(0), - RawBsonRef::Int32(-5), - RawBsonRef::Int64(0), - RawBsonRef::Int64(-5), - ] { - let doc = build_with_field(bad_num); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - match &err { - BsonEodIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, target), - other => panic!("expected InvalidNumber for {target}, got {other:?}"), - } - let mut st = BsonEodIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_invalid_number, 1); - assert_eq!(st.rejected_total(), 1); - } - } - - // Volume: missing, Null/wrong-type, negative/NaN/inf - let mut missing_vol = RawDocumentBuf::new(); - missing_vol.append(cstr!("eodSearchCode"), "NVDA.US"); - missing_vol.append(cstr!("timestamp"), 1_717_767_000_i64); - missing_vol.append(cstr!("open"), 10.0_f64); - missing_vol.append(cstr!("high"), 11.0_f64); - missing_vol.append(cstr!("low"), 9.0_f64); - missing_vol.append(cstr!("close"), 10.5_f64); - let err = decode_eod_intraday_doc(&missing_vol).unwrap_err(); - assert_eq!(err, BsonEodIntradayError::MissingField { field: "volume" }); - - let build_with_vol = |val: RawBsonRef<'_>| { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("timestamp"), 1_717_767_000_i64); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), val); - doc - }; - - for (val, expected_type) in [ - (RawBsonRef::Null, ElementType::Null), - (RawBsonRef::String("100"), ElementType::String), - (RawBsonRef::Boolean(false), ElementType::Boolean), - ] { - let doc = build_with_vol(val); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonEodIntradayError::WrongType { - field: "volume", - actual: expected_type, - } - ); - let mut st = BsonEodIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_wrong_type, 1); - assert_eq!(st.rejected_total(), 1); - } - - for bad_vol in [ - RawBsonRef::Double(-0.01), - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Int32(-1), - RawBsonRef::Int64(-1), - ] { - let doc = build_with_vol(bad_vol); - let err = decode_eod_intraday_doc(&doc).unwrap_err(); - match &err { - BsonEodIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, "volume"), - other => panic!("expected InvalidNumber for volume, got {other:?}"), - } - let mut st = BsonEodIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_invalid_number, 1); - assert_eq!(st.rejected_total(), 1); - } -} - -#[test] -fn rejects_truncated_and_corrupt_single_doc_bytes_without_panicking() { - // Truncated header (< 4 bytes) - assert_eq!( - decode_eod_intraday_bytes(&[0x10, 0x00]), - Err(BsonEodIntradayError::TruncatedDocument { - offset: 0, - remaining: 2, - declared_len: None, - }) - ); - - // Declared length < 5 - assert_eq!( - decode_eod_intraday_bytes(&[4, 0, 0, 0]), - Err(BsonEodIntradayError::CorruptDocumentLength { - offset: 0, - declared_len: 4, - }) - ); - - // Truncated body (declared_len > remaining) - let valid = make_valid_doc("NVDA.US", 1_717_767_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let truncated = &valid.as_bytes()[..valid.as_bytes().len() - 3]; - assert_eq!( - decode_eod_intraday_bytes(truncated), - Err(BsonEodIntradayError::TruncatedDocument { - offset: 0, - remaining: truncated.len(), - declared_len: Some(valid.as_bytes().len() as i32), - }) - ); - - // Trailing extra bytes on single-doc decode -> CorruptDocumentLength - let mut with_trailing = valid.as_bytes().to_vec(); - with_trailing.push(0x00); - assert_eq!( - decode_eod_intraday_bytes(&with_trailing), - Err(BsonEodIntradayError::CorruptDocumentLength { - offset: 0, - declared_len: valid.as_bytes().len() as i32, - }) - ); - - // Malformed BSON (missing trailing null terminator) - let mut bad_term = valid.as_bytes().to_vec(); - *bad_term.last_mut().unwrap() = 0xFF; - match decode_eod_intraday_bytes(&bad_term) { - Err(BsonEodIntradayError::CorruptBson { offset: 0, .. }) => {} - other => panic!("expected CorruptBson, got {other:?}"), - } -} - -#[test] -fn rejects_corrupt_utf8_in_skipped_top_level_field_and_recovers_to_next_frame() { - // Build a valid document with a skipped `datetime` string field, then corrupt one payload byte - // inside `datetime` to invalid UTF-8 (0xFF) while leaving all lengths and NUL terminators - // intact. - const DATETIME_MARKER: &[u8] = b"2024-06-07 13:30:00"; - let mut doc_with_datetime = make_valid_doc( - "NVDA.US", - 1_717_767_000, - 120.50, - 121.25, - 120.10, - 120.90, - 1_000.0, - ); - doc_with_datetime.append(cstr!("datetime"), "2024-06-07 13:30:00"); - - let mut corrupt_bytes = doc_with_datetime.as_bytes().to_vec(); - let marker_pos = corrupt_bytes - .windows(DATETIME_MARKER.len()) - .position(|w| w == DATETIME_MARKER) - .expect("datetime payload must exist in serialized BSON"); - corrupt_bytes[marker_pos + 4] = 0xFF; - - // Single-document decode must reject as CorruptBson at offset 0. - match decode_eod_intraday_bytes(&corrupt_bytes) { - Err(BsonEodIntradayError::CorruptBson { offset: 0, detail }) => { - assert!( - detail.contains("datetime"), - "expected offending field name in detail, got: {detail}" - ); - } - other => panic!("expected CorruptBson at offset 0, got {other:?}"), - } - - // Buffer decode with a preceding valid frame and a following valid frame: rejects the - // damaged frame at its exact byte offset, increments `rejected_corrupt_document`, and - // recovers cleanly to decode the next frame. - let valid_before = - make_valid_doc("AAPL.US", 1_717_766_940, 195.0, 196.0, 194.5, 195.5, 500.0); - let valid_after = - make_valid_doc("MSFT.US", 1_717_767_060, 420.0, 421.0, 419.5, 420.5, 750.0); - - let mut buf = Vec::new(); - buf.extend_from_slice(valid_before.as_bytes()); - let corrupt_offset = buf.len(); - buf.extend_from_slice(&corrupt_bytes); - buf.extend_from_slice(valid_after.as_bytes()); - - let mut rows = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_eod_intraday_buffer( - &buf, - |bar| rows.push((bar.eod_search_code.to_owned(), bar.ts, bar.close)), - |off, err| errors.push((off, err)), - ); - - assert_eq!( - rows, - vec![ - ("AAPL.US".to_owned(), 1_717_766_940_000_000, 195.5), - ("MSFT.US".to_owned(), 1_717_767_060_000_000, 420.5), - ] - ); - assert_eq!(stats.docs_seen, 3); - assert_eq!(stats.rows_decoded, 2); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(stats.rejected_total(), 1); - assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); - assert_eq!(errors.len(), 1); - assert_eq!(errors[0].0, corrupt_offset); - assert!(matches!( - &errors[0].1, - BsonEodIntradayError::CorruptBson { offset, detail } - if *offset == corrupt_offset && detail.contains("datetime") - )); -} - -#[test] -fn decodes_mixed_buffer_preserving_order_recovering_past_corrupt_frame_and_merging_stats() { - let valid1 = make_valid_doc("NVDA.US", 1_717_767_000, 120.0, 121.0, 119.5, 120.5, 1000.0); - let empty_key = make_valid_doc(" ", 1_717_767_060, 120.5, 121.0, 120.0, 120.8, 500.0); - let bad_ts = make_doc_with_timestamp(RawBsonRef::Double(1_717_767_120.5)); - let bad_price = make_valid_doc("NVDA.US", 1_717_767_180, 0.0, 121.0, 119.0, 120.0, 200.0); - - let mut wrong_type = RawDocumentBuf::new(); - wrong_type.append(cstr!("eodSearchCode"), "NVDA.US"); - wrong_type.append(cstr!("timestamp"), 1_717_767_240_i64); - wrong_type.append(cstr!("open"), RawBsonRef::Null); - wrong_type.append(cstr!("high"), 121.0_f64); - wrong_type.append(cstr!("low"), 119.0_f64); - wrong_type.append(cstr!("close"), 120.0_f64); - wrong_type.append(cstr!("volume"), 200.0_f64); - - let mut missing_field = RawDocumentBuf::new(); - missing_field.append(cstr!("eodSearchCode"), "NVDA.US"); - missing_field.append(cstr!("timestamp"), 1_717_767_300_i64); - missing_field.append(cstr!("open"), 120.0_f64); - missing_field.append(cstr!("high"), 121.0_f64); - missing_field.append(cstr!("low"), 119.0_f64); - missing_field.append(cstr!("close"), 120.0_f64); - - // Valid length-framed doc whose trailing terminator is corrupt -> CorruptBson, but buffer - // iteration recovers and decodes valid2 after it. - let mut corrupt_framed = valid1.as_bytes().to_vec(); - *corrupt_framed.last_mut().unwrap() = 0xAA; - - let valid2 = make_valid_doc("AAPL.US", 1_717_767_360, 195.0, 196.0, 194.5, 195.5, 0.0); - - let mut buf = Vec::new(); - buf.extend_from_slice(valid1.as_bytes()); - let off_empty = buf.len(); - buf.extend_from_slice(empty_key.as_bytes()); - let off_bad_ts = buf.len(); - buf.extend_from_slice(bad_ts.as_bytes()); - let off_bad_price = buf.len(); - buf.extend_from_slice(bad_price.as_bytes()); - let off_wrong_type = buf.len(); - buf.extend_from_slice(wrong_type.as_bytes()); - let off_missing = buf.len(); - buf.extend_from_slice(missing_field.as_bytes()); - let off_corrupt = buf.len(); - buf.extend_from_slice(&corrupt_framed); - buf.extend_from_slice(valid2.as_bytes()); - - let mut rows = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_eod_intraday_buffer( - &buf, - |bar| rows.push((bar.eod_search_code.to_owned(), bar.ts, bar.close, bar.volume)), - |offset, err| errors.push((offset, err)), - ); - - assert_eq!(rows.len(), 2); - assert_eq!(rows[0], ("NVDA.US".to_owned(), 1_717_767_000_000_000, 120.5, 1000.0)); - assert_eq!(rows[1], ("AAPL.US".to_owned(), 1_717_767_360_000_000, 195.5, 0.0)); - - assert_eq!(stats.docs_seen, 8); - assert_eq!(stats.rows_decoded, 2); - assert_eq!(stats.rejected_empty_field, 1); - assert_eq!(stats.rejected_invalid_timestamp, 1); - assert_eq!(stats.rejected_invalid_number, 1); - assert_eq!(stats.rejected_wrong_type, 1); - assert_eq!(stats.rejected_missing_field, 1); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(stats.rejected_total(), 6); - assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); - - assert_eq!(errors.len(), 6); - assert_eq!(errors[0].0, off_empty); - assert_eq!(errors[1].0, off_bad_ts); - assert_eq!(errors[2].0, off_bad_price); - assert_eq!(errors[3].0, off_wrong_type); - assert_eq!(errors[4].0, off_missing); - assert_eq!(errors[5].0, off_corrupt); - assert!(matches!( - errors[5].1, - BsonEodIntradayError::CorruptBson { offset, .. } if offset == off_corrupt - )); - - // Verify BsonEodIntradayDecodeStats::merge sums every counter. - let mut merged = BsonEodIntradayDecodeStats { - docs_seen: 10, - rows_decoded: 4, - rejected_missing_field: 1, - rejected_empty_field: 1, - rejected_wrong_type: 1, - rejected_invalid_timestamp: 1, - rejected_invalid_number: 1, - rejected_corrupt_document: 1, - }; - merged.merge(&stats); - assert_eq!( - merged, - BsonEodIntradayDecodeStats { - docs_seen: 18, - rows_decoded: 6, - rejected_missing_field: 2, - rejected_empty_field: 2, - rejected_wrong_type: 2, - rejected_invalid_timestamp: 2, - rejected_invalid_number: 2, - rejected_corrupt_document: 2, - } - ); - assert_eq!(merged.docs_seen, merged.rows_decoded + merged.rejected_total()); - - // Truncated tail stops cleanly and still maintains conservation invariant. - let mut with_trunc = buf.clone(); - let trunc_off = with_trunc.len(); - with_trunc.extend_from_slice(&valid2.as_bytes()[..10]); - let mut trunc_errs = Vec::new(); - let trunc_stats = decode_eod_intraday_buffer( - &with_trunc, - |_| {}, - |off, err| trunc_errs.push((off, err)), - ); - assert_eq!(trunc_stats.docs_seen, 9); - assert_eq!(trunc_stats.rows_decoded, 2); - assert_eq!(trunc_stats.rejected_corrupt_document, 2); - assert_eq!( - trunc_stats.docs_seen, - trunc_stats.rows_decoded + trunc_stats.rejected_total() - ); - assert_eq!(trunc_errs.last().unwrap().0, trunc_off); - assert!(matches!( - trunc_errs.last().unwrap().1, - BsonEodIntradayError::TruncatedDocument { offset, remaining: 10, declared_len: Some(_) } - if offset == trunc_off - )); -} - -#[test] -fn decoded_nvda_bars_feed_build_bars_1m_end_to_end_with_10_for_1_split() { - // NVDA 10:1 split ex-date: 2024-06-10. - // Bar 1: 2024-06-07 15:59 ET (EDT, UTC-4) = 2024-06-07 19:59:00 UTC = 1_717_790_340 s. - // Bar 2: 2024-06-10 09:30 ET (EDT, UTC-4) = 2024-06-10 13:30:00 UTC = 1_718_026_200 s. - const PRE_SPLIT_TS_SEC: i64 = 1_717_790_340; - const EX_DATE_TS_SEC: i64 = 1_718_026_200; - - // Provider's retroactively split-adjusted 1m values. - let pre_split_doc = make_valid_doc( - "NVDA.US", - PRE_SPLIT_TS_SEC, - 120.80, - 121.05, - 120.72, - 120.888, - 2_500_000.0, - ); - let ex_date_doc = make_valid_doc( - "NVDA.US", - EX_DATE_TS_SEC, - 120.37, - 121.10, - 120.15, - 120.95, - 1_800_000.0, - ); - - let mut raw_buf = Vec::new(); - raw_buf.extend_from_slice(pre_split_doc.as_bytes()); - raw_buf.extend_from_slice(ex_date_doc.as_bytes()); - - let splits = SplitTable::from_events([( - "NVDA.US".to_owned(), - SplitEvent { - ex_date: day(2024, 6, 10), - ratio: 10.0, - }, - )]) - .unwrap(); - let empty_splits = SplitTable::::default(); - - let run_once = |table: &SplitTable| { - let mut bars = Vec::new(); - let mut decode_errors = Vec::new(); - let decode_stats = decode_eod_intraday_buffer( - &raw_buf, - |raw| bars.push(raw.into_eod_intraday_bar(|code, _ts| code.to_owned())), - |off, err| decode_errors.push((off, err)), - ); - assert!(decode_errors.is_empty()); - assert_eq!(decode_stats.docs_seen, 2); - assert_eq!(decode_stats.rows_decoded, 2); - let built = build_bars_1m(bars, table); - (decode_stats, built) - }; - - let (stats_split, built_split) = run_once(&splits); - let (stats_empty, built_empty) = run_once(&empty_splits); - let (stats_replay, built_replay) = run_once(&splits); - - // Deterministic replay produces identical rows and stats. - assert_eq!(stats_split, stats_replay); - assert_eq!(built_split.rows, built_replay.rows); - assert_eq!(built_split.stats, built_replay.stats); - assert_eq!(stats_split, stats_empty); - - assert_eq!(built_split.rows.len(), 2); - assert_eq!(built_empty.rows.len(), 2); - - // Pre-split bar: OHLC * 10, volume / 10, dollar volume (close * volume) conserved. - let pre_split = &built_split.rows[0]; - let pre_empty = &built_empty.rows[0]; - assert_eq!(pre_split.key, "NVDA.US"); - assert_eq!(pre_split.ts, PRE_SPLIT_TS_SEC * 1_000_000); - assert_eq!(pre_split.session_date, day(2024, 6, 7)); - assert_eq!(pre_split.session, IntradaySession::Rth); - assert_eq!(pre_split.source, BARS_1M_SOURCE_EOD); - assert_rel_eq(pre_split.open, pre_empty.open * 10.0, 1e-12); - assert_rel_eq(pre_split.high, pre_empty.high * 10.0, 1e-12); - assert_rel_eq(pre_split.low, pre_empty.low * 10.0, 1e-12); - assert_rel_eq(pre_split.close, 1_208.88, 1e-12); - assert_rel_eq(pre_split.close, pre_empty.close * 10.0, 1e-12); - assert_rel_eq(pre_split.volume, pre_empty.volume / 10.0, 1e-12); - assert_rel_eq( - pre_split.close * pre_split.volume, - pre_empty.close * pre_empty.volume, - 1e-12, - ); - - // Ex-date bar: unchanged by the 2024-06-10 split (strict ex_date > session_date boundary). - let ex_split = &built_split.rows[1]; - let ex_empty = &built_empty.rows[1]; - assert_eq!(ex_split.ts, EX_DATE_TS_SEC * 1_000_000); - assert_eq!(ex_split.session_date, day(2024, 6, 10)); - assert_eq!(ex_split.session, IntradaySession::Rth); - assert_eq!(ex_split.open.to_bits(), ex_empty.open.to_bits()); - assert_eq!(ex_split.high.to_bits(), ex_empty.high.to_bits()); - assert_eq!(ex_split.low.to_bits(), ex_empty.low.to_bits()); - assert_eq!(ex_split.close.to_bits(), ex_empty.close.to_bits()); - assert_eq!(ex_split.volume.to_bits(), ex_empty.volume.to_bits()); -} diff --git a/tools/curate-etl/src/bson_qm_intraday.rs b/tools/curate-etl/src/bson_qm_intraday.rs deleted file mode 100644 index 491d4138..00000000 --- a/tools/curate-etl/src/bson_qm_intraday.rs +++ /dev/null @@ -1,641 +0,0 @@ -//! Zero-copy raw BSON decoder for MongoDB `qmIntraday` documents (`M2.3i`). -//! -//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into -//! borrowed [`RawQmIntradayBar`] views without allocating a `String` or `bson::Document` per row. -//! Callers can convert borrowed views into [`crate::bars_1m::EodIntradayBar`] via a -//! caller-supplied key mapper without per-row `String` allocations, keeping in mind that -//! `qmIntraday` raw fields are already un-adjusted (see [`RawQmIntradayBar::into_eod_intraday_bar`]). -//! -//! # Empirical Field Contract & Cited Sources -//! -//! Field names and semantics are grounded in the repository's ingestion writer and empirical data -//! contract: -//! - `apps/stock/data-ingestion/src/handlers/qm/actions/intraday-crawl.action.ts:119-131,165-173` -//! (requests 1-minute bars via `interval: '1'`, spreads the provider bar payload, adds -//! `qmSearchCode`, `symbol`, `exchange`, and -//! `timestamp: new Date(bar.startdatetime || bar.date || bar.datetime)`, and upserts into -//! `qmIntraday` keyed by `['qmSearchCode', 'timestamp']`) -//! - `design/DATA-CONTRACTS.md:16` (§1 row `qmIntraday`, ~173.3M docs): stores **both** raw -//! (`open..close`, `sharevolume`) and split-adjusted (`adjustedopen..adjustedclose`, `avolume`) -//! fields. This decoder reads the raw fields only; all adjusted fields are validated as borrowed -//! `RawBsonRef` payloads and otherwise ignored. -//! -//! `ts` is decoded as bar-start UTC microseconds (`DateTime` milliseconds × `1_000`). Downstream -//! research/curation owns availability (`known_at`) decisions. -//! -//! # Accepted BSON Representations & Decoder Conventions -//! -//! Following [`crate::bson_eod_intraday`] and [`crate::bson_qm_prices`]: -//! - `qmSearchCode`: BSON UTF-8 `String`, borrowed verbatim (never trimmed). Empty or -//! whitespace-only strings are rejected as [`BsonQmIntradayError::EmptyField`]; non-string -//! values (including BSON `Null`) are rejected as [`BsonQmIntradayError::WrongType`]. -//! - `timestamp`: BSON `DateTime` (UTC milliseconds since Unix epoch), converted to UTC -//! microseconds via checked multiplication by `1_000`. Non-`DateTime` types (including `Null`, -//! integers, doubles, strings, and BSON `Timestamp`) are rejected as -//! [`BsonQmIntradayError::WrongType`]; negative millisecond values or values overflowing `i64` -//! microseconds are rejected as [`BsonQmIntradayError::InvalidTimestamp`]. -//! - `open`, `high`, `low`, `close`: BSON `Double`, `Int32`, or `Int64`; must be finite and -//! strictly positive (`> 0.0`). Non-numeric types (including `Null`) are rejected as -//! [`BsonQmIntradayError::WrongType`]; `NaN`, `±inf`, `0.0`, `-0.0`, and `< 0.0` are rejected -//! as [`BsonQmIntradayError::InvalidNumber`]. -//! - `sharevolume`: BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` is -//! normalized to `+0.0`). Non-numeric types (including `Null`) are rejected as -//! [`BsonQmIntradayError::WrongType`]; `NaN`, `±inf`, and `< 0.0` are rejected as -//! [`BsonQmIntradayError::InvalidNumber`]. -//! - All other top-level fields (`_id`, `symbol`, `exchange`, `adjustedopen`, `adjustedhigh`, -//! `adjustedlow`, `adjustedclose`, `avolume`, `startdatetime`, nested objects/arrays, etc.) are -//! validated as borrowed `RawBsonRef` views (zero allocation) and otherwise ignored, so malformed -//! bytes in skipped fields still surface as [`BsonQmIntradayError::CorruptBson`]. -//! - Duplicate fields and error precedence: later valid duplicates replace earlier valid values, -//! the first semantic error is retained (a later valid duplicate cannot clear an earlier semantic -//! error), and malformed BSON bytes take precedence immediately as `CorruptBson`. After the scan, -//! the first semantic error is returned, or else the first missing required field in -//! `qmSearchCode`, `timestamp`, `open`, `high`, `low`, `close`, `sharevolume` order. - -use std::error::Error; -use std::fmt; - -use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement}; -use bson::spec::ElementType; - -use crate::bars_1m::EodIntradayBar; -use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError}; - -/// MongoDB field name for the QuoteMedia security key (`intraday-crawl.action.ts:167,173`). -pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode"; -/// MongoDB field name for the bar-start BSON `DateTime` (`intraday-crawl.action.ts:170,173`). -pub const FIELD_TIMESTAMP: &str = "timestamp"; -/// MongoDB field name for raw bar open price (`DATA-CONTRACTS.md:16`). -pub const FIELD_OPEN: &str = "open"; -/// MongoDB field name for raw bar high price (`DATA-CONTRACTS.md:16`). -pub const FIELD_HIGH: &str = "high"; -/// MongoDB field name for raw bar low price (`DATA-CONTRACTS.md:16`). -pub const FIELD_LOW: &str = "low"; -/// MongoDB field name for raw bar close price (`DATA-CONTRACTS.md:16`). -pub const FIELD_CLOSE: &str = "close"; -/// MongoDB field name for raw bar share volume (`DATA-CONTRACTS.md:16`). -pub const FIELD_SHARE_VOLUME: &str = "sharevolume"; - -const MICROS_PER_MILLI: i64 = 1_000; -/// Largest UTC millisecond timestamp that fits in signed `i64` microseconds (`9_223_372_036_854_775`). -#[cfg(test)] -pub(crate) const MAX_TIMESTAMP_MILLIS: i64 = i64::MAX / MICROS_PER_MILLI; - -/// Borrowed zero-copy view of a single decoded `qmIntraday` BSON document. -/// -/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice. -/// `open`, `high`, `low`, `close`, and `volume` are the provider's already-raw values -/// (`open..close`, `sharevolume`); adjusted fields are ignored. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct RawQmIntradayBar<'a> { - pub qm_search_code: &'a str, - /// 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, -} - -impl<'a> RawQmIntradayBar<'a> { - /// Converts this borrowed view into an [`EodIntradayBar`] using a caller-supplied key - /// mapper. - /// - /// `map_key` receives `(qm_search_code, ts)` (provider code and UTC bar-start microseconds) - /// and this method only maps the key and copies the raw OHLCV fields verbatim. - /// - /// **Important:** [`crate::bars_1m::build_bars_1m`] applies split un-adjustment to - /// [`EodIntradayBar`] inputs (which is required for retroactively split-adjusted - /// `eodIntraday1M` bars). Passing already-raw `qmIntraday` bars through a split-unadjusting - /// path with non-empty splits would distort raw prices and volumes; downstream `qmIntraday` - /// curation must ingest raw values without split un-adjustment. - #[inline] - pub fn into_eod_intraday_bar(self, map_key: F) -> EodIntradayBar - where - F: FnOnce(&'a str, i64) -> K, - { - EodIntradayBar { - key: map_key(self.qm_search_code, self.ts), - ts: self.ts, - open: self.open, - high: self.high, - low: self.low, - close: self.close, - volume: self.volume, - } - } - - /// Fallible conversion into [`EodIntradayBar`] using a caller-supplied key resolver. - /// - /// Maps `(qm_search_code, ts)` and copies the raw OHLCV fields verbatim without applying any - /// split adjustment. See [`Self::into_eod_intraday_bar`] for the split un-adjustment caveat. - #[inline] - pub fn try_into_eod_intraday_bar(self, map_key: F) -> Option> - where - F: FnOnce(&'a str, i64) -> Option, - { - let key = map_key(self.qm_search_code, self.ts)?; - Some(EodIntradayBar { - key, - ts: self.ts, - open: self.open, - high: self.high, - low: self.low, - close: self.close, - volume: self.volume, - }) - } -} - -/// Typed errors returned while decoding raw `qmIntraday` BSON documents or length-prefixed -/// buffers. -/// -/// Every field-level error names the offending BSON field in both its structure and `Display` -/// output; malformed and truncated BSON framing errors report `CorruptBson` with byte offset and -/// framing detail; no input path panics. -#[derive(Debug, Clone, PartialEq)] -pub enum BsonQmIntradayError { - /// A required field was absent from the document. - MissingField { field: &'static str }, - /// A required string field was empty or contained only whitespace. - EmptyField { field: &'static str }, - /// A required field had an unexpected BSON element type (including `Null`). - WrongType { - field: &'static str, - actual: ElementType, - }, - /// `timestamp` BSON `DateTime` was negative or overflowed `i64` microseconds. - InvalidTimestamp { field: &'static str }, - /// An OHLC field was non-finite or `<= 0.0`, or `sharevolume` was non-finite or `< 0.0`. - InvalidNumber { field: &'static str, value: f64 }, - /// Underlying BSON framing, truncation, document length, or element bytes were malformed. - CorruptBson { offset: usize, detail: String }, -} - -impl fmt::Display for BsonQmIntradayError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::MissingField { field } => { - write!(f, "qmIntraday BSON missing required field '{field}'") - } - Self::EmptyField { field } => { - write!( - f, - "qmIntraday BSON field '{field}' must not be empty or blank" - ) - } - Self::WrongType { field, actual } => { - write!( - f, - "qmIntraday BSON field '{field}' has unexpected BSON type {actual:?}" - ) - } - Self::InvalidTimestamp { field } => { - write!( - f, - "qmIntraday BSON field '{field}' is not a valid non-negative DateTime within i64 microsecond range" - ) - } - Self::InvalidNumber { field, value } => { - if *field == FIELD_SHARE_VOLUME { - write!( - f, - "qmIntraday BSON field '{field}' has invalid numeric value {value}: must be finite and >= 0" - ) - } else { - write!( - f, - "qmIntraday BSON field '{field}' has invalid numeric value {value}: must be finite and > 0" - ) - } - } - Self::CorruptBson { offset, detail } => { - write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}") - } - } - } -} - -impl Error for BsonQmIntradayError {} - -#[inline] -fn map_framing_error(err: BsonEodPriceError) -> BsonQmIntradayError { - match err { - BsonEodPriceError::TruncatedDocument { offset, .. } - | BsonEodPriceError::CorruptDocumentLength { offset, .. } => { - BsonQmIntradayError::CorruptBson { - offset, - detail: err.to_string(), - } - } - BsonEodPriceError::CorruptBson { offset, detail } => { - BsonQmIntradayError::CorruptBson { offset, detail } - } - BsonEodPriceError::MissingField { field } => BsonQmIntradayError::MissingField { field }, - BsonEodPriceError::EmptyField { field } => BsonQmIntradayError::EmptyField { field }, - BsonEodPriceError::WrongType { field, actual } => { - BsonQmIntradayError::WrongType { field, actual } - } - BsonEodPriceError::MalformedDate { field } => { - BsonQmIntradayError::InvalidTimestamp { field } - } - BsonEodPriceError::InvalidNumber { field, value } => { - BsonQmIntradayError::InvalidNumber { field, value } - } - } -} - -/// Per-batch decode and rejection accounting for [`decode_qm_intraday_buffer`]. -/// -/// Conservation invariant: `rows_decoded + rejected_total() == docs_seen`. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct BsonQmIntradayDecodeStats { - pub docs_seen: usize, - pub rows_decoded: usize, - pub rejected_missing_field: usize, - pub rejected_empty_field: usize, - pub rejected_wrong_type: usize, - pub rejected_invalid_timestamp: usize, - pub rejected_invalid_number: usize, - pub rejected_corrupt_document: usize, -} - -impl BsonQmIntradayDecodeStats { - /// Total number of rejected documents across all error categories. - #[inline] - pub fn rejected_total(&self) -> usize { - self.rejected_missing_field - + self.rejected_empty_field - + self.rejected_wrong_type - + self.rejected_invalid_timestamp - + self.rejected_invalid_number - + self.rejected_corrupt_document - } - - /// Increments the rejection counter corresponding to `err`. - #[inline] - pub fn record_error(&mut self, err: &BsonQmIntradayError) { - match err { - BsonQmIntradayError::MissingField { .. } => self.rejected_missing_field += 1, - BsonQmIntradayError::EmptyField { .. } => self.rejected_empty_field += 1, - BsonQmIntradayError::WrongType { .. } => self.rejected_wrong_type += 1, - BsonQmIntradayError::InvalidTimestamp { .. } => self.rejected_invalid_timestamp += 1, - BsonQmIntradayError::InvalidNumber { .. } => self.rejected_invalid_number += 1, - BsonQmIntradayError::CorruptBson { .. } => self.rejected_corrupt_document += 1, - } - } - - /// Accumulates counters from another batch into `self`. - #[inline] - pub fn merge(&mut self, other: &Self) { - self.docs_seen += other.docs_seen; - self.rows_decoded += other.rows_decoded; - self.rejected_missing_field += other.rejected_missing_field; - self.rejected_empty_field += other.rejected_empty_field; - self.rejected_wrong_type += other.rejected_wrong_type; - self.rejected_invalid_timestamp += other.rejected_invalid_timestamp; - self.rejected_invalid_number += other.rejected_invalid_number; - self.rejected_corrupt_document += other.rejected_corrupt_document; - } -} - -impl std::ops::AddAssign for BsonQmIntradayDecodeStats { - #[inline] - fn add_assign(&mut self, rhs: Self) { - self.merge(&rhs); - } -} - -#[inline] -fn decode_element_value<'a>( - field: &'static str, - elem: RawElement<'a>, - offset: usize, -) -> Result, BsonQmIntradayError> { - elem.value().map_err(|err| BsonQmIntradayError::CorruptBson { - offset, - detail: format!("field '{field}': {err}"), - }) -} - -#[inline] -fn decode_timestamp_datetime_to_micros(val: RawBsonRef<'_>) -> Result { - match val { - RawBsonRef::DateTime(dt) => { - let millis = dt.timestamp_millis(); - if millis < 0 { - return Err(BsonQmIntradayError::InvalidTimestamp { - field: FIELD_TIMESTAMP, - }); - } - millis - .checked_mul(MICROS_PER_MILLI) - .ok_or(BsonQmIntradayError::InvalidTimestamp { - field: FIELD_TIMESTAMP, - }) - } - other => Err(BsonQmIntradayError::WrongType { - field: FIELD_TIMESTAMP, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_positive_number( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => { - if !v.is_finite() || v <= 0.0 { - return Err(BsonQmIntradayError::InvalidNumber { field, value: v }); - } - Ok(v) - } - RawBsonRef::Int32(v) => { - if v <= 0 { - return Err(BsonQmIntradayError::InvalidNumber { - field, - value: f64::from(v), - }); - } - Ok(f64::from(v)) - } - RawBsonRef::Int64(v) => { - if v <= 0 { - return Err(BsonQmIntradayError::InvalidNumber { - field, - value: v as f64, - }); - } - Ok(v as f64) - } - other => Err(BsonQmIntradayError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -#[inline] -fn decode_non_negative_number( - field: &'static str, - val: RawBsonRef<'_>, -) -> Result { - match val { - RawBsonRef::Double(v) => { - if !v.is_finite() || v < 0.0 { - return Err(BsonQmIntradayError::InvalidNumber { field, value: v }); - } - if v == 0.0 { - Ok(0.0) - } else { - Ok(v) - } - } - RawBsonRef::Int32(v) => { - if v < 0 { - return Err(BsonQmIntradayError::InvalidNumber { - field, - value: f64::from(v), - }); - } - Ok(f64::from(v)) - } - RawBsonRef::Int64(v) => { - if v < 0 { - return Err(BsonQmIntradayError::InvalidNumber { - field, - value: v as f64, - }); - } - Ok(v as f64) - } - other => Err(BsonQmIntradayError::WrongType { - field, - actual: other.element_type(), - }), - } -} - -fn decode_qm_intraday_doc_at<'a>( - doc: &'a RawDocument, - offset: usize, -) -> Result, BsonQmIntradayError> { - let mut qm_search_code: Option<&'a str> = None; - let mut ts: Option = None; - let mut open: Option = None; - let mut high: Option = None; - let mut low: Option = None; - let mut close: Option = None; - let mut volume: Option = None; - let mut first_semantic_err: Option = None; - - for elem_res in doc.iter_elements() { - let elem = elem_res.map_err(|err| BsonQmIntradayError::CorruptBson { - offset, - detail: err.to_string(), - })?; - let key = elem.key(); - - if key == cstr!("qmSearchCode") { - match decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)? { - RawBsonRef::String(s) => { - if s.trim().is_empty() { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonQmIntradayError::EmptyField { - field: FIELD_QM_SEARCH_CODE, - }); - } - } else { - qm_search_code = Some(s); - } - } - other => { - if first_semantic_err.is_none() { - first_semantic_err = Some(BsonQmIntradayError::WrongType { - field: FIELD_QM_SEARCH_CODE, - actual: other.element_type(), - }); - } - } - } - } else if key == cstr!("timestamp") { - let val = decode_element_value(FIELD_TIMESTAMP, elem, offset)?; - match decode_timestamp_datetime_to_micros(val) { - Ok(micros) => ts = Some(micros), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("open") { - let val = decode_element_value(FIELD_OPEN, elem, offset)?; - match decode_positive_number(FIELD_OPEN, val) { - Ok(v) => open = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("high") { - let val = decode_element_value(FIELD_HIGH, elem, offset)?; - match decode_positive_number(FIELD_HIGH, val) { - Ok(v) => high = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("low") { - let val = decode_element_value(FIELD_LOW, elem, offset)?; - match decode_positive_number(FIELD_LOW, val) { - Ok(v) => low = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("close") { - let val = decode_element_value(FIELD_CLOSE, elem, offset)?; - match decode_positive_number(FIELD_CLOSE, val) { - Ok(v) => close = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else if key == cstr!("sharevolume") { - let val = decode_element_value(FIELD_SHARE_VOLUME, elem, offset)?; - match decode_non_negative_number(FIELD_SHARE_VOLUME, val) { - Ok(v) => volume = Some(v), - Err(err) => { - if first_semantic_err.is_none() { - first_semantic_err = Some(err); - } - } - } - } else { - // Validate skipped top-level payloads (including adjustedopen..adjustedclose and - // avolume) via borrowed `RawBsonRef` views (zero allocation) so malformed bytes still - // reject the document as `CorruptBson` at its frame offset. - elem.value().map_err(|err| BsonQmIntradayError::CorruptBson { - offset, - detail: format!("field '{}': {err}", key.as_str()), - })?; - } - } - - if let Some(err) = first_semantic_err { - return Err(err); - } - - let Some(qm_search_code) = qm_search_code else { - return Err(BsonQmIntradayError::MissingField { - field: FIELD_QM_SEARCH_CODE, - }); - }; - let Some(ts) = ts else { - return Err(BsonQmIntradayError::MissingField { - field: FIELD_TIMESTAMP, - }); - }; - let Some(open) = open else { - return Err(BsonQmIntradayError::MissingField { field: FIELD_OPEN }); - }; - let Some(high) = high else { - return Err(BsonQmIntradayError::MissingField { field: FIELD_HIGH }); - }; - let Some(low) = low else { - return Err(BsonQmIntradayError::MissingField { field: FIELD_LOW }); - }; - let Some(close) = close else { - return Err(BsonQmIntradayError::MissingField { field: FIELD_CLOSE }); - }; - let Some(volume) = volume else { - return Err(BsonQmIntradayError::MissingField { - field: FIELD_SHARE_VOLUME, - }); - }; - - Ok(RawQmIntradayBar { - qm_search_code, - ts, - open, - high, - low, - close, - volume, - }) -} - -/// Decodes a single `&RawDocument` representing a `qmIntraday` MongoDB document in one forward -/// pass without allocating a `String` or owned `bson::Document`. -#[inline] -pub fn decode_qm_intraday_doc<'a>( - doc: &'a RawDocument, -) -> Result, BsonQmIntradayError> { - decode_qm_intraday_doc_at(doc, 0) -} - -/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed -/// [`RawQmIntradayBar`]. -pub fn decode_qm_intraday_bytes<'a>( - bytes: &'a [u8], -) -> Result, BsonQmIntradayError> { - let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?; - decode_qm_intraday_doc_at(doc, 0) -} - -/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_intraday_doc`], -/// invoking `on_bar` for every valid document and `on_error(byte_offset, err)` for every rejected -/// document without aborting the stream on recoverable per-document errors. -/// -/// Stops at an unrecoverable frame length or truncated tail and counts it once. -/// Always maintains `stats.rows_decoded + stats.rejected_total() == stats.docs_seen`. -pub fn decode_qm_intraday_buffer<'a, F, E>( - buf: &'a [u8], - mut on_bar: F, - mut on_error: E, -) -> BsonQmIntradayDecodeStats -where - F: FnMut(RawQmIntradayBar<'a>), - E: FnMut(usize, BsonQmIntradayError), -{ - let mut stats = BsonQmIntradayDecodeStats::default(); - let mut iter = iter_raw_bson_docs(buf); - - while let Some(item) = iter.next_with_offset() { - stats.docs_seen += 1; - match item { - Ok((doc_offset, doc)) => match decode_qm_intraday_doc_at(doc, doc_offset) { - Ok(bar) => { - stats.rows_decoded += 1; - on_bar(bar); - } - Err(err) => { - stats.record_error(&err); - on_error(doc_offset, err); - } - }, - Err((doc_offset, err)) => { - let mapped = map_framing_error(err); - stats.record_error(&mapped); - on_error(doc_offset, mapped); - } - } - } - - stats -} - -#[cfg(test)] -#[path = "bson_qm_intraday_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/bson_qm_intraday_tests.rs b/tools/curate-etl/src/bson_qm_intraday_tests.rs deleted file mode 100644 index b4638271..00000000 --- a/tools/curate-etl/src/bson_qm_intraday_tests.rs +++ /dev/null @@ -1,1092 +0,0 @@ -use bson::oid::ObjectId; -use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf}; -use bson::spec::ElementType; -use bson::{DateTime, Timestamp}; - -use super::*; - -fn make_valid_doc( - code: &str, - timestamp_ms: i64, - open: f64, - high: f64, - low: f64, - close: f64, - sharevolume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("timestamp"), DateTime::from_millis(timestamp_ms)); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("sharevolume"), sharevolume); - doc -} - -fn make_doc_with_timestamp(timestamp: RawBsonRef<'_>) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), timestamp); - doc.append(cstr!("open"), 84.10_f64); - doc.append(cstr!("high"), 84.55_f64); - doc.append(cstr!("low"), 84.02_f64); - doc.append(cstr!("close"), 84.40_f64); - doc.append(cstr!("sharevolume"), 12_500.0_f64); - doc -} - -#[test] -fn decodes_raw_fields_ignoring_differing_adjusted_fields_with_zero_copy_key_and_mappers() { - // 2024-06-07T13:30:00.375Z (nonzero milliseconds to verify exact * 1_000 scaling) - const TS_MS: i64 = 1_717_767_000_375; - const EXPECTED_TS_MICROS: i64 = 1_717_767_000_375_000; - const VERBATIM_KEY: &str = " SHOP:CA "; - - let mut nested = RawDocumentBuf::new(); - nested.append(cstr!("provider"), "quotemedia"); - nested.append(cstr!("interval"), 1_i32); - - let mut tags = RawArrayBuf::new(); - tags.push("ca"); - tags.push("1m"); - - let mut doc = RawDocumentBuf::new(); - doc.append( - cstr!("_id"), - ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]), - ); - doc.append(cstr!("symbol"), "SHOP"); - doc.append(cstr!("exchange"), "TSX"); - doc.append(cstr!("qmSearchCode"), VERBATIM_KEY); - doc.append(cstr!("startdatetime"), "2024-06-07 09:30:00"); - doc.append(cstr!("timestamp"), DateTime::from_millis(TS_MS)); - // Mixed numeric encodings for raw fields: - doc.append(cstr!("open"), 84_i32); - doc.append(cstr!("high"), 85_i64); - doc.append(cstr!("low"), 83.75_f64); - doc.append(cstr!("close"), 84.50_f64); - doc.append(cstr!("sharevolume"), 12_500_i64); - // Deliberately different adjusted fields that must be ignored: - doc.append(cstr!("adjustedopen"), 8.40_f64); - doc.append(cstr!("adjustedhigh"), 8.50_f64); - doc.append(cstr!("adjustedlow"), 8.375_f64); - doc.append(cstr!("adjustedclose"), 8.45_f64); - doc.append(cstr!("avolume"), 125_000.0_f64); - doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); - doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref())); - - let bytes = doc.as_bytes(); - let buf_start = bytes.as_ptr() as usize; - let buf_end = buf_start + bytes.len(); - - let from_doc = decode_qm_intraday_doc(&doc).unwrap(); - let from_bytes = decode_qm_intraday_bytes(bytes).unwrap(); - assert_eq!(from_doc, from_bytes); - - for bar in [from_doc, from_bytes] { - assert_eq!(bar.qm_search_code, VERBATIM_KEY); - assert_eq!(bar.ts, EXPECTED_TS_MICROS); - assert_eq!(bar.open.to_bits(), 84.0_f64.to_bits()); - assert_eq!(bar.high.to_bits(), 85.0_f64.to_bits()); - assert_eq!(bar.low.to_bits(), 83.75_f64.to_bits()); - assert_eq!(bar.close.to_bits(), 84.50_f64.to_bits()); - assert_eq!(bar.volume.to_bits(), 12_500.0_f64.to_bits()); - - // Zero-copy proof: borrowed key slice points inside the input BSON buffer. - let key_start = bar.qm_search_code.as_ptr() as usize; - let key_end = key_start + bar.qm_search_code.len(); - assert!( - key_start >= buf_start && key_end <= buf_end, - "expected qm_search_code pointer {key_start:#x}..{key_end:#x} inside input buffer {buf_start:#x}..{buf_end:#x}" - ); - } - - // Verify into_eod_intraday_bar and try_into_eod_intraday_bar preserve raw OHLCV verbatim. - let mut seen_into: Option<(&str, i64)> = None; - let mapped = from_doc.into_eod_intraday_bar(|code, ts| { - seen_into = Some((code, ts)); - 42_u64 - }); - assert_eq!(seen_into, Some((VERBATIM_KEY, EXPECTED_TS_MICROS))); - assert_eq!(mapped.key, 42_u64); - assert_eq!(mapped.ts, EXPECTED_TS_MICROS); - assert_eq!(mapped.open.to_bits(), 84.0_f64.to_bits()); - assert_eq!(mapped.high.to_bits(), 85.0_f64.to_bits()); - assert_eq!(mapped.low.to_bits(), 83.75_f64.to_bits()); - assert_eq!(mapped.close.to_bits(), 84.50_f64.to_bits()); - assert_eq!(mapped.volume.to_bits(), 12_500.0_f64.to_bits()); - - let mut seen_try_some: Option<(&str, i64)> = None; - let try_some = from_doc.try_into_eod_intraday_bar(|code, ts| { - seen_try_some = Some((code, ts)); - Some(99_u64) - }); - assert_eq!(seen_try_some, Some((VERBATIM_KEY, EXPECTED_TS_MICROS))); - let try_some = try_some.unwrap(); - assert_eq!(try_some.key, 99_u64); - assert_eq!(try_some.ts, EXPECTED_TS_MICROS); - assert_eq!(try_some.open.to_bits(), 84.0_f64.to_bits()); - assert_eq!(try_some.high.to_bits(), 85.0_f64.to_bits()); - assert_eq!(try_some.low.to_bits(), 83.75_f64.to_bits()); - assert_eq!(try_some.close.to_bits(), 84.50_f64.to_bits()); - assert_eq!(try_some.volume.to_bits(), 12_500.0_f64.to_bits()); - - let try_none: Option> = from_doc.try_into_eod_intraday_bar(|code, ts| { - assert_eq!(code, VERBATIM_KEY); - assert_eq!(ts, EXPECTED_TS_MICROS); - None - }); - assert!(try_none.is_none()); -} - -#[test] -fn table_tests_all_seven_required_fields_for_omission_null_and_wrong_type() { - const ALL_FIELDS: [&str; 7] = [ - FIELD_QM_SEARCH_CODE, - FIELD_TIMESTAMP, - FIELD_OPEN, - FIELD_HIGH, - FIELD_LOW, - FIELD_CLOSE, - FIELD_SHARE_VOLUME, - ]; - - let append_valid = |doc: &mut RawDocumentBuf, field: &str| match field { - FIELD_QM_SEARCH_CODE => doc.append(cstr!("qmSearchCode"), "SHOP:CA"), - FIELD_TIMESTAMP => doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)), - FIELD_OPEN => doc.append(cstr!("open"), 10.0_f64), - FIELD_HIGH => doc.append(cstr!("high"), 11.0_f64), - FIELD_LOW => doc.append(cstr!("low"), 9.5_f64), - FIELD_CLOSE => doc.append(cstr!("close"), 10.5_f64), - FIELD_SHARE_VOLUME => doc.append(cstr!("sharevolume"), 100.0_f64), - other => unreachable!("unexpected field {other}"), - }; - - let append_override = |doc: &mut RawDocumentBuf, field: &str, val: RawBsonRef<'_>| match field { - FIELD_QM_SEARCH_CODE => doc.append(cstr!("qmSearchCode"), val), - FIELD_TIMESTAMP => doc.append(cstr!("timestamp"), val), - FIELD_OPEN => doc.append(cstr!("open"), val), - FIELD_HIGH => doc.append(cstr!("high"), val), - FIELD_LOW => doc.append(cstr!("low"), val), - FIELD_CLOSE => doc.append(cstr!("close"), val), - FIELD_SHARE_VOLUME => doc.append(cstr!("sharevolume"), val), - other => unreachable!("unexpected field {other}"), - }; - - for target in ALL_FIELDS { - // 1. Omission -> MissingField - let mut missing = RawDocumentBuf::new(); - for f in ALL_FIELDS { - if f != target { - append_valid(&mut missing, f); - } - } - let err = decode_qm_intraday_doc(&missing).unwrap_err(); - assert_eq!(err, BsonQmIntradayError::MissingField { field: target }); - assert!(err.to_string().contains(target)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_missing_field, 1); - assert_eq!(st.rejected_total(), 1); - - // 2. Null -> WrongType(Null) - let mut with_null = RawDocumentBuf::new(); - for f in ALL_FIELDS { - if f == target { - append_override(&mut with_null, f, RawBsonRef::Null); - } else { - append_valid(&mut with_null, f); - } - } - let err = decode_qm_intraday_doc(&with_null).unwrap_err(); - assert_eq!( - err, - BsonQmIntradayError::WrongType { - field: target, - actual: ElementType::Null, - } - ); - assert!(err.to_string().contains(target)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_wrong_type, 1); - assert_eq!(st.rejected_total(), 1); - - // 3. Another inappropriate BSON type -> WrongType - let (bad_val, expected_type) = match target { - FIELD_QM_SEARCH_CODE => (RawBsonRef::Int32(123), ElementType::Int32), - FIELD_TIMESTAMP => (RawBsonRef::Boolean(true), ElementType::Boolean), - _ => (RawBsonRef::String("10.0"), ElementType::String), - }; - let mut with_wrong = RawDocumentBuf::new(); - for f in ALL_FIELDS { - if f == target { - append_override(&mut with_wrong, f, bad_val); - } else { - append_valid(&mut with_wrong, f); - } - } - let err = decode_qm_intraday_doc(&with_wrong).unwrap_err(); - assert_eq!( - err, - BsonQmIntradayError::WrongType { - field: target, - actual: expected_type, - } - ); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_wrong_type, 1); - assert_eq!(st.rejected_total(), 1); - } - - // Empty document checks missing-field order starts at qmSearchCode. - let empty_doc = RawDocumentBuf::new(); - assert_eq!( - decode_qm_intraday_doc(&empty_doc).unwrap_err(), - BsonQmIntradayError::MissingField { - field: FIELD_QM_SEARCH_CODE - } - ); -} - -#[test] -fn rejects_empty_and_whitespace_only_qm_search_code() { - for blank in ["", " ", " ", "\t\n\r "] { - let doc = make_valid_doc(blank, 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmIntradayError::EmptyField { - field: FIELD_QM_SEARCH_CODE - } - ); - assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_empty_field, 1); - assert_eq!(st.rejected_total(), 1); - } -} - -#[test] -fn validates_timestamp_datetime_boundaries_and_rejects_substitutes() { - // Epoch zero is valid. - let epoch_doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(0))); - assert_eq!(decode_qm_intraday_doc(&epoch_doc).unwrap().ts, 0); - - // Largest in-range millisecond timestamp (i64::MAX / 1_000) is valid. - let max_doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis( - MAX_TIMESTAMP_MILLIS, - ))); - assert_eq!( - decode_qm_intraday_doc(&max_doc).unwrap().ts, - MAX_TIMESTAMP_MILLIS * 1_000 - ); - - // Negative and overflowing DateTime values -> InvalidTimestamp. - for bad_ms in [-1_i64, i64::MIN, MAX_TIMESTAMP_MILLIS + 1, i64::MAX] { - let doc = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(bad_ms))); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmIntradayError::InvalidTimestamp { - field: FIELD_TIMESTAMP - } - ); - assert!(err.to_string().contains(FIELD_TIMESTAMP)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_invalid_timestamp, 1); - assert_eq!(st.rejected_total(), 1); - } - - // Numeric, string, and BSON Timestamp substitutes -> WrongType. - let wrong_ts: [(RawBsonRef<'_>, ElementType); 6] = [ - (RawBsonRef::Int32(1_717_767_000), ElementType::Int32), - (RawBsonRef::Int64(1_717_767_000_000), ElementType::Int64), - (RawBsonRef::Double(1_717_767_000_000.0), ElementType::Double), - ( - RawBsonRef::String("2024-06-07T13:30:00Z"), - ElementType::String, - ), - ( - RawBsonRef::Timestamp(Timestamp { - time: 1_717_767_000, - increment: 1, - }), - ElementType::Timestamp, - ), - (RawBsonRef::Null, ElementType::Null), - ]; - for (val, expected_type) in wrong_ts { - let doc = make_doc_with_timestamp(val); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - assert_eq!( - err, - BsonQmIntradayError::WrongType { - field: FIELD_TIMESTAMP, - actual: expected_type, - } - ); - } -} - -#[test] -fn validates_ohlc_and_sharevolume_domains_and_normalizes_negative_zero_volume() { - let ohlc_fields = [FIELD_OPEN, FIELD_HIGH, FIELD_LOW, FIELD_CLOSE]; - - for target in ohlc_fields { - let build_with = |val: RawBsonRef<'_>| { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - for (name, key) in [ - (FIELD_OPEN, cstr!("open")), - (FIELD_HIGH, cstr!("high")), - (FIELD_LOW, cstr!("low")), - (FIELD_CLOSE, cstr!("close")), - (FIELD_SHARE_VOLUME, cstr!("sharevolume")), - ] { - if name == target { - doc.append(key, val); - } else { - doc.append(key, 10.0_f64); - } - } - doc - }; - - for bad_num in [ - RawBsonRef::Double(0.0), - RawBsonRef::Double(-0.0), - RawBsonRef::Double(-1.25), - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Int32(0), - RawBsonRef::Int32(-5), - RawBsonRef::Int64(0), - RawBsonRef::Int64(-5), - ] { - let doc = build_with(bad_num); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - match &err { - BsonQmIntradayError::InvalidNumber { field, .. } => assert_eq!(*field, target), - other => panic!("expected InvalidNumber for {target}, got {other:?}"), - } - assert!(err.to_string().contains(target)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_invalid_number, 1); - assert_eq!(st.rejected_total(), 1); - } - } - - let build_with_vol = |val: RawBsonRef<'_>| { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.5_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("sharevolume"), val); - doc - }; - - // Zero sharevolume in +0.0, -0.0, Int32(0), Int64(0) canonicalizes to +0.0. - for zero_vol in [ - RawBsonRef::Double(0.0), - RawBsonRef::Double(-0.0), - RawBsonRef::Int32(0), - RawBsonRef::Int64(0), - ] { - let doc = build_with_vol(zero_vol); - let decoded = decode_qm_intraday_doc(&doc).unwrap(); - assert_eq!(decoded.volume.to_bits(), 0.0_f64.to_bits()); - } - - // Negative and non-finite sharevolume -> InvalidNumber. - for bad_vol in [ - RawBsonRef::Double(-0.01), - RawBsonRef::Double(f64::NAN), - RawBsonRef::Double(f64::INFINITY), - RawBsonRef::Double(f64::NEG_INFINITY), - RawBsonRef::Int32(-1), - RawBsonRef::Int64(-1), - ] { - let doc = build_with_vol(bad_vol); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - match &err { - BsonQmIntradayError::InvalidNumber { field, .. } => { - assert_eq!(*field, FIELD_SHARE_VOLUME) - } - other => panic!("expected InvalidNumber for sharevolume, got {other:?}"), - } - assert!(err.to_string().contains(FIELD_SHARE_VOLUME)); - let mut st = BsonQmIntradayDecodeStats::default(); - st.record_error(&err); - assert_eq!(st.rejected_invalid_number, 1); - assert_eq!(st.rejected_total(), 1); - } -} - -#[test] -fn duplicate_fields_and_semantic_vs_corrupt_precedence() { - // 1. All duplicate occurrences valid -> last valid value wins. - let mut dup_valid = RawDocumentBuf::new(); - dup_valid.append(cstr!("qmSearchCode"), "FIRST:CA"); - dup_valid.append(cstr!("timestamp"), DateTime::from_millis(1_000)); - dup_valid.append(cstr!("open"), 10.0_f64); - dup_valid.append(cstr!("high"), 11.0_f64); - dup_valid.append(cstr!("low"), 9.0_f64); - dup_valid.append(cstr!("close"), 10.5_f64); - dup_valid.append(cstr!("sharevolume"), 100.0_f64); - dup_valid.append(cstr!("qmSearchCode"), "SECOND:CA"); - dup_valid.append(cstr!("timestamp"), DateTime::from_millis(2_500)); - dup_valid.append(cstr!("open"), 20.0_f64); - dup_valid.append(cstr!("high"), 22.0_f64); - dup_valid.append(cstr!("low"), 19.0_f64); - dup_valid.append(cstr!("close"), 21.5_f64); - dup_valid.append(cstr!("sharevolume"), 250_i32); - - let bar = decode_qm_intraday_doc(&dup_valid).unwrap(); - assert_eq!(bar.qm_search_code, "SECOND:CA"); - assert_eq!(bar.ts, 2_500_000); - assert_eq!(bar.open.to_bits(), 20.0_f64.to_bits()); - assert_eq!(bar.high.to_bits(), 22.0_f64.to_bits()); - assert_eq!(bar.low.to_bits(), 19.0_f64.to_bits()); - assert_eq!(bar.close.to_bits(), 21.5_f64.to_bits()); - assert_eq!(bar.volume.to_bits(), 250.0_f64.to_bits()); - - // 2. A valid duplicate cannot erase an earlier semantic error. - let mut err_then_valid = RawDocumentBuf::new(); - err_then_valid.append(cstr!("qmSearchCode"), " "); - err_then_valid.append(cstr!("qmSearchCode"), "SHOP:CA"); - err_then_valid.append(cstr!("timestamp"), DateTime::from_millis(1_000)); - err_then_valid.append(cstr!("open"), 10.0_f64); - err_then_valid.append(cstr!("high"), 11.0_f64); - err_then_valid.append(cstr!("low"), 9.0_f64); - err_then_valid.append(cstr!("close"), 10.5_f64); - err_then_valid.append(cstr!("sharevolume"), 100.0_f64); - assert_eq!( - decode_qm_intraday_doc(&err_then_valid).unwrap_err(), - BsonQmIntradayError::EmptyField { - field: FIELD_QM_SEARCH_CODE - } - ); - - // 3. First semantic error survives a second semantic error. - let mut two_errors = RawDocumentBuf::new(); - two_errors.append(cstr!("qmSearchCode"), "SHOP:CA"); - two_errors.append(cstr!("timestamp"), DateTime::from_millis(-1)); - two_errors.append(cstr!("open"), -5.0_f64); - two_errors.append(cstr!("high"), RawBsonRef::Null); - two_errors.append(cstr!("low"), 9.0_f64); - two_errors.append(cstr!("close"), 10.5_f64); - two_errors.append(cstr!("sharevolume"), 100.0_f64); - assert_eq!( - decode_qm_intraday_doc(&two_errors).unwrap_err(), - BsonQmIntradayError::InvalidTimestamp { - field: FIELD_TIMESTAMP - } - ); - - // 4. Malformed UTF-8 in a later skipped field overrides an earlier semantic error as CorruptBson. - const MARKER: &[u8] = b"2024-06-07 09:30:00"; - let mut semantic_then_corrupt = RawDocumentBuf::new(); - semantic_then_corrupt.append(cstr!("qmSearchCode"), " "); // earlier EmptyField - semantic_then_corrupt.append(cstr!("timestamp"), DateTime::from_millis(-5)); // second semantic err - semantic_then_corrupt.append(cstr!("open"), 10.0_f64); - semantic_then_corrupt.append(cstr!("high"), 11.0_f64); - semantic_then_corrupt.append(cstr!("low"), 9.0_f64); - semantic_then_corrupt.append(cstr!("close"), 10.5_f64); - semantic_then_corrupt.append(cstr!("sharevolume"), 100.0_f64); - semantic_then_corrupt.append(cstr!("startdatetime"), "2024-06-07 09:30:00"); - - let mut corrupt_bytes = semantic_then_corrupt.as_bytes().to_vec(); - let pos = corrupt_bytes - .windows(MARKER.len()) - .position(|w| w == MARKER) - .expect("startdatetime marker must exist"); - corrupt_bytes[pos + 4] = 0xFF; - - match decode_qm_intraday_bytes(&corrupt_bytes) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!( - detail.contains("startdatetime"), - "expected offending skipped field name in detail, got: {detail}" - ); - } - other => panic!("expected CorruptBson overriding earlier semantic error, got {other:?}"), - } -} - -#[test] -fn rejects_truncated_corrupt_and_trailing_single_doc_bytes_as_corrupt_bson() { - // Truncated header (< 4 bytes) - match decode_qm_intraday_bytes(&[0x10, 0x00]) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!(detail.contains("truncated"), "detail={detail}"); - } - other => panic!("expected CorruptBson for truncated header, got {other:?}"), - } - - // Declared length < 5 - match decode_qm_intraday_bytes(&[4, 0, 0, 0]) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!(detail.contains('4'), "detail={detail}"); - } - other => panic!("expected CorruptBson for length < 5, got {other:?}"), - } - - let valid = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); - - // Truncated body - let truncated = &valid.as_bytes()[..valid.as_bytes().len() - 3]; - match decode_qm_intraday_bytes(truncated) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!(detail.contains("truncated"), "detail={detail}"); - } - other => panic!("expected CorruptBson for truncated body, got {other:?}"), - } - - // Trailing extra bytes on single-doc decode - let mut with_trailing = valid.as_bytes().to_vec(); - with_trailing.push(0x00); - match decode_qm_intraday_bytes(&with_trailing) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!(detail.contains("length"), "detail={detail}"); - } - other => panic!("expected CorruptBson for trailing bytes, got {other:?}"), - } - - // Malformed BSON (bad trailing NUL terminator) - let mut bad_term = valid.as_bytes().to_vec(); - *bad_term.last_mut().unwrap() = 0xFF; - match decode_qm_intraday_bytes(&bad_term) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, .. }) => {} - other => panic!("expected CorruptBson for bad terminator, got {other:?}"), - } -} - -#[test] -fn decodes_mixed_buffer_deterministically_recovers_past_corrupt_frame_and_merges_stats() { - // Empty buffer -> zero stats and no callbacks. - let mut empty_rows = 0usize; - let mut empty_errs = 0usize; - let empty_stats = decode_qm_intraday_buffer(&[], |_| empty_rows += 1, |_, _| empty_errs += 1); - assert_eq!(empty_stats, BsonQmIntradayDecodeStats::default()); - assert_eq!(empty_stats.rejected_total(), 0); - assert_eq!(empty_rows, 0); - assert_eq!(empty_errs, 0); - - let valid1 = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); - let empty_key = make_valid_doc(" ", 1_717_767_060_000, 84.5, 85.0, 84.0, 84.8, 500.0); - let bad_ts = make_doc_with_timestamp(RawBsonRef::DateTime(DateTime::from_millis(-10))); - let bad_price = make_valid_doc("SHOP:CA", 1_717_767_180_000, 0.0, 85.0, 83.0, 84.0, 200.0); - - let mut wrong_type = RawDocumentBuf::new(); - wrong_type.append(cstr!("qmSearchCode"), "SHOP:CA"); - wrong_type.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_240_000)); - wrong_type.append(cstr!("open"), RawBsonRef::Null); - wrong_type.append(cstr!("high"), 85.0_f64); - wrong_type.append(cstr!("low"), 83.0_f64); - wrong_type.append(cstr!("close"), 84.0_f64); - wrong_type.append(cstr!("sharevolume"), 200.0_f64); - - let mut missing_field = RawDocumentBuf::new(); - missing_field.append(cstr!("qmSearchCode"), "SHOP:CA"); - missing_field.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_300_000)); - missing_field.append(cstr!("open"), 84.0_f64); - missing_field.append(cstr!("high"), 85.0_f64); - missing_field.append(cstr!("low"), 83.0_f64); - missing_field.append(cstr!("close"), 84.0_f64); - - // Valid length-framed doc whose trailing terminator is corrupt -> CorruptBson, but buffer - // iteration recovers past the known frame boundary and decodes valid2 after it. - let mut corrupt_framed = valid1.as_bytes().to_vec(); - *corrupt_framed.last_mut().unwrap() = 0xAA; - - let valid2 = make_valid_doc("X:CA", 1_717_767_360_000, 39.5, 40.0, 39.25, 39.75, -0.0); - - let mut batch1 = Vec::new(); - batch1.extend_from_slice(valid1.as_bytes()); - let off_empty = batch1.len(); - batch1.extend_from_slice(empty_key.as_bytes()); - let off_bad_ts = batch1.len(); - batch1.extend_from_slice(bad_ts.as_bytes()); - let off_bad_price = batch1.len(); - batch1.extend_from_slice(bad_price.as_bytes()); - - let mut batch2 = Vec::new(); - batch2.extend_from_slice(wrong_type.as_bytes()); - batch2.extend_from_slice(missing_field.as_bytes()); - batch2.extend_from_slice(&corrupt_framed); - batch2.extend_from_slice(valid2.as_bytes()); - - let mut full_buf = Vec::new(); - full_buf.extend_from_slice(&batch1); - let off_wrong_type = full_buf.len(); - full_buf.extend_from_slice(wrong_type.as_bytes()); - let off_missing = full_buf.len(); - full_buf.extend_from_slice(missing_field.as_bytes()); - let off_corrupt = full_buf.len(); - full_buf.extend_from_slice(&corrupt_framed); - full_buf.extend_from_slice(valid2.as_bytes()); - let off_trunc = full_buf.len(); - // Truncated tail: stops cleanly and is counted once. - full_buf.extend_from_slice(&valid2.as_bytes()[..10]); - - let run_once = |buf: &[u8]| { - let mut rows = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_qm_intraday_buffer( - buf, - |bar| { - rows.push(( - bar.qm_search_code.to_owned(), - bar.ts, - bar.close.to_bits(), - bar.volume.to_bits(), - )) - }, - |offset, err| errors.push((offset, err)), - ); - (rows, errors, stats) - }; - - let (rows_a, errs_a, stats_a) = run_once(&full_buf); - let (rows_b, errs_b, stats_b) = run_once(&full_buf); - - // Deterministic replay produces identical rows, errors, offsets, and stats. - assert_eq!(rows_a, rows_b); - assert_eq!(errs_a, errs_b); - assert_eq!(stats_a, stats_b); - - assert_eq!( - rows_a, - vec![ - ( - "SHOP:CA".to_owned(), - 1_717_767_000_000_000, - 84.5_f64.to_bits(), - 1000.0_f64.to_bits(), - ), - ( - "X:CA".to_owned(), - 1_717_767_360_000_000, - 39.75_f64.to_bits(), - 0.0_f64.to_bits(), - ), - ] - ); - - assert_eq!(stats_a.docs_seen, 9); - assert_eq!(stats_a.rows_decoded, 2); - assert_eq!(stats_a.rejected_empty_field, 1); - assert_eq!(stats_a.rejected_invalid_timestamp, 1); - assert_eq!(stats_a.rejected_invalid_number, 1); - assert_eq!(stats_a.rejected_wrong_type, 1); - assert_eq!(stats_a.rejected_missing_field, 1); - assert_eq!(stats_a.rejected_corrupt_document, 2); // corrupt_framed + truncated tail - assert_eq!(stats_a.rejected_total(), 7); - assert_eq!( - stats_a.docs_seen, - stats_a.rows_decoded + stats_a.rejected_total() - ); - - assert_eq!(errs_a.len(), 7); - assert_eq!(errs_a[0].0, off_empty); - assert_eq!( - errs_a[0].1, - BsonQmIntradayError::EmptyField { - field: FIELD_QM_SEARCH_CODE - } - ); - assert_eq!(errs_a[1].0, off_bad_ts); - assert_eq!( - errs_a[1].1, - BsonQmIntradayError::InvalidTimestamp { - field: FIELD_TIMESTAMP - } - ); - assert_eq!(errs_a[2].0, off_bad_price); - assert!(matches!( - errs_a[2].1, - BsonQmIntradayError::InvalidNumber { - field: FIELD_OPEN, - .. - } - )); - assert_eq!(errs_a[3].0, off_wrong_type); - assert_eq!( - errs_a[3].1, - BsonQmIntradayError::WrongType { - field: FIELD_OPEN, - actual: ElementType::Null, - } - ); - assert_eq!(errs_a[4].0, off_missing); - assert_eq!( - errs_a[4].1, - BsonQmIntradayError::MissingField { - field: FIELD_SHARE_VOLUME - } - ); - assert_eq!(errs_a[5].0, off_corrupt); - assert!(matches!( - &errs_a[5].1, - BsonQmIntradayError::CorruptBson { offset, .. } if *offset == off_corrupt - )); - assert_eq!(errs_a[6].0, off_trunc); - assert!(matches!( - &errs_a[6].1, - BsonQmIntradayError::CorruptBson { offset, detail } - if *offset == off_trunc && detail.contains("truncated") - )); - - // Verify merge and AddAssign match decoding frame-aligned batches separately. - let mut batch2_with_trunc = batch2.clone(); - batch2_with_trunc.extend_from_slice(&valid2.as_bytes()[..10]); - let s1 = decode_qm_intraday_buffer(&batch1, |_| {}, |_, _| {}); - let s2 = decode_qm_intraday_buffer(&batch2_with_trunc, |_| {}, |_, _| {}); - let mut merged = s1; - merged.merge(&s2); - assert_eq!(merged, stats_a); - - let mut added = s1; - added += s2; - assert_eq!(added, stats_a); -} - -// --- QA edge cases (T-150) ------------------------------------------------------------------- - -fn find_marker(bytes: &[u8], marker: &[u8]) -> usize { - bytes - .windows(marker.len()) - .position(|w| w == marker) - .expect("marker must exist in fixture bytes") -} - -#[test] -fn corrupt_bytes_inside_an_adjusted_field_reject_the_document_as_corrupt_bson() { - // Proves adjusted fields are validated (not blindly skipped) even though they are never read: - // flip `adjustedclose` from Double (0x01) to String (0x02) so its 8 payload bytes are read as a - // bogus string length. - let mut doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 84.0, 85.0, 83.5, 84.5, 1000.0); - doc.append(cstr!("adjustedclose"), 8.45_f64); - doc.append(cstr!("avolume"), 10_000.0_f64); - let mut bytes = doc.as_bytes().to_vec(); - let key_pos = find_marker(&bytes, b"adjustedclose\0"); - assert_eq!( - bytes[key_pos - 1], - 0x01, - "fixture: element type byte precedes key" - ); - bytes[key_pos - 1] = 0x02; - - match decode_qm_intraday_bytes(&bytes) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, .. }) => {} - other => panic!("expected CorruptBson for corrupt adjustedclose, got {other:?}"), - } -} - -#[test] -fn adjusted_fields_of_any_type_or_value_do_not_affect_raw_decode() { - // Adjusted fields that would fail raw validation (Null, negative, NaN, string) must be ignored. - let mut doc = make_valid_doc( - "RY:CA", - 1_717_767_000_000, - 130.0, - 131.0, - 129.5, - 130.5, - 2_000.0, - ); - doc.append(cstr!("adjustedopen"), RawBsonRef::Null); - doc.append(cstr!("adjustedhigh"), -1.0_f64); - doc.append(cstr!("adjustedlow"), f64::NAN); - doc.append(cstr!("adjustedclose"), "n/a"); - doc.append(cstr!("avolume"), -5_i64); - - let bar = decode_qm_intraday_doc(&doc).unwrap(); - assert_eq!(bar.qm_search_code, "RY:CA"); - assert_eq!(bar.ts, 1_717_767_000_000_000); - assert_eq!(bar.open.to_bits(), 130.0_f64.to_bits()); - assert_eq!(bar.high.to_bits(), 131.0_f64.to_bits()); - assert_eq!(bar.low.to_bits(), 129.5_f64.to_bits()); - assert_eq!(bar.close.to_bits(), 130.5_f64.to_bits()); - assert_eq!(bar.volume.to_bits(), 2_000.0_f64.to_bits()); -} - -#[test] -fn adjusted_only_document_is_missing_raw_fields_not_silently_substituted() { - // A doc carrying only adjusted prices/volume must not fall back to them. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("adjustedopen"), 8.4_f64); - doc.append(cstr!("adjustedhigh"), 8.5_f64); - doc.append(cstr!("adjustedlow"), 8.3_f64); - doc.append(cstr!("adjustedclose"), 8.45_f64); - doc.append(cstr!("avolume"), 125_000.0_f64); - assert_eq!( - decode_qm_intraday_doc(&doc).unwrap_err(), - BsonQmIntradayError::MissingField { field: FIELD_OPEN } - ); - - // Same with only `volume`/`avolume` instead of `sharevolume`. - let mut doc = make_doc_without_sharevolume(); - doc.append(cstr!("volume"), 100.0_f64); - doc.append(cstr!("avolume"), 100.0_f64); - assert_eq!( - decode_qm_intraday_doc(&doc).unwrap_err(), - BsonQmIntradayError::MissingField { - field: FIELD_SHARE_VOLUME - } - ); -} - -fn make_doc_without_sharevolume() -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc -} - -#[test] -fn field_names_match_case_sensitively() { - // `Open` / `QmSearchCode` are unknown fields, so the real ones are reported missing. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("QmSearchCode"), "SHOP:CA"); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("Open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("sharevolume"), 1.0_f64); - assert_eq!( - decode_qm_intraday_doc(&doc).unwrap_err(), - BsonQmIntradayError::MissingField { field: FIELD_OPEN } - ); -} - -#[test] -fn field_order_does_not_change_the_decoded_bar() { - let forward = make_valid_doc( - "SHOP:CA", - 1_717_767_000_123, - 84.0, - 85.0, - 83.5, - 84.5, - 1_000.0, - ); - - let mut reversed = RawDocumentBuf::new(); - reversed.append(cstr!("sharevolume"), 1_000.0_f64); - reversed.append(cstr!("close"), 84.5_f64); - reversed.append(cstr!("low"), 83.5_f64); - reversed.append(cstr!("high"), 85.0_f64); - reversed.append(cstr!("open"), 84.0_f64); - reversed.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_123)); - reversed.append(cstr!("qmSearchCode"), "SHOP:CA"); - - assert_eq!( - decode_qm_intraday_doc(&forward).unwrap(), - decode_qm_intraday_doc(&reversed).unwrap() - ); -} - -#[test] -fn missing_field_precedence_follows_declared_order_and_semantic_error_beats_missing() { - // close and sharevolume both missing -> close (earlier in declared order) is reported. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "SHOP:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - assert_eq!( - decode_qm_intraday_doc(&doc).unwrap_err(), - BsonQmIntradayError::MissingField { field: FIELD_CLOSE } - ); - - // A semantic error on a late field wins over an earlier-ordered missing field. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_717_767_000_000)); - doc.append(cstr!("sharevolume"), -1.0_f64); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - assert!( - matches!( - err, - BsonQmIntradayError::InvalidNumber { - field: FIELD_SHARE_VOLUME, - .. - } - ), - "got {err:?}" - ); -} - -#[test] -fn invalid_duplicate_after_valid_value_still_rejects_the_document() { - // Valid open followed by an invalid duplicate open: the semantic error must be kept. - let mut doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - doc.append(cstr!("open"), 0.0_f64); - let err = decode_qm_intraday_doc(&doc).unwrap_err(); - assert!( - matches!(err, BsonQmIntradayError::InvalidNumber { field: FIELD_OPEN, value } if value == 0.0), - "got {err:?}" - ); -} - -#[test] -fn malformed_utf8_in_qm_search_code_is_corrupt_bson_naming_the_field() { - let doc = make_valid_doc("SHOP:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let mut bytes = doc.as_bytes().to_vec(); - let pos = find_marker(&bytes, b"SHOP:CA"); - bytes[pos + 1] = 0xFF; - match decode_qm_intraday_bytes(&bytes) { - Err(BsonQmIntradayError::CorruptBson { offset: 0, detail }) => { - assert!(detail.contains(FIELD_QM_SEARCH_CODE), "detail={detail}"); - } - other => panic!("expected CorruptBson for invalid UTF-8 key, got {other:?}"), - } -} - -#[test] -fn non_ascii_and_large_integer_values_are_preserved_exactly() { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), "BCE.PR.Ä:CA"); - doc.append(cstr!("timestamp"), DateTime::from_millis(1_735_689_599_999)); - doc.append(cstr!("open"), 1_i32); - doc.append(cstr!("high"), i32::MAX); - doc.append(cstr!("low"), 1_i64); - doc.append(cstr!("close"), 9_007_199_254_740_992_i64); // 2^53, exact in f64 - doc.append(cstr!("sharevolume"), i64::MAX); - - let bar = decode_qm_intraday_doc(&doc).unwrap(); - assert_eq!(bar.qm_search_code, "BCE.PR.Ä:CA"); - assert_eq!(bar.ts, 1_735_689_599_999_000); - assert_eq!(bar.open, 1.0); - assert_eq!(bar.high, f64::from(i32::MAX)); - assert_eq!(bar.low, 1.0); - assert_eq!(bar.close, 9_007_199_254_740_992.0); - assert_eq!(bar.volume, i64::MAX as f64); - assert!(bar.volume.is_finite()); -} - -#[test] -fn display_messages_name_field_and_domain() { - let vol = BsonQmIntradayError::InvalidNumber { - field: FIELD_SHARE_VOLUME, - value: -1.0, - } - .to_string(); - assert!(vol.contains("sharevolume") && vol.contains(">= 0"), "{vol}"); - let price = BsonQmIntradayError::InvalidNumber { - field: FIELD_HIGH, - value: 0.0, - } - .to_string(); - assert!( - price.contains("high") && price.contains("> 0") && !price.contains(">= 0"), - "{price}" - ); - let corrupt = BsonQmIntradayError::CorruptBson { - offset: 77, - detail: "x".into(), - } - .to_string(); - assert!(corrupt.contains("77"), "{corrupt}"); -} - -#[test] -fn buffer_stops_at_unrecoverable_frame_length_counting_it_once_and_keeps_earlier_rows() { - let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let b = make_valid_doc("B:CA", 1_717_767_060_000, 20.0, 21.0, 19.0, 20.5, 200.0); - let c = make_valid_doc("C:CA", 1_717_767_120_000, 30.0, 31.0, 29.0, 30.5, 300.0); - - let mut buf = Vec::new(); - buf.extend_from_slice(a.as_bytes()); - buf.extend_from_slice(b.as_bytes()); - let bad_off = buf.len(); - buf.extend_from_slice(&3_i32.to_le_bytes()); // declared length < 5: no boundary known - buf.extend_from_slice(c.as_bytes()); // must NOT be decoded (cannot resync safely) - - let mut codes = Vec::new(); - let mut errors = Vec::new(); - let stats = decode_qm_intraday_buffer( - &buf, - |bar| codes.push(bar.qm_search_code), - |off, err| errors.push((off, err)), - ); - - assert_eq!(codes, vec!["A:CA", "B:CA"]); - assert_eq!(errors.len(), 1); - assert_eq!(errors[0].0, bad_off); - assert!(matches!( - &errors[0].1, - BsonQmIntradayError::CorruptBson { offset, .. } if *offset == bad_off - )); - assert_eq!(stats.docs_seen, 3); - assert_eq!(stats.rows_decoded, 2); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); -} - -#[test] -fn buffer_rows_borrow_keys_from_the_input_buffer() { - let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let b = make_valid_doc("B:CA", 1_717_767_060_000, 20.0, 21.0, 19.0, 20.5, 200.0); - let mut buf = Vec::new(); - buf.extend_from_slice(a.as_bytes()); - buf.extend_from_slice(b.as_bytes()); - let range = buf.as_ptr_range(); - - let mut ptrs = Vec::new(); - let stats = decode_qm_intraday_buffer( - &buf, - |bar| ptrs.push(bar.qm_search_code.as_ptr()), - |_, err| panic!("unexpected error {err:?}"), - ); - assert_eq!(stats.rows_decoded, 2); - assert_eq!(ptrs.len(), 2); - for p in ptrs { - assert!( - range.contains(&p), - "key pointer {p:?} outside input buffer {range:?}" - ); - } -} - -#[test] -fn single_valid_doc_buffer_with_short_trailing_bytes_decodes_row_then_counts_truncated_tail() { - let a = make_valid_doc("A:CA", 1_717_767_000_000, 10.0, 11.0, 9.0, 10.5, 100.0); - let mut buf = a.as_bytes().to_vec(); - let tail_off = buf.len(); - buf.extend_from_slice(&[0x00, 0x00]); - - let mut rows = 0usize; - let mut errors = Vec::new(); - let stats = decode_qm_intraday_buffer(&buf, |_| rows += 1, |off, err| errors.push((off, err))); - assert_eq!(rows, 1); - assert_eq!(errors.len(), 1); - assert_eq!(errors[0].0, tail_off); - assert!(matches!( - errors[0].1, - BsonQmIntradayError::CorruptBson { .. } - )); - assert_eq!(stats.docs_seen, 2); - assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total()); -} diff --git a/tools/curate-etl/src/bson_stream.rs b/tools/curate-etl/src/bson_stream.rs index be7c201a..b8cf17f1 100644 --- a/tools/curate-etl/src/bson_stream.rs +++ b/tools/curate-etl/src/bson_stream.rs @@ -24,10 +24,6 @@ use std::io; use crate::bson_ceo_shorts::{ decode_ceo_shorts_buffer, BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, }; -use crate::bson_eod_intraday::{ - decode_eod_intraday_buffer, BsonEodIntradayDecodeStats, BsonEodIntradayError, - RawEodIntradayBar, -}; use crate::bson_eod_prices::{ decode_eod_price_buffer, BsonEodDecodeStats, BsonEodPriceError, RawEodDailyBar, }; @@ -40,9 +36,6 @@ use crate::bson_qm_events::{ BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames, QmFilingsFieldNames, RawQmEarning, RawQmFiling, }; -use crate::bson_qm_intraday::{ - decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, RawQmIntradayBar, -}; use crate::bson_qm_prices::{ decode_qm_price_buffer, BsonQmPriceDecodeStats, BsonQmPriceError, RawQmPrice, }; @@ -538,144 +531,6 @@ fn rebase_qm_error(base: u64, err: BsonQmActionError) -> BsonQmActionError { } } -#[inline] -fn rebase_eod_intraday_error(base: u64, err: BsonEodIntradayError) -> BsonEodIntradayError { - match err { - BsonEodIntradayError::TruncatedDocument { - offset, - remaining, - declared_len, - } => BsonEodIntradayError::TruncatedDocument { - offset: rebase_offset(base, offset), - remaining, - declared_len, - }, - BsonEodIntradayError::CorruptDocumentLength { - offset, - declared_len, - } => BsonEodIntradayError::CorruptDocumentLength { - offset: rebase_offset(base, offset), - declared_len, - }, - BsonEodIntradayError::CorruptBson { offset, detail } => { - BsonEodIntradayError::CorruptBson { - offset: rebase_offset(base, offset), - detail, - } - } - other => other, - } -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_intraday_buffer`], -/// accumulating [`BsonEodIntradayDecodeStats`] and rebasing per-document error offsets to -/// absolute stream byte offsets. -pub fn decode_eod_intraday_chunks( - reader: &mut RawBsonChunkReader, - mut on_bar: F, - mut on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawEodIntradayBar<'a>), - E: FnMut(u64, BsonEodIntradayError), -{ - let mut total = BsonEodIntradayDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_eod_intraday_buffer( - chunk.bytes, - &mut on_bar, - |local_offset, err| { - let abs_offset = base + local_offset as u64; - on_error(abs_offset, rebase_eod_intraday_error(base, err)); - }, - ); - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `eodIntraday1M` [`std::io::Read`] source through -/// [`decode_eod_intraday_buffer`] with bounded memory. -/// -/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset -/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`. -pub fn decode_eod_intraday_stream( - reader: R, - options: BsonStreamOptions, - on_bar: F, - on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawEodIntradayBar<'a>), - E: FnMut(u64, BsonEodIntradayError), -{ - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_eod_intraday_chunks(&mut chunk_reader, on_bar, on_error) -} - -#[inline] -fn rebase_qm_intraday_error(base: u64, err: BsonQmIntradayError) -> BsonQmIntradayError { - match err { - BsonQmIntradayError::CorruptBson { offset, detail } => BsonQmIntradayError::CorruptBson { - offset: rebase_offset(base, offset), - detail, - }, - other => other, - } -} - -/// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_qm_intraday_buffer`], -/// accumulating [`BsonQmIntradayDecodeStats`] and rebasing per-document error offsets to -/// absolute stream byte offsets. -pub fn decode_qm_intraday_chunks( - reader: &mut RawBsonChunkReader, - mut on_bar: F, - mut on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmIntradayBar<'a>), - E: FnMut(u64, BsonQmIntradayError), -{ - let mut total = BsonQmIntradayDecodeStats::default(); - while let Some(chunk) = reader.next_chunk()? { - let base = chunk.start_offset; - let chunk_stats = decode_qm_intraday_buffer( - chunk.bytes, - &mut on_bar, - |local_offset, err| { - let abs_offset = base + local_offset as u64; - on_error(abs_offset, rebase_qm_intraday_error(base, err)); - }, - ); - total += chunk_stats; - } - Ok(total) -} - -/// Streams a concatenated raw BSON `qmIntraday` [`std::io::Read`] source through -/// [`decode_qm_intraday_buffer`] with bounded memory. -/// -/// Per-document decode errors are reported to `on_error` with their absolute stream byte offset -/// and skipped; stream-level framing or I/O errors return `Err(BsonStreamError)`. -pub fn decode_qm_intraday_stream( - reader: R, - options: BsonStreamOptions, - on_bar: F, - on_error: E, -) -> Result -where - R: io::Read, - F: for<'a> FnMut(RawQmIntradayBar<'a>), - E: FnMut(u64, BsonQmIntradayError), -{ - let mut chunk_reader = RawBsonChunkReader::with_options(reader, options)?; - decode_qm_intraday_chunks(&mut chunk_reader, on_bar, on_error) -} - /// Streams chunks from an existing [`RawBsonChunkReader`] through [`decode_eod_price_buffer`], /// accumulating [`BsonEodDecodeStats`] and rebasing per-document error offsets to absolute stream /// byte offsets. diff --git a/tools/curate-etl/src/bson_stream_tests.rs b/tools/curate-etl/src/bson_stream_tests.rs index 1ca61802..500300f6 100644 --- a/tools/curate-etl/src/bson_stream_tests.rs +++ b/tools/curate-etl/src/bson_stream_tests.rs @@ -4,24 +4,17 @@ use std::io::{self, Cursor, Read}; use bson::raw::{cstr, RawDocumentBuf}; use bson::DateTime; -use crate::bson_eod_intraday::{ - decode_eod_intraday_buffer, BsonEodIntradayError, -}; use crate::bson_eod_prices::{ decode_eod_price_buffer, iter_raw_bson_docs, BsonEodDecodeStats, }; use crate::bson_qm_actions::{ decode_qm_dividend_buffer, decode_qm_split_buffer, BsonQmActionDecodeStats, }; -use crate::bson_qm_intraday::{ - decode_qm_intraday_buffer, BsonQmIntradayDecodeStats, BsonQmIntradayError, -}; use crate::bson_qm_prices::{decode_qm_price_buffer, BsonQmPriceError}; use crate::bson_stream::{ - decode_eod_intraday_chunks, decode_eod_intraday_stream, decode_eod_price_stream, - decode_qm_dividend_stream, decode_qm_intraday_chunks, decode_qm_intraday_stream, - decode_qm_price_stream, decode_qm_split_stream, BsonStreamError, BsonStreamOptions, - RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, + decode_eod_price_stream, decode_qm_dividend_stream, decode_qm_price_stream, + decode_qm_split_stream, BsonStreamError, BsonStreamOptions, RawBsonChunkReader, + DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, }; #[derive(Debug, Clone, Copy)] @@ -2120,345 +2113,3 @@ fn decode_qm_price_stream_matches_buffer_rebases_offsets_and_fails_on_framing() .unwrap_err(); assert!(matches!(err, BsonStreamError::TruncatedDocument { .. })); } - -#[test] -fn decode_eod_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() { - let make_doc = |code: &str, ts: i64, open: f64, close: f64, vol: f64| -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), ts); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), open.max(close) + 0.5); - doc.append(cstr!("low"), open.min(close) - 0.5); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), vol); - doc.into_bytes() - }; - - let mut fixture = Vec::new(); - fixture.extend_from_slice(&make_doc("NVDA.US", 1_717_767_000, 120.0, 120.5, 1000.0)); - fixture.extend_from_slice(&make_doc("AAPL.US", 1_717_767_060, 195.0, 195.25, 0.0)); - - // Semantic error: invalid timestamp (negative) - let bad_ts_offset = fixture.len() as u64; - fixture.extend_from_slice(&make_doc("NVDA.US", -60, 120.0, 120.5, 100.0)); - - // Valid length-framed doc with corrupt trailing terminator -> CorruptBson with embedded offset - let mut corrupt_bytes = make_doc("MSFT.US", 1_717_767_120, 420.0, 421.0, 500.0); - *corrupt_bytes.last_mut().unwrap() = 0xEE; - let corrupt_offset = fixture.len() as u64; - fixture.extend_from_slice(&corrupt_bytes); - - fixture.extend_from_slice(&make_doc("SHOP.TO", 1_717_767_180, 88.0, 88.4, 2500.0)); - - let mut expected_rows = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_eod_intraday_buffer( - &fixture, - |b| { - expected_rows.push(( - b.eod_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| expected_errs.push((off as u64, err)), - ); - assert_eq!(expected_stats.docs_seen, 5); - assert_eq!(expected_stats.rows_decoded, 3); - assert_eq!(expected_stats.rejected_invalid_timestamp, 1); - assert_eq!(expected_stats.rejected_corrupt_document, 1); - assert_eq!(expected_stats.rejected_total(), 2); - - // Exercise decode_eod_intraday_stream across small capacities and short reads splitting - // length prefixes and document bodies. - for (cap, step) in [(1, 1), (3, 2), (17, 3), (64, 7), (512, 13)] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: 4096, - }; - let mut got_rows = Vec::new(); - let mut got_errs = Vec::new(); - let got_stats = decode_eod_intraday_stream( - FixedStepReader::new(&fixture, step), - opts, - |b| { - got_rows.push(( - b.eod_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| got_errs.push((off, err)), - ) - .unwrap(); - - assert_eq!(got_stats, expected_stats); - assert_eq!(got_rows, expected_rows); - assert_eq!(got_errs, expected_errs); - assert_eq!(got_errs[0].0, bad_ts_offset); - assert!(matches!( - got_errs[1], - (off, BsonEodIntradayError::CorruptBson { offset, .. }) - if off == corrupt_offset && offset as u64 == corrupt_offset - )); - } - - // Exercise decode_eod_intraday_chunks directly with random read sizes and EINTR interrupts. - let opts = BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }; - let mut chunk_reader = - RawBsonChunkReader::with_options(RandomInterruptReader::new(&fixture, 0x141, true), opts) - .unwrap(); - let mut chunk_rows = Vec::new(); - let mut chunk_errs = Vec::new(); - let chunk_stats = decode_eod_intraday_chunks( - &mut chunk_reader, - |b| { - chunk_rows.push(( - b.eod_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| chunk_errs.push((off, err)), - ) - .unwrap(); - assert_eq!(chunk_stats, expected_stats); - assert_eq!(chunk_rows, expected_rows); - assert_eq!(chunk_errs, expected_errs); - - // Truncated trailing document must deliver the complete prefix first and then return - // BsonStreamError::TruncatedDocument at the exact tail offset. - let mut truncated = fixture.clone(); - let trunc_offset = truncated.len() as u64; - truncated.extend_from_slice(&120_i32.to_le_bytes()); - truncated.extend_from_slice(&[0x02, b'a', 0x00]); - let mut prefix_rows = Vec::new(); - let mut prefix_errs = Vec::new(); - let err = decode_eod_intraday_stream( - FixedStepReader::new(&truncated, 5), - BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }, - |b| { - prefix_rows.push(( - b.eod_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, e| prefix_errs.push((off, e)), - ) - .unwrap_err(); - assert_eq!(prefix_rows, expected_rows); - assert_eq!(prefix_errs, expected_errs); - assert!(matches!( - err, - BsonStreamError::TruncatedDocument { - offset, - remaining: 7, - declared_len: Some(120), - } if offset == trunc_offset - )); -} - -#[test] -fn decode_qm_intraday_chunks_and_stream_match_buffer_and_rebase_offsets() { - let make_doc = |code: &str, ts_ms: i64, open: f64, close: f64, vol: f64| -> Vec { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("timestamp"), DateTime::from_millis(ts_ms)); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), open.max(close) + 0.5); - doc.append(cstr!("low"), open.min(close) - 0.5); - doc.append(cstr!("close"), close); - doc.append(cstr!("sharevolume"), vol); - // Include adjusted fields that must be validated and ignored. - doc.append(cstr!("adjustedopen"), open / 10.0); - doc.append(cstr!("adjustedclose"), close / 10.0); - doc.append(cstr!("avolume"), vol * 10.0); - doc.into_bytes() - }; - - // Empty input returns zeroed stats with zero callbacks. - { - let mut empty_rows = 0usize; - let mut empty_errs = 0usize; - let stats = decode_qm_intraday_stream( - Cursor::new(Vec::::new()), - BsonStreamOptions::default(), - |_| empty_rows += 1, - |_, _| empty_errs += 1, - ) - .unwrap(); - assert_eq!(stats, BsonQmIntradayDecodeStats::default()); - assert_eq!(empty_rows, 0); - assert_eq!(empty_errs, 0); - } - - let mut fixture = Vec::new(); - fixture.extend_from_slice(&make_doc("NVDA", 1_717_767_000_000, 1200.0, 1205.0, 1_000.0)); - fixture.extend_from_slice(&make_doc("AAPL", 1_717_767_060_000, 195.0, 195.25, 0.0)); - - // Semantic error: invalid timestamp (negative DateTime millis). - let bad_ts_offset = fixture.len() as u64; - fixture.extend_from_slice(&make_doc("NVDA", -60_000, 1200.0, 1205.0, 100.0)); - - // Valid length-framed doc with corrupt trailing terminator -> CorruptBson with embedded offset. - let mut corrupt_bytes = make_doc("MSFT", 1_717_767_120_000, 420.0, 421.0, 500.0); - *corrupt_bytes.last_mut().unwrap() = 0xEE; - let corrupt_offset = fixture.len() as u64; - fixture.extend_from_slice(&corrupt_bytes); - - fixture.extend_from_slice(&make_doc("SHOP:CA", 1_717_767_180_000, 88.0, 88.4, 2_500.0)); - - let mut expected_rows = Vec::new(); - let mut expected_errs = Vec::new(); - let expected_stats = decode_qm_intraday_buffer( - &fixture, - |b| { - expected_rows.push(( - b.qm_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| expected_errs.push((off as u64, err)), - ); - assert_eq!(expected_stats.docs_seen, 5); - assert_eq!(expected_stats.rows_decoded, 3); - assert_eq!(expected_stats.rejected_invalid_timestamp, 1); - assert_eq!(expected_stats.rejected_corrupt_document, 1); - assert_eq!(expected_stats.rejected_total(), 2); - - // Exercise decode_qm_intraday_stream across small capacities and short reads splitting - // length prefixes and document bodies. - for (cap, step) in [(1, 1), (3, 2), (17, 3), (64, 7), (512, 13)] { - let opts = BsonStreamOptions { - chunk_capacity_bytes: cap, - max_doc_bytes: 4096, - }; - let mut got_rows = Vec::new(); - let mut got_errs = Vec::new(); - let got_stats = decode_qm_intraday_stream( - FixedStepReader::new(&fixture, step), - opts, - |b| { - got_rows.push(( - b.qm_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| got_errs.push((off, err)), - ) - .unwrap(); - - assert_eq!(got_stats, expected_stats); - assert_eq!(got_rows, expected_rows); - assert_eq!(got_errs, expected_errs); - assert_eq!(got_errs[0].0, bad_ts_offset); - assert!(matches!( - got_errs[1], - (off, BsonQmIntradayError::CorruptBson { offset, .. }) - if off == corrupt_offset && offset as u64 == corrupt_offset - )); - } - - // Exercise decode_qm_intraday_chunks directly with random read sizes and EINTR interrupts. - let opts = BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }; - let mut chunk_reader = - RawBsonChunkReader::with_options(RandomInterruptReader::new(&fixture, 0x152, true), opts) - .unwrap(); - let mut chunk_rows = Vec::new(); - let mut chunk_errs = Vec::new(); - let chunk_stats = decode_qm_intraday_chunks( - &mut chunk_reader, - |b| { - chunk_rows.push(( - b.qm_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, err| chunk_errs.push((off, err)), - ) - .unwrap(); - assert_eq!(chunk_stats, expected_stats); - assert_eq!(chunk_rows, expected_rows); - assert_eq!(chunk_errs, expected_errs); - - // Truncated trailing document must deliver the complete prefix first and then return - // BsonStreamError::TruncatedDocument at the exact tail offset. - let mut truncated = fixture.clone(); - let trunc_offset = truncated.len() as u64; - truncated.extend_from_slice(&120_i32.to_le_bytes()); - truncated.extend_from_slice(&[0x02, b'a', 0x00]); - let mut prefix_rows = Vec::new(); - let mut prefix_errs = Vec::new(); - let err = decode_qm_intraday_stream( - FixedStepReader::new(&truncated, 5), - BsonStreamOptions { - chunk_capacity_bytes: 32, - max_doc_bytes: 4096, - }, - |b| { - prefix_rows.push(( - b.qm_search_code.to_owned(), - b.ts, - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - )) - }, - |off, e| prefix_errs.push((off, e)), - ) - .unwrap_err(); - assert_eq!(prefix_rows, expected_rows); - assert_eq!(prefix_errs, expected_errs); - assert!(matches!( - err, - BsonStreamError::TruncatedDocument { - offset, - remaining: 7, - declared_len: Some(120), - } if offset == trunc_offset - )); -} diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index 11a967b9..73f35d58 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -8,8 +8,7 @@ use std::io; use std::path::{Path, PathBuf}; use crate::bench::{ - DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_1M_BENCH_ROWS, DEFAULT_BARS_BENCH_ROWS, - DEFAULT_BENCH_ROWS, + DEFAULT_ADJ_BENCH_EVENTS, 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, @@ -18,8 +17,7 @@ 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_FUNDAMENTALS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, DEFAULT_ILP_BARS_1M_BENCH_ROWS, + DEFAULT_CURATE_SHORTS_COMMAND_BENCH_ROWS, DEFAULT_EVENTS_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, @@ -72,12 +70,9 @@ pub enum CliAction { BenchAdj(usize), BenchCorporateActions(usize), BenchBars(usize), - BenchBars1m(usize), - BenchIlpBars1m(usize), BenchFx(usize), BenchShorts(usize), BenchEvents(usize), - BenchFundamentals(usize), BenchProviderMapping(usize), BenchParquetBars(usize), BenchParquetShorts(usize), @@ -133,12 +128,9 @@ 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-ilp-bars-1m [rows] Run fixed-seed QuestDB ILP v2 bars_1m encode + sharded batch benchmark (default: {DEFAULT_ILP_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\ @@ -181,12 +173,9 @@ 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-ilp-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\ @@ -1473,22 +1462,6 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-bars", _, ..] => Err("too many arguments for bench-bars".to_string()), - ["bench-bars-1m"] => Ok(CliAction::BenchBars1m(DEFAULT_BARS_1M_BENCH_ROWS)), - ["bench-bars-1m", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchBars1m(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-bars-1m", _, ..] => Err("too many arguments for bench-bars-1m".to_string()), - ["bench-ilp-bars-1m"] => Ok(CliAction::BenchIlpBars1m(DEFAULT_ILP_BARS_1M_BENCH_ROWS)), - ["bench-ilp-bars-1m", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchIlpBars1m(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-ilp-bars-1m", _, ..] => Err("too many arguments for bench-ilp-bars-1m".to_string()), ["bench-fx"] => Ok(CliAction::BenchFx(DEFAULT_FX_BENCH_ROWS)), ["bench-fx", raw] => match raw.parse::() { Ok(n) if n > 0 => Ok(CliAction::BenchFx(n)), @@ -1513,18 +1486,6 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-events", _, ..] => Err("too many arguments for bench-events".to_string()), - ["bench-fundamentals"] => Ok(CliAction::BenchFundamentals( - DEFAULT_FUNDAMENTALS_BENCH_ROWS, - )), - ["bench-fundamentals", raw] => match raw.parse::() { - Ok(n) if n > 0 => Ok(CliAction::BenchFundamentals(n)), - _ => Err(format!( - "invalid row count '{raw}' (expected a positive integer)" - )), - }, - ["bench-fundamentals", _, ..] => { - Err("too many arguments for bench-fundamentals".to_string()) - } ["bench-provider-mapping"] => Ok(CliAction::BenchProviderMapping( DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, )), @@ -2127,7 +2088,6 @@ 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")); @@ -2159,7 +2119,6 @@ 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")); @@ -2187,22 +2146,6 @@ 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!( @@ -3431,32 +3374,5 @@ 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-ilp-bars-1m - assert_eq!( - parse_args(&to_args(&["bench-ilp-bars-1m"])), - Ok(CliAction::BenchIlpBars1m(DEFAULT_ILP_BARS_1M_BENCH_ROWS)) - ); - assert_eq!( - parse_args(&to_args(&["bench-ilp-bars-1m", "2500"])), - Ok(CliAction::BenchIlpBars1m(2_500)) - ); - assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "-5"])).is_err()); - assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-ilp-bars-1m", "1", "2"])).is_err()); - - // bench-fundamentals - assert_eq!( - parse_args(&to_args(&["bench-fundamentals"])), - Ok(CliAction::BenchFundamentals(DEFAULT_FUNDAMENTALS_BENCH_ROWS)) - ); - assert_eq!( - parse_args(&to_args(&["bench-fundamentals", "2500"])), - Ok(CliAction::BenchFundamentals(2_500)) - ); - assert!(parse_args(&to_args(&["bench-fundamentals", "0"])).is_err()); - assert!(parse_args(&to_args(&["bench-fundamentals", "abc"])).is_err()); - assert!(parse_args(&to_args(&["bench-fundamentals", "1", "2"])).is_err()); } } diff --git a/tools/curate-etl/src/curate_bars_1m.rs b/tools/curate-etl/src/curate_bars_1m.rs deleted file mode 100644 index 849ebbc7..00000000 --- a/tools/curate-etl/src/curate_bars_1m.rs +++ /dev/null @@ -1,448 +0,0 @@ -//! Pure, in-memory `bars_1m` curation stage joining [`crate::bars_1m::build_bars_1m`], -//! [`crate::provider_mapping::ProviderMappingTable`], [`crate::bars_1m::check_session_closes_against_bars_1d`], -//! [`crate::ilp::IlpShardedWriter`], and [`crate::bson_stream::decode_eod_intraday_stream`]. -//! -//! # Contract & Point-in-Time Rules -//! - Calls [`build_bars_1m`] with provider source keys intact so [`SplitTable`] applies split -//! un-adjustment on each bar's **Eastern Time** `session_date` (`ex_date > session_date`) -//! before `listing_id` resolution. -//! - Resolves each built row's `(mapping_source, source_id, session_date)` to a permanent -//! `listing_id: i32` via [`ProviderMappingTable::cursor_for`] / [`crate::provider_mapping::ProviderMappingCursor::resolve`] -//! (one cursor per contiguous source-key run, since `build_bars_1m` emits rows sorted by -//! `(key, ts)` and `session_date` is monotonically non-decreasing with UTC `ts`). -//! - Re-sorts mapped rows in place by `(listing_id, ts)` and compacts cross-`source_id` -//! collisions on the same `(listing_id, ts)`: bitwise-identical OHLCV and matching `session` -//! collapse to one row (`listing_collision_collapsed`), while any OHLCV or `session` conflict -//! drops the entire group (`listing_collision_dropped`), mirroring `curate_bars_1d`. -//! - Writes sorted `Bar1mRow` rows into a caller-owned [`IlpShardedWriter`] without calling -//! [`IlpShardedWriter::finish`], allowing multiple chunks to stream through one writer. - -use std::borrow::Borrow; -use std::error::Error; -use std::fmt; -use std::hash::Hash; -use std::io::{self, Write}; - -use crate::bars::Bar1dRow; -use crate::bars_1m::{ - build_bars_1m, check_session_closes_against_bars_1d, Bar1mRow, Bars1mBuild, Bars1mError, - Bars1mStats, EodIntradayBar, IntradaySession, SessionCloseCheck, SessionCloseCutoffPolicy, - BARS_1M_SOURCE_EOD, -}; -use crate::bson_eod_intraday::BsonEodIntradayDecodeStats; -use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions}; -use crate::ilp::{IlpShardedWriter, IlpWriterError}; -use crate::provider_mapping::ProviderMappingTable; -use crate::split::SplitTable; - -/// Accounting summary produced alongside [`CurateBars1mOutput::rows`]. -/// -/// Conservation invariants: -/// - `rows_in == builder.rows_out` -/// - `rows_in == rows_out + dropped_unmapped + listing_collision_collapsed + listing_collision_dropped` -/// - `pre_rows_out + rth_rows_out + post_rows_out == rows_out` -/// - `builder` independently satisfies all [`Bars1mStats`] conservation invariants. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateBars1mStats { - pub builder: Bars1mStats, - pub rows_in: usize, - pub rows_out: usize, - pub listings_out: usize, - pub pre_rows_out: usize, - pub rth_rows_out: usize, - pub post_rows_out: usize, - pub dropped_unmapped: usize, - pub listing_collision_collapsed: usize, - pub listing_collision_dropped: usize, -} - -/// Output of [`curate_bars_1m`]: curated `bars_1m` rows keyed by permanent `listing_id`, sorted -/// and unique by `(listing_id, ts)`, plus full stage and builder statistics. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateBars1mOutput { - pub rows: Vec>, - pub stats: CurateBars1mStats, -} - -/// Typed caller errors returned by [`curate_bars_1m`]. -/// -/// Bad single rows (unmapped dates and cross-`source_id` collisions) are dropped and counted in -/// [`CurateBars1mStats`] rather than aborting the stage. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CurateBars1mError { - /// Caller-supplied `mapping_source` was empty or contained only whitespace. - EmptyMappingSource, -} - -impl fmt::Display for CurateBars1mError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Self::EmptyMappingSource => { - write!(f, "mapping_source must not be empty or blank") - } - } - } -} - -impl Error for CurateBars1mError {} - -/// Summary returned by [`curate_and_write_bars_1m`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateBars1mWriteReport { - pub curate_stats: CurateBars1mStats, - /// Number of curated rows accepted by [`IlpShardedWriter::write_bar_1m`] in this call. - pub rows_written: usize, -} - -/// Typed error returned by [`curate_and_write_bars_1m`]. -#[derive(Debug)] -pub enum CurateBars1mWriteError { - Curate(CurateBars1mError), - Ilp(IlpWriterError), -} - -impl fmt::Display for CurateBars1mWriteError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Curate(err) => write!(f, "bars_1m curation failed: {err}"), - Self::Ilp(err) => write!(f, "bars_1m ILP write failed: {err}"), - } - } -} - -impl Error for CurateBars1mWriteError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Curate(err) => Some(err), - Self::Ilp(err) => Some(err), - } - } -} - -impl From for CurateBars1mWriteError { - fn from(err: CurateBars1mError) -> Self { - Self::Curate(err) - } -} - -impl From for CurateBars1mWriteError { - fn from(err: IlpWriterError) -> Self { - Self::Ilp(err) - } -} - -/// Combined decode and write summary returned by [`curate_and_write_bars_1m_from_bson`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateBars1mBsonReport { - pub decode_stats: BsonEodIntradayDecodeStats, - pub write_report: CurateBars1mWriteReport, -} - -/// Typed error returned by [`curate_and_write_bars_1m_from_bson`]. -#[derive(Debug)] -pub enum CurateBars1mBsonError { - Stream(BsonStreamError), - Write(CurateBars1mWriteError), -} - -impl fmt::Display for CurateBars1mBsonError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Stream(err) => write!(f, "bars_1m BSON stream failed: {err}"), - Self::Write(err) => write!(f, "{err}"), - } - } -} - -impl Error for CurateBars1mBsonError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Stream(err) => Some(err), - Self::Write(err) => Some(err), - } - } -} - -impl From for CurateBars1mBsonError { - fn from(err: BsonStreamError) -> Self { - Self::Stream(err) - } -} - -impl From for CurateBars1mBsonError { - fn from(err: CurateBars1mWriteError) -> Self { - Self::Write(err) - } -} - -#[inline] -fn bar_1m_values_bit_eq(a: &Bar1mRow, b: &Bar1mRow) -> 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() - && a.session == b.session -} - -/// Maps source-keyed [`Bars1mBuild`] rows to permanent `listing_id: i32` keys via -/// `provider_mapping` on each bar's Eastern Time `session_date`, stamps `source`, re-sorts in -/// place by `(listing_id, ts)`, and compacts cross-`source_id` collisions. -pub(crate) fn map_bars_1m( - built: Bars1mBuild, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - source: &'static str, -) -> CurateBars1mOutput -where - K: Eq + AsRef, -{ - let mut stats = CurateBars1mStats { - builder: built.stats, - rows_in: built.rows.len(), - ..CurateBars1mStats::default() - }; - - let mut rows: Vec> = Vec::with_capacity(built.rows.len()); - let total_built = built.rows.len(); - let mut idx = 0usize; - - while idx < total_built { - let run_start = idx; - let run_key = &built.rows[run_start].key; - idx += 1; - while idx < total_built && built.rows[idx].key == *run_key { - idx += 1; - } - let run_end = idx; - - let mut cursor = provider_mapping.cursor_for(mapping_source, run_key.as_ref()); - if cursor.ranges().is_empty() { - stats.dropped_unmapped += run_end - run_start; - continue; - } - - for bar in &built.rows[run_start..run_end] { - let Some(listing_id) = cursor.resolve(bar.session_date) else { - stats.dropped_unmapped += 1; - continue; - }; - - rows.push(Bar1mRow { - key: listing_id, - ts: bar.ts, - session_date: bar.session_date, - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - volume: bar.volume, - session: bar.session, - source, - }); - } - } - - // Free builder rows before sorting/compacting mapped rows to cut peak RAM. - drop(built.rows); - - rows.sort_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.ts.cmp(&b.ts))); - - let mut write_idx = 0usize; - let mut read_idx = 0usize; - let total_mapped = rows.len(); - let mut last_listing_id: Option = None; - - while read_idx < total_mapped { - let listing_id = rows[read_idx].key; - let ts = rows[read_idx].ts; - let mut group_end = read_idx + 1; - while group_end < total_mapped - && rows[group_end].key == listing_id - && rows[group_end].ts == ts - { - group_end += 1; - } - let group_len = group_end - read_idx; - - let retain_group = if group_len == 1 { - true - } else { - let first = &rows[read_idx]; - let all_identical = rows[read_idx + 1..group_end] - .iter() - .all(|other| bar_1m_values_bit_eq(first, other)); - if all_identical { - stats.listing_collision_collapsed += group_len - 1; - true - } else { - stats.listing_collision_dropped += group_len; - false - } - }; - - if retain_group { - if write_idx != read_idx { - rows.swap(write_idx, read_idx); - } - if last_listing_id != Some(listing_id) { - stats.listings_out += 1; - last_listing_id = Some(listing_id); - } - match rows[write_idx].session { - IntradaySession::Pre => stats.pre_rows_out += 1, - IntradaySession::Rth => stats.rth_rows_out += 1, - IntradaySession::Post => stats.post_rows_out += 1, - } - write_idx += 1; - } - - read_idx = group_end; - } - - rows.truncate(write_idx); - stats.rows_out = rows.len(); - - CurateBars1mOutput { rows, stats } -} - -/// Pure `bars_1m` curation stage: un-adjusts source-keyed `eodIntraday1M` bars via -/// [`build_bars_1m`], resolves `(mapping_source, source_id, session_date) -> listing_id` through -/// `provider_mapping` using each bar's Eastern Time `session_date`, and emits [`Bar1mRow`] -/// rows sorted and unique by `(listing_id, ts)`. -/// -/// - Rejects empty or whitespace-only `mapping_source` with [`CurateBars1mError::EmptyMappingSource`]. -/// Non-blank `mapping_source` values are looked up verbatim. -/// - Rows whose `(mapping_source, source_id, session_date)` is not covered by any range in -/// `provider_mapping` are counted in [`CurateBars1mStats::dropped_unmapped`]. -/// - After re-sorting in place by `(listing_id, ts)`, cross-`source_id` collisions on the same -/// `(listing_id, ts)` collapse to one row when OHLCV (bitwise) and `session` match -/// (`listing_collision_collapsed += g - 1`), and drop the entire group otherwise -/// (`listing_collision_dropped += g`). -pub fn curate_bars_1m( - bars: B, - splits: &SplitTable, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, -) -> Result -where - K: Ord + Eq + Hash + Clone + AsRef, - B: IntoIterator>, -{ - if mapping_source.trim().is_empty() { - return Err(CurateBars1mError::EmptyMappingSource); - } - - let built = build_bars_1m(bars, splits); - Ok(map_bars_1m( - built, - provider_mapping, - mapping_source, - BARS_1M_SOURCE_EOD, - )) -} - -/// Thin wrapper running [`check_session_closes_against_bars_1d`] over `listing_id`-keyed curated -/// `bars_1m` rows against `listing_id`-keyed raw [`Bar1dRow`] closes using the caller's -/// [`SessionCloseCutoffPolicy`] and `rel_tolerance`. -pub fn check_curated_session_closes( - rows_1m: &[Bar1mRow], - bars_1d: I, - cutoff_policy: &SessionCloseCutoffPolicy, - rel_tolerance: f64, -) -> Result, Bars1mError> -where - R: Borrow>, - I: IntoIterator, -{ - check_session_closes_against_bars_1d(rows_1m, bars_1d, cutoff_policy, rel_tolerance) -} - -/// Runs [`curate_bars_1m`] and streams every curated row in `(listing_id, ts)` order into the -/// caller-owned [`IlpShardedWriter`] using `known_at_micros`. -/// -/// Intentionally does **not** call [`IlpShardedWriter::finish`], so callers may stream multiple -/// chunks through a single writer before flushing and collecting aggregate [`crate::ilp::IlpWriteStats`]. -pub fn curate_and_write_bars_1m( - bars: B, - splits: &SplitTable, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - writer: &mut IlpShardedWriter, - known_at_micros: i64, -) -> Result -where - W: Write + Send, - K: Ord + Eq + Hash + Clone + AsRef, - B: IntoIterator>, -{ - let curated = curate_bars_1m(bars, splits, provider_mapping, mapping_source)?; - let mut rows_written = 0usize; - for row in &curated.rows { - writer.write_bar_1m(row, known_at_micros)?; - rows_written += 1; - } - - Ok(CurateBars1mWriteReport { - curate_stats: curated.stats, - rows_written, - }) -} - -/// Decodes a concatenated raw BSON `eodIntraday1M` stream via [`decode_eod_intraday_stream`], -/// converts each valid document via [`crate::bson_eod_intraday::RawEodIntradayBar::into_eod_intraday_bar`], -/// and runs [`curate_and_write_bars_1m`] against the caller-owned [`IlpShardedWriter`]. -/// -/// Per-document semantic decode errors are counted and skipped in [`BsonEodIntradayDecodeStats`]; -/// fatal stream framing or I/O errors abort before any row from this call is written to `writer`. -/// -/// # Memory note -/// This helper buffers all decoded [`EodIntradayBar`] rows for a single call in memory -/// before curating and writing. Bounded chunking by listing or calendar month is handled by -/// higher-level runner stages. -#[allow(clippy::too_many_arguments)] -pub fn curate_and_write_bars_1m_from_bson( - reader: R, - options: BsonStreamOptions, - splits: &SplitTable, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - writer: &mut IlpShardedWriter, - known_at_micros: i64, -) -> Result -where - R: io::Read, - W: Write + Send, -{ - if mapping_source.trim().is_empty() { - return Err(CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource).into()); - } - - let mut bars: Vec> = Vec::new(); - let decode_stats = decode_eod_intraday_stream( - reader, - options, - |raw| { - bars.push(raw.into_eod_intraday_bar(|code, _| code.to_owned())); - }, - |_offset, _err| {}, - )?; - - let write_report = curate_and_write_bars_1m( - bars, - splits, - provider_mapping, - mapping_source, - writer, - known_at_micros, - )?; - - Ok(CurateBars1mBsonReport { - decode_stats, - write_report, - }) -} - -#[cfg(test)] -#[path = "curate_bars_1m_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/curate_bars_1m_tests.rs b/tools/curate-etl/src/curate_bars_1m_tests.rs deleted file mode 100644 index fc56c83e..00000000 --- a/tools/curate-etl/src/curate_bars_1m_tests.rs +++ /dev/null @@ -1,886 +0,0 @@ -use std::error::Error; -use std::io::{self, Cursor, Write}; - -use bson::raw::{cstr, RawDocumentBuf}; - -use super::*; -use crate::bars::Bar1dRow; -use crate::bars_1m::{BARS_1M_SOURCE_EOD, IntradaySession}; -use crate::ilp::{encode_bar_1m, shard_for_listing_id, IlpWriterOptions, TABLE_BARS_1M}; -use crate::provider_mapping::ProviderMappingRow; -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 bar_1m( - key: &str, - ts: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> EodIntradayBar { - EodIntradayBar { - key: key.to_string(), - ts, - open, - high, - low, - close, - volume, - } -} - -fn daily_row(listing_id: i32, session_date: i32, close: f64) -> Bar1dRow { - Bar1dRow { - key: listing_id, - session_date, - open: close, - high: close, - low: close, - close, - volume: 100_000.0, - } -} - -fn map_row( - source: &str, - source_id: &str, - valid_from: i32, - valid_to: Option, - listing_id: i32, -) -> ProviderMappingRow { - ProviderMappingRow { - source: source.to_string(), - source_id: source_id.to_string(), - valid_from, - valid_to, - listing_id, - } -} - -fn make_bson_doc( - code: &str, - timestamp_sec: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), timestamp_sec); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc -} - -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_conservation_and_order(out: &CurateBars1mOutput) { - let s = &out.stats; - assert_eq!( - s.rows_in, s.builder.rows_out, - "rows_in != builder.rows_out: {s:?}" - ); - assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); - assert_eq!( - s.rows_in, - s.rows_out - + s.dropped_unmapped - + s.listing_collision_collapsed - + s.listing_collision_dropped, - "curate_bars_1m conservation invariant failed: {s:?}" - ); - assert_eq!( - s.rows_out, - s.pre_rows_out + s.rth_rows_out + s.post_rows_out, - "session breakdown != rows_out: {s:?}" - ); - - for pair in out.rows.windows(2) { - assert!( - (pair[0].key, pair[0].ts) < (pair[1].key, pair[1].ts), - "rows not strictly sorted and unique by (listing_id, ts): {:?} vs {:?}", - (pair[0].key, pair[0].ts), - (pair[1].key, pair[1].ts) - ); - } -} - -fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool { - !needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle) -} - -#[test] -fn nexm_reverse_split_1_for_20_curates_by_listing_id_and_matches_bars_1d() { - let pre_day = day(2025, 6, 17); - let ex_date = day(2025, 6, 18); - let nexm_listing_id = 42_001; - - let splits = SplitTable::from_events([( - "NEXM.V".to_string(), - SplitEvent { - ex_date, - ratio: 0.05, - }, - )]) - .unwrap(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "NEXM.V", - day(2020, 1, 1), - None, - nexm_listing_id, - )]) - .unwrap(); - - // Pre-split adjusted 1m close = 24.29 -> raw = 24.29 * 0.05 = 1.2145, volume = 5000 / 0.05 = 100_000. - let pre_open_bar = bar_1m( - "NEXM.V", - 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", - 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", - et_ts(2025, 6, 18, 15, 59), - 24.10, - 24.50, - 23.90, - 24.30, - 12_500.0, - ); - - let out = curate_bars_1m( - [pre_open_bar, pre_close_bar.clone(), ex_bar.clone()], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&out); - assert_eq!(out.stats.rows_in, 3); - assert_eq!(out.stats.rows_out, 3); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.rth_rows_out, 3); - assert!(out.rows.iter().all(|r| r.key == nexm_listing_id)); - - let pre_close_out = &out.rows[1]; - assert_eq!(pre_close_out.key, nexm_listing_id); - 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 bar must be bitwise unchanged. - let ex_out = &out.rows[2]; - assert_eq!(ex_out.key, nexm_listing_id); - assert_eq!(ex_out.session_date, ex_date); - assert_eq!(ex_out.open.to_bits(), ex_bar.open.to_bits()); - assert_eq!(ex_out.high.to_bits(), ex_bar.high.to_bits()); - assert_eq!(ex_out.low.to_bits(), ex_bar.low.to_bits()); - assert_eq!(ex_out.close.to_bits(), ex_bar.close.to_bits()); - assert_eq!(ex_out.volume.to_bits(), ex_bar.volume.to_bits()); - - let daily_closes = [ - daily_row(nexm_listing_id, pre_day, 1.215), // ~0.041% diff vs 1.2145 - daily_row(nexm_listing_id, ex_date, 24.30), - ]; - let policy = SessionCloseCutoffPolicy::standard_rth(); - let check = check_curated_session_closes(&out.rows, &daily_closes, &policy, 0.005).unwrap(); - assert_eq!(check.stats.checked, 2); - assert_eq!(check.stats.within_tolerance, 2); - 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_matches_bars_1d_and_fails_negative_control_without_splits() { - let pre_day = day(2024, 6, 7); - let ex_date = day(2024, 6, 10); - let nvda_listing_id = 77_001; - - let splits = SplitTable::from_events([( - "NVDA.US".to_string(), - SplitEvent { - ex_date, - ratio: 10.0, - }, - )]) - .unwrap(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "NVDA.US", - day(2020, 1, 1), - None, - nvda_listing_id, - )]) - .unwrap(); - - // Pre-split adjusted 1m close = 120.888 -> raw = 1208.88; volume = 412_390 -> raw = 41_239. - let pre_bar = bar_1m( - "NVDA.US", - 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", - et_ts(2024, 6, 10, 15, 59), - 121.50, - 121.95, - 121.40, - 121.79, - 350_000.0, - ); - let daily_closes = [ - daily_row(nvda_listing_id, pre_day, 1208.88), - daily_row(nvda_listing_id, ex_date, 121.79), - ]; - let policy = SessionCloseCutoffPolicy::standard_rth(); - - let out = curate_bars_1m([pre_bar.clone(), ex_bar.clone()], &splits, &mapping, "eod").unwrap(); - assert_conservation_and_order(&out); - assert_eq!(out.stats.rows_in, 2); - assert_eq!(out.stats.rows_out, 2); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.rth_rows_out, 2); - - let pre_out = &out.rows[0]; - assert_eq!(pre_out.key, nvda_listing_id); - assert_eq!(pre_out.session_date, pre_day); - assert_rel_eq(pre_out.open, 1205.0, 1e-12); - assert_rel_eq(pre_out.high, 1210.0, 1e-12); - assert_rel_eq(pre_out.low, 1204.0, 1e-12); - assert_rel_eq(pre_out.close, 1208.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, - ); - - let ex_out = &out.rows[1]; - assert_eq!(ex_out.key, nvda_listing_id); - assert_eq!(ex_out.session_date, ex_date); - assert_eq!(ex_out.open.to_bits(), ex_bar.open.to_bits()); - assert_eq!(ex_out.high.to_bits(), ex_bar.high.to_bits()); - assert_eq!(ex_out.low.to_bits(), ex_bar.low.to_bits()); - assert_eq!(ex_out.close.to_bits(), ex_bar.close.to_bits()); - assert_eq!(ex_out.volume.to_bits(), ex_bar.volume.to_bits()); - - let check = check_curated_session_closes(&out.rows, &daily_closes, &policy, 0.005).unwrap(); - assert_eq!(check.stats.checked, 2); - assert_eq!(check.stats.within_tolerance, 2); - assert_eq!(check.stats.mismatched, 0); - assert_eq!(check.stats.unchecked, 0); - assert!(check.mismatch_samples.is_empty()); - - // Negative control: empty split table leaves pre-split 1m bar split-adjusted, so June 7 fails. - let empty_splits = SplitTable::::default(); - let unsplit_out = - curate_bars_1m([pre_bar, ex_bar], &empty_splits, &mapping, "eod").unwrap(); - assert_conservation_and_order(&unsplit_out); - let neg_check = - check_curated_session_closes(&unsplit_out.rows, &daily_closes, &policy, 0.005).unwrap(); - assert_eq!(neg_check.stats.checked, 2); - assert_eq!(neg_check.stats.within_tolerance, 1); - assert_eq!(neg_check.stats.mismatched, 1); - assert_eq!(neg_check.stats.unchecked, 0); - assert_eq!(neg_check.mismatch_samples.len(), 1); - assert_eq!(neg_check.mismatch_samples[0].key, nvda_listing_id); - assert_eq!(neg_check.mismatch_samples[0].session_date, pre_day); -} - -#[test] -fn check_curated_session_closes_forwards_early_close_cutoff_policy() { - let early_day = day(2024, 11, 29); - let listing_id = 55_001; - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "NVDA.US", - day(2020, 1, 1), - None, - listing_id, - )]) - .unwrap(); - - // 12:59 ET matches the official early-close daily close; a stray 15:59 ET print differs. - let out = curate_bars_1m( - [ - bar_1m("NVDA.US", et_ts(2024, 11, 29, 12, 59), 138.0, 138.5, 137.8, 138.25, 10_000.0), - bar_1m("NVDA.US", et_ts(2024, 11, 29, 15, 59), 145.0, 145.5, 144.8, 145.00, 100.0), - ], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&out); - - let daily = [daily_row(listing_id, early_day, 138.25)]; - let early_policy = SessionCloseCutoffPolicy::standard_rth() - .with_date_cutoff(early_day, et_ts(2024, 11, 29, 13, 0)); - let early_check = - check_curated_session_closes(&out.rows, &daily, &early_policy, 0.005).unwrap(); - assert_eq!(early_check.stats.checked, 1); - assert_eq!(early_check.stats.within_tolerance, 1); - assert_eq!(early_check.stats.mismatched, 0); - assert_eq!(early_check.stats.unchecked, 0); - - // Without the early-close cutoff, the 15:59 ET bar is selected and mismatches. - let standard_policy = SessionCloseCutoffPolicy::standard_rth(); - let standard_check = - check_curated_session_closes(&out.rows, &daily, &standard_policy, 0.005).unwrap(); - assert_eq!(standard_check.stats.checked, 1); - assert_eq!(standard_check.stats.within_tolerance, 0); - assert_eq!(standard_check.stats.mismatched, 1); -} - -#[test] -fn unmapped_source_code_is_dropped_and_conserved() { - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "OTHER.US", - day(2020, 1, 1), - None, - 101, - )]) - .unwrap(); - - let out = curate_bars_1m( - [bar_1m( - "MISSING.US", - et_ts(2024, 6, 10, 10, 0), - 10.0, - 10.5, - 9.8, - 10.2, - 1_000.0, - )], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&out); - assert!(out.rows.is_empty()); - assert_eq!(out.stats.rows_in, 1); - assert_eq!(out.stats.rows_out, 0); - assert_eq!(out.stats.dropped_unmapped, 1); - assert_eq!(out.stats.listings_out, 0); - assert_eq!(out.stats.listing_collision_collapsed, 0); - assert_eq!(out.stats.listing_collision_dropped, 0); -} - -#[test] -fn mapping_range_change_uses_et_session_date_and_sorts_by_listing_id_and_ts() { - let d1 = day(2024, 6, 10); - let d2 = day(2024, 6, 11); - let earlier_listing_id = 200; // intentionally larger than later_listing_id - let later_listing_id = 100; - - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::from_rows([ - map_row("eod", "REUSED.US", day(2020, 1, 1), Some(d1), earlier_listing_id), - map_row("eod", "REUSED.US", d2, None, later_listing_id), - ]) - .unwrap(); - - // 20:30 ET on 2024-06-10 (EDT = UTC-4) is 00:30 UTC on 2024-06-11. - // Lookup must use ET session_date (d1), not UTC date (d2). - let pre_change_late_et = bar_1m( - "REUSED.US", - et_ts(2024, 6, 10, 20, 30), - 10.0, - 10.2, - 9.9, - 10.1, - 500.0, - ); - let post_change_pre_market = bar_1m( - "REUSED.US", - et_ts(2024, 6, 11, 8, 15), - 20.0, - 20.5, - 19.8, - 20.2, - 800.0, - ); - - // Supply out of final (listing_id, ts) order (listing 200 before listing 100). - let out = curate_bars_1m( - [pre_change_late_et.clone(), post_change_pre_market.clone()], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&out); - assert_eq!(out.stats.rows_in, 2); - assert_eq!(out.stats.rows_out, 2); - assert_eq!(out.stats.listings_out, 2); - assert_eq!(out.stats.dropped_unmapped, 0); - assert_eq!(out.stats.pre_rows_out, 1); - assert_eq!(out.stats.rth_rows_out, 0); - assert_eq!(out.stats.post_rows_out, 1); - - assert_eq!(out.rows[0].key, later_listing_id); - assert_eq!(out.rows[0].session_date, d2); - assert_eq!(out.rows[0].session, IntradaySession::Pre); - assert_eq!(out.rows[0].ts, post_change_pre_market.ts); - - assert_eq!(out.rows[1].key, earlier_listing_id); - assert_eq!(out.rows[1].session_date, d1); - assert_eq!(out.rows[1].session, IntradaySession::Post); - assert_eq!(out.rows[1].ts, pre_change_late_et.ts); -} - -#[test] -fn cross_source_identical_aliases_collapse_and_conflicting_aliases_drop_group() { - let ts_same = et_ts(2024, 6, 10, 10, 15); - let listing_id = 300; - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::from_rows([ - map_row("eod", "ALIAS_A.US", day(2020, 1, 1), None, listing_id), - map_row("eod", "ALIAS_B.US", day(2020, 1, 1), None, listing_id), - map_row("eod", "ALIAS_C.US", day(2020, 1, 1), None, listing_id), - ]) - .unwrap(); - - // Identical aliases: 2 in, 1 out, 1 collapsed. - let collapsed = curate_bars_1m( - [ - bar_1m("ALIAS_A.US", ts_same, 50.0, 51.0, 49.5, 50.5, 1_200.0), - bar_1m("ALIAS_B.US", ts_same, 50.0, 51.0, 49.5, 50.5, 1_200.0), - ], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&collapsed); - assert_eq!(collapsed.stats.rows_in, 2); - assert_eq!(collapsed.stats.rows_out, 1); - assert_eq!(collapsed.stats.listings_out, 1); - assert_eq!(collapsed.stats.rth_rows_out, 1); - assert_eq!(collapsed.stats.listing_collision_collapsed, 1); - assert_eq!(collapsed.stats.listing_collision_dropped, 0); - - // Conflicting aliases: 2 matching + 1 differing -> 3 in, 0 out, 3 dropped. - let conflicted = curate_bars_1m( - [ - bar_1m("ALIAS_A.US", ts_same, 50.0, 51.0, 49.5, 50.5, 1_200.0), - bar_1m("ALIAS_B.US", ts_same, 50.0, 51.0, 49.5, 50.5, 1_200.0), - bar_1m("ALIAS_C.US", ts_same, 50.0, 51.0, 49.5, 50.75, 1_200.0), - ], - &splits, - &mapping, - "eod", - ) - .unwrap(); - assert_conservation_and_order(&conflicted); - assert!(conflicted.rows.is_empty()); - assert_eq!(conflicted.stats.rows_in, 3); - assert_eq!(conflicted.stats.rows_out, 0); - assert_eq!(conflicted.stats.listings_out, 0); - assert_eq!(conflicted.stats.listing_collision_collapsed, 0); - assert_eq!(conflicted.stats.listing_collision_dropped, 3); -} - -#[test] -fn blank_or_whitespace_mapping_source_returns_empty_mapping_source_error() { - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::default(); - - assert_eq!( - curate_bars_1m(Vec::>::new(), &splits, &mapping, ""), - Err(CurateBars1mError::EmptyMappingSource) - ); - assert_eq!( - curate_bars_1m(Vec::>::new(), &splits, &mapping, " \t\n "), - Err(CurateBars1mError::EmptyMappingSource) - ); - - let mut sink = Vec::::new(); - let mut writer = IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let err = curate_and_write_bars_1m( - Vec::>::new(), - &splits, - &mapping, - " ", - &mut writer, - 1_700_000_000_000_000, - ) - .unwrap_err(); - assert!(matches!( - err, - CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource) - )); - assert!(err.source().is_some()); -} - -#[test] -fn ilp_round_trip_matches_exact_per_shard_bytes_and_supports_multi_call_writer_reuse() { - let known_at = 1_718_050_000_000_000_i64; - let splits = SplitTable::::default(); - let listing_ids = [101_i32, 202, 303, 404, 505, 606]; - let mapping = ProviderMappingTable::from_rows(listing_ids.iter().map(|&id| { - map_row( - "eod", - &format!("SYM{id}.US"), - day(2020, 1, 1), - None, - id, - ) - })) - .unwrap(); - - let chunk1: Vec> = listing_ids - .iter() - .enumerate() - .flat_map(|(i, &id)| { - let code = format!("SYM{id}.US"); - let base = 10.0 + i as f64; - [ - bar_1m(&code, et_ts(2024, 6, 10, 9, 30), base, base + 1.0, base - 0.5, base + 0.2, 100.0), - bar_1m(&code, et_ts(2024, 6, 10, 15, 59), base + 0.2, base + 1.2, base, base + 0.8, 250.0), - ] - }) - .collect(); - - // Expected exact per-shard binary payloads from curate_bars_1m + encode_bar_1m. - let curated1 = curate_bars_1m(chunk1.clone(), &splits, &mapping, "eod").unwrap(); - assert_conservation_and_order(&curated1); - let mut expected_shards = vec![Vec::::new(); 4]; - for row in &curated1.rows { - let shard = shard_for_listing_id(row.key, 4); - encode_bar_1m(&mut expected_shards[shard], row, known_at).unwrap(); - } - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let mut s2 = Vec::new(); - let mut s3 = Vec::new(); - let (report1, stats1) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1, &mut s2, &mut s3], - IlpWriterOptions::default(), - ) - .unwrap(); - let report = - curate_and_write_bars_1m(chunk1.clone(), &splits, &mapping, "eod", &mut writer, known_at) - .unwrap(); - let stats = writer.finish().unwrap(); - (report, stats) - }; - - assert_eq!(report1.rows_written, report1.curate_stats.rows_out); - assert_eq!(stats1.rows, report1.rows_written); - assert_eq!(stats1.rows, 12); - - let actual_shards = [&s0, &s1, &s2, &s3]; - for shard in 0..4 { - assert_eq!(actual_shards[shard], &expected_shards[shard]); - if !actual_shards[shard].is_empty() { - assert!(contains_subslice( - actual_shards[shard], - TABLE_BARS_1M.as_bytes() - )); - } - } - - for &id in &listing_ids { - let target_shard = shard_for_listing_id(id, 4); - let token = format!(",listing_id={id},"); - for (shard, payload) in actual_shards.iter().enumerate() { - if shard == target_shard { - assert!( - contains_subslice(payload, token.as_bytes()), - "missing listing {id} on target shard {target_shard}" - ); - } else { - assert!( - !contains_subslice(payload, token.as_bytes()), - "listing {id} leaked onto non-target shard {shard}" - ); - } - } - } - - // Reuse one writer across two calls and verify aggregate finish() row count. - let chunk2 = vec![ - bar_1m("SYM101.US", et_ts(2024, 6, 11, 9, 30), 11.0, 11.5, 10.8, 11.2, 300.0), - bar_1m("SYM202.US", et_ts(2024, 6, 11, 16, 15), 12.0, 12.4, 11.9, 12.1, 400.0), - ]; - let mut r0 = Vec::new(); - let mut r1 = Vec::new(); - let mut r2 = Vec::new(); - let mut r3 = Vec::new(); - let mut writer = IlpShardedWriter::new( - vec![&mut r0, &mut r1, &mut r2, &mut r3], - IlpWriterOptions::default(), - ) - .unwrap(); - let rep_a = - curate_and_write_bars_1m(chunk1, &splits, &mapping, "eod", &mut writer, known_at).unwrap(); - let rep_b = - curate_and_write_bars_1m(chunk2, &splits, &mapping, "eod", &mut writer, known_at).unwrap(); - let agg_stats = writer.finish().unwrap(); - assert_eq!(agg_stats.rows, rep_a.rows_written + rep_b.rows_written); - assert_eq!(agg_stats.rows, 14); -} - -struct FailingSink { - fail_on_write: bool, -} - -impl Write for FailingSink { - fn write(&mut self, buf: &[u8]) -> io::Result { - if self.fail_on_write { - Err(io::Error::new( - io::ErrorKind::BrokenPipe, - "simulated sink write failure", - )) - } else { - Ok(buf.len()) - } - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -#[test] -fn writer_io_failure_surfaces_typed_error_with_source_and_poisons_writer() { - let listing_id = 909; - let target_shard = shard_for_listing_id(listing_id, 4); - let splits = SplitTable::::default(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "FAIL.US", - day(2020, 1, 1), - None, - listing_id, - )]) - .unwrap(); - - let sinks: Vec = (0..4) - .map(|idx| FailingSink { - fail_on_write: idx == target_shard, - }) - .collect(); - let mut writer = IlpShardedWriter::new( - sinks, - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - - let bar = bar_1m("FAIL.US", et_ts(2024, 6, 10, 10, 0), 10.0, 10.5, 9.9, 10.2, 500.0); - let err = curate_and_write_bars_1m( - [bar.clone()], - &splits, - &mapping, - "eod", - &mut writer, - 1_718_050_000_000_000, - ) - .unwrap_err(); - - match &err { - CurateBars1mWriteError::Ilp(IlpWriterError::Io { shard, source }) => { - assert_eq!(*shard, target_shard); - assert_eq!(source.kind(), io::ErrorKind::BrokenPipe); - } - other => panic!("expected Ilp(Io) error, got {other:?}"), - } - let ilp_source = err.source().expect("write error exposes IlpWriterError"); - assert!(ilp_source.source().is_some()); - - // Subsequent call must observe the writer's poisoned state. - let poisoned_err = curate_and_write_bars_1m( - [bar], - &splits, - &mapping, - "eod", - &mut writer, - 1_718_050_000_000_000, - ) - .unwrap_err(); - assert!(matches!( - poisoned_err, - CurateBars1mWriteError::Ilp(IlpWriterError::Poisoned { failed_shard }) - if failed_shard == target_shard - )); -} - -#[test] -fn bson_stream_counts_rejected_doc_and_aborts_cleanly_on_truncated_tail() { - let listing_id = 77_001; - let known_at = 1_718_050_000_000_000_i64; - let splits = SplitTable::from_events([( - "NVDA.US".to_string(), - SplitEvent { - ex_date: day(2024, 6, 10), - ratio: 10.0, - }, - )]) - .unwrap(); - let mapping = ProviderMappingTable::from_rows([map_row( - "eod", - "NVDA.US", - day(2020, 1, 1), - None, - listing_id, - )]) - .unwrap(); - - let doc1 = make_bson_doc( - "NVDA.US", - et_ts(2024, 6, 7, 15, 59) / 1_000_000, - 120.50, - 121.00, - 120.40, - 120.888, - 412_390.0, - ); - let doc2 = make_bson_doc( - "NVDA.US", - et_ts(2024, 6, 10, 15, 59) / 1_000_000, - 121.50, - 121.95, - 121.40, - 121.79, - 350_000.0, - ); - // Correctly framed BSON document missing required field `close`. - let mut bad_doc = RawDocumentBuf::new(); - bad_doc.append(cstr!("eodSearchCode"), "NVDA.US"); - bad_doc.append(cstr!("timestamp"), et_ts(2024, 6, 10, 10, 0) / 1_000_000); - bad_doc.append(cstr!("open"), 120.0_f64); - bad_doc.append(cstr!("high"), 121.0_f64); - bad_doc.append(cstr!("low"), 119.5_f64); - bad_doc.append(cstr!("volume"), 1_000.0_f64); - - let mut stream_bytes = Vec::new(); - stream_bytes.extend_from_slice(doc1.as_bytes()); - stream_bytes.extend_from_slice(bad_doc.as_bytes()); - stream_bytes.extend_from_slice(doc2.as_bytes()); - - let mut sink = Vec::new(); - let (report, ilp_stats) = { - let mut writer = - IlpShardedWriter::new(vec![&mut sink], IlpWriterOptions::default()).unwrap(); - let report = curate_and_write_bars_1m_from_bson( - Cursor::new(&stream_bytes), - BsonStreamOptions::default(), - &splits, - &mapping, - "eod", - &mut writer, - known_at, - ) - .unwrap(); - let stats = writer.finish().unwrap(); - (report, stats) - }; - - assert_eq!(report.decode_stats.docs_seen, 3); - assert_eq!(report.decode_stats.rows_decoded, 2); - assert_eq!(report.decode_stats.rejected_total(), 1); - assert_eq!(report.decode_stats.rejected_missing_field, 1); - assert_eq!(report.write_report.rows_written, 2); - assert_eq!(report.write_report.curate_stats.rows_out, 2); - assert_eq!(ilp_stats.rows, 2); - assert!(contains_subslice(&sink, TABLE_BARS_1M.as_bytes())); - - // Fatal framing error: truncated second document must fail and write zero rows to any sink. - let mut truncated_bytes = Vec::new(); - truncated_bytes.extend_from_slice(doc1.as_bytes()); - let doc2_bytes = doc2.as_bytes(); - truncated_bytes.extend_from_slice(&doc2_bytes[..doc2_bytes.len() / 2]); - - let mut sink_trunc = Vec::new(); - let (err, trunc_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut sink_trunc], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_bars_1m_from_bson( - Cursor::new(&truncated_bytes), - BsonStreamOptions::default(), - &splits, - &mapping, - "eod", - &mut writer, - known_at, - ) - .unwrap_err(); - let stats = writer.finish().unwrap(); - (err, stats) - }; - - assert!(matches!( - err, - CurateBars1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) - )); - assert!(err.source().is_some()); - assert_eq!(trunc_stats.rows, 0); - assert!(sink_trunc.is_empty()); -} diff --git a/tools/curate-etl/src/curate_fx_1m.rs b/tools/curate-etl/src/curate_fx_1m.rs deleted file mode 100644 index 0bdcc390..00000000 --- a/tools/curate-etl/src/curate_fx_1m.rs +++ /dev/null @@ -1,327 +0,0 @@ -//! Pure, in-memory `fx_1m` curation stage for EODHD `CAD.FOREX` 1-minute FX bars (`M2.3k`), -//! joining [`crate::bson_eod_intraday::RawEodIntradayBar`], -//! [`crate::bson_stream::decode_eod_intraday_stream`], and [`crate::ilp::IlpShardedWriter`]. -//! -//! # Contract & Point-in-Time Rules -//! - **Source selection:** accepts only rows whose `eod_search_code` matches -//! [`EOD_CAD_FOREX_CODE`] (`"CAD.FOREX"`) verbatim. Any other code is dropped and counted in -//! [`CurateFx1mStats::dropped_wrong_code`] without erroring. -//! - **No split un-adjustment, listing mapping, or session tagging:** FX trades ~24h and is not -//! subject to equity splits or `provider_mapping` ranges. Every valid `CAD.FOREX` bar is kept -//! with its UTC microsecond bar-start `ts` unchanged (preserving the source clock without -//! implying the bar's close was observable at bar start). -//! - **Rate direction & bitwise preservation:** OHLC values pass through bit-identical in CAD per -//! 1 USD (matching `fx_1d`); `volume` is ignored at the curation layer. -//! - **Canonical labels:** emits `pair = FX_PAIR_USDCAD` (`"USDCAD"`, shared with `fx_1d` so -//! daily and intraday FX tables join on the same label) and `source = FX_1M_SOURCE_EOD` -//! (`"eod"`, fitting QuestDB `SYMBOL CAPACITY 8`). -//! - **Validation precedence:** bad single bars never panic or abort the stage; each bar is -//! classified once in strict priority order: -//! 1. `dropped_wrong_code` (`eod_search_code != "CAD.FOREX"`) -//! 2. `dropped_negative_ts` (`ts < 0`) -//! 3. `dropped_invalid_ohlc` (any of `open`, `high`, `low`, `close` non-finite or `<= 0.0`) -//! 4. `dropped_high_below_bound` (`high < max(open, close, low)`) -//! 5. `dropped_low_above_bound` (`low > min(open, close)`) -//! - **Ordering & deduplication:** surviving rows are sorted ascending by `ts` and compacted in -//! place per timestamp group using `f64::to_bits` equality across all four OHLC fields: -//! bitwise-identical groups of size `n` emit one row (`duplicate_collapsed += n - 1`), while -//! conflicting groups emit zero rows (`duplicate_conflict_dropped += n`). -//! - **Writer lifecycle:** [`curate_and_write_fx_1m`] and [`curate_and_write_fx_1m_from_bson`] -//! stream sorted [`Fx1mRow`]s into a caller-owned [`IlpShardedWriter`] via -//! [`IlpShardedWriter::write_fx_1m`] without calling [`IlpShardedWriter::finish`], allowing -//! multiple chunks to share one writer. -//! -//! # Memory, Chunking & BSON Validation Boundary -//! - **In-memory sort & per-call deduplication:** sorting buffers accepted `CAD.FOREX` rows for a -//! single call in memory, and deduplication applies within that call only. Callers splitting -//! large inputs across calls must keep all copies of a timestamp in the same call and submit -//! chunks in chronological order when global ordering is required. -//! - **BSON validation boundary:** [`curate_and_write_fx_1m_from_bson`] decodes via -//! [`decode_eod_intraday_stream`], which validates non-empty `eodSearchCode`, non-negative -//! integral `timestamp`, finite positive OHLC, and finite non-negative `volume` before invoking -//! the curation accumulator. Document-level decode rejects are accounted in -//! [`BsonEodIntradayDecodeStats`] (so `decode_stats.rows_decoded == write_report.curate_stats.bars_in`), -//! while direct in-memory calls to [`build_fx_1m`] / [`curate_and_write_fx_1m`] exercise the full -//! builder validation rules and ignore `volume`. - -use std::error::Error; -use std::fmt; -use std::io::{self, Write}; - -use crate::bson_eod_intraday::{BsonEodIntradayDecodeStats, RawEodIntradayBar}; -use crate::bson_stream::{decode_eod_intraday_stream, BsonStreamError, BsonStreamOptions}; -use crate::fx::FX_PAIR_USDCAD; -use crate::ilp::{Fx1mRow, IlpShardedWriter, IlpWriterError}; -use crate::run_curate_fx::EOD_CAD_FOREX_CODE; - -/// Canonical provenance label written to [`Fx1mRow::source`] for EODHD `eodIntraday1M` FX bars -/// (`SYMBOL CAPACITY 8`). -pub const FX_1M_SOURCE_EOD: &str = "eod"; - -/// Accounting summary produced alongside [`CurateFx1mOutput::rows`]. -/// -/// Conservation invariant: -/// `bars_in == rows_out + dropped_wrong_code + dropped_negative_ts + dropped_invalid_ohlc + dropped_high_below_bound + dropped_low_above_bound + duplicate_collapsed + duplicate_conflict_dropped` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateFx1mStats { - pub bars_in: usize, - pub rows_out: usize, - pub dropped_wrong_code: usize, - pub dropped_negative_ts: usize, - pub dropped_invalid_ohlc: usize, - pub dropped_high_below_bound: usize, - pub dropped_low_above_bound: usize, - pub duplicate_collapsed: usize, - pub duplicate_conflict_dropped: usize, -} - -/// Output of [`build_fx_1m`]: curated `fx_1m` rows sorted and unique by `ts`, plus exact -/// accounting statistics. -#[derive(Debug, Clone, PartialEq)] -pub struct CurateFx1mOutput { - pub rows: Vec>, - pub stats: CurateFx1mStats, -} - -/// Summary returned by [`curate_and_write_fx_1m`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateFx1mWriteReport { - pub curate_stats: CurateFx1mStats, - /// Number of curated rows accepted by [`IlpShardedWriter::write_fx_1m`] in this call. - pub rows_written: usize, -} - -/// Combined decode and write summary returned by [`curate_and_write_fx_1m_from_bson`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateFx1mBsonReport { - pub decode_stats: BsonEodIntradayDecodeStats, - pub write_report: CurateFx1mWriteReport, -} - -/// Typed error returned by [`curate_and_write_fx_1m_from_bson`]. -#[derive(Debug)] -pub enum CurateFx1mBsonError { - Stream(BsonStreamError), - Write(IlpWriterError), -} - -impl fmt::Display for CurateFx1mBsonError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Stream(err) => write!(f, "fx_1m BSON stream failed: {err}"), - Self::Write(err) => write!(f, "fx_1m ILP write failed: {err}"), - } - } -} - -impl Error for CurateFx1mBsonError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Stream(err) => Some(err), - Self::Write(err) => Some(err), - } - } -} - -impl From for CurateFx1mBsonError { - fn from(err: BsonStreamError) -> Self { - Self::Stream(err) - } -} - -impl From for CurateFx1mBsonError { - fn from(err: IlpWriterError) -> Self { - Self::Write(err) - } -} - -#[inline] -fn is_valid_rate(rate: f64) -> bool { - rate.is_finite() && rate > 0.0 -} - -#[inline] -fn fx_1m_ohlc_bit_eq(a: &Fx1mRow<'_>, b: &Fx1mRow<'_>) -> 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() -} - -#[derive(Default)] -struct Fx1mAccumulator { - rows: Vec>, - stats: CurateFx1mStats, -} - -impl Fx1mAccumulator { - #[inline] - fn push(&mut self, bar: RawEodIntradayBar<'_>) { - self.stats.bars_in += 1; - - if bar.eod_search_code != EOD_CAD_FOREX_CODE { - self.stats.dropped_wrong_code += 1; - return; - } - if bar.ts < 0 { - self.stats.dropped_negative_ts += 1; - return; - } - if !is_valid_rate(bar.open) - || !is_valid_rate(bar.high) - || !is_valid_rate(bar.low) - || !is_valid_rate(bar.close) - { - self.stats.dropped_invalid_ohlc += 1; - return; - } - if bar.high < bar.open || bar.high < bar.close || bar.high < bar.low { - self.stats.dropped_high_below_bound += 1; - return; - } - if bar.low > bar.open || bar.low > bar.close { - self.stats.dropped_low_above_bound += 1; - return; - } - - self.rows.push(Fx1mRow { - pair: FX_PAIR_USDCAD, - ts: bar.ts, - open: bar.open, - high: bar.high, - low: bar.low, - close: bar.close, - source: FX_1M_SOURCE_EOD, - }); - } - - fn finish(mut self) -> CurateFx1mOutput { - self.rows.sort_unstable_by_key(|row| row.ts); - - let len = self.rows.len(); - let mut write_idx = 0usize; - let mut read_idx = 0usize; - - while read_idx < len { - let ts = self.rows[read_idx].ts; - let mut group_end = read_idx + 1; - while group_end < len && self.rows[group_end].ts == ts { - group_end += 1; - } - let group_len = group_end - read_idx; - let first = self.rows[read_idx]; - let all_identical = self.rows[read_idx + 1..group_end] - .iter() - .all(|other| fx_1m_ohlc_bit_eq(&first, other)); - - if all_identical { - self.stats.duplicate_collapsed += group_len - 1; - if write_idx != read_idx { - self.rows[write_idx] = first; - } - write_idx += 1; - } else { - self.stats.duplicate_conflict_dropped += group_len; - } - - read_idx = group_end; - } - - self.rows.truncate(write_idx); - self.stats.rows_out = self.rows.len(); - - CurateFx1mOutput { - rows: self.rows, - stats: self.stats, - } - } -} - -fn write_curated_fx_1m( - curated: CurateFx1mOutput, - writer: &mut IlpShardedWriter, -) -> Result { - let mut rows_written = 0usize; - for row in &curated.rows { - writer.write_fx_1m(row)?; - rows_written += 1; - } - - Ok(CurateFx1mWriteReport { - curate_stats: curated.stats, - rows_written, - }) -} - -/// Pure `eodIntraday1M` (`CAD.FOREX`) -> `fx_1m` curation builder. -/// -/// Filters to exact [`EOD_CAD_FOREX_CODE`] rows, validates timestamps and OHLC in strict priority -/// order (ignoring `volume`), sorts ascending by `ts`, and deduplicates same-`ts` groups using -/// bitwise OHLC equality. Valid OHLC and UTC microsecond `ts` pass through unchanged, stamped -/// with `pair = FX_PAIR_USDCAD` and `source = FX_1M_SOURCE_EOD`. -pub fn build_fx_1m<'a, B>(bars: B) -> CurateFx1mOutput -where - B: IntoIterator>, -{ - let mut acc = Fx1mAccumulator::default(); - for bar in bars { - acc.push(bar); - } - acc.finish() -} - -/// Runs [`build_fx_1m`] and streams every curated row in ascending `ts` order into the -/// caller-owned [`IlpShardedWriter`] via [`IlpShardedWriter::write_fx_1m`]. -/// -/// Intentionally does **not** call [`IlpShardedWriter::finish`], so callers may stream multiple -/// chunks through a single writer before flushing and collecting aggregate -/// [`crate::ilp::IlpWriteStats`]. -pub fn curate_and_write_fx_1m<'a, W, B>( - bars: B, - writer: &mut IlpShardedWriter, -) -> Result -where - W: Write + Send, - B: IntoIterator>, -{ - let curated = build_fx_1m(bars); - write_curated_fx_1m(curated, writer) -} - -/// Decodes a concatenated raw BSON `eodIntraday1M` stream via [`decode_eod_intraday_stream`], -/// feeds every decoded [`RawEodIntradayBar`] directly into the `fx_1m` curation accumulator, and -/// streams sorted curated rows into the caller-owned [`IlpShardedWriter`]. -/// -/// - Per-document semantic decode errors are counted and skipped in -/// [`BsonEodIntradayDecodeStats`]; fatal stream framing or I/O errors abort before any row from -/// this call is written to `writer`. -/// - Intentionally does **not** call [`IlpShardedWriter::finish`]. -pub fn curate_and_write_fx_1m_from_bson( - reader: R, - options: BsonStreamOptions, - writer: &mut IlpShardedWriter, -) -> Result -where - R: io::Read, - W: Write + Send, -{ - let mut acc = Fx1mAccumulator::default(); - let decode_stats = decode_eod_intraday_stream( - reader, - options, - |raw| acc.push(raw), - |_offset, _err| {}, - )?; - - let curated = acc.finish(); - let write_report = write_curated_fx_1m(curated, writer)?; - - Ok(CurateFx1mBsonReport { - decode_stats, - write_report, - }) -} - -#[cfg(test)] -#[path = "curate_fx_1m_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/curate_fx_1m_tests.rs b/tools/curate-etl/src/curate_fx_1m_tests.rs deleted file mode 100644 index 8a5622d3..00000000 --- a/tools/curate-etl/src/curate_fx_1m_tests.rs +++ /dev/null @@ -1,560 +0,0 @@ -use std::error::Error; -use std::io::{self, Cursor, Write}; - -use bson::raw::{cstr, RawDocumentBuf}; - -use super::*; -use crate::ilp::{encode_fx_1m, shard_for_fx_pair, IlpWriterOptions}; - -fn raw_bar<'a>( - code: &'a str, - ts: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> RawEodIntradayBar<'a> { - RawEodIntradayBar { - eod_search_code: code, - ts, - open, - high, - low, - close, - volume, - } -} - -fn make_eod_intraday_bson_doc( - code: &str, - ts_seconds: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("timestamp"), ts_seconds); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc -} - -fn assert_conservation_and_order(out: &CurateFx1mOutput) { - let s = &out.stats; - assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); - assert_eq!( - s.bars_in, - s.rows_out - + s.dropped_wrong_code - + s.dropped_negative_ts - + s.dropped_invalid_ohlc - + s.dropped_high_below_bound - + s.dropped_low_above_bound - + s.duplicate_collapsed - + s.duplicate_conflict_dropped, - "curate_fx_1m conservation invariant failed: {s:?}" - ); - - for pair in out.rows.windows(2) { - assert!( - pair[0].ts < pair[1].ts, - "rows not strictly ascending by ts: {} >= {}", - pair[0].ts, - pair[1].ts - ); - } - - for row in &out.rows { - assert_eq!(row.pair, FX_PAIR_USDCAD); - assert_eq!(row.source, FX_1M_SOURCE_EOD); - } -} - -struct FailingSink; - -impl Write for FailingSink { - fn write(&mut self, _buf: &[u8]) -> io::Result { - Err(io::Error::new(io::ErrorKind::BrokenPipe, "sink failure")) - } - - fn flush(&mut self) -> io::Result<()> { - Err(io::Error::new(io::ErrorKind::BrokenPipe, "flush failure")) - } -} - -#[test] -fn empty_input_returns_empty_rows_and_zeroed_stats() { - let out = build_fx_1m(std::iter::empty()); - assert!(out.rows.is_empty()); - assert_eq!(out.stats, CurateFx1mStats::default()); - assert_conservation_and_order(&out); -} - -#[test] -fn valid_out_of_order_bars_sort_preserve_ohlc_bits_keep_off_session_and_ignore_volume() { - // 2024-06-09 22:15:00 UTC (Sunday evening FX open, off equity RTH). - let ts_sunday_utc = 1_717_971_300_000_000_i64; - // 2024-06-10 03:00:00 UTC (overnight). - let ts_overnight_utc = 1_717_988_400_000_000_i64; - // Exact epoch start ts = 0 must be accepted. - let ts_zero = 0_i64; - - let b_late = raw_bar( - EOD_CAD_FOREX_CODE, - ts_overnight_utc, - 1.37654321, - 1.37712345, - 1.37611111, - 1.37689012, - -99.0, // invalid volume ignored by builder - ); - let b_zero = raw_bar( - EOD_CAD_FOREX_CODE, - ts_zero, - 1.0725, - 1.0731, - 1.0720, - 1.0728, - f64::NAN, // NaN volume ignored by builder - ); - let b_mid = raw_bar( - EOD_CAD_FOREX_CODE, - ts_sunday_utc, - 1.3750, - 1.3755, - 1.3745, - 1.3752, - f64::INFINITY, // inf volume ignored by builder - ); - // Exact-match failures (case mismatch, trailing space, different ticker) -> dropped, not errored. - let b_lowercase = raw_bar("cad.forex", ts_sunday_utc + 60_000_000, 1.37, 1.38, 1.36, 1.37, 0.0); - let b_padded = raw_bar("CAD.FOREX ", ts_sunday_utc + 120_000_000, 1.37, 1.38, 1.36, 1.37, 0.0); - let b_other = raw_bar("AAPL.US", ts_sunday_utc + 180_000_000, 195.0, 196.0, 194.5, 195.5, 1000.0); - - let out = build_fx_1m([b_late, b_lowercase, b_zero, b_other, b_mid, b_padded]); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.bars_in, 6); - assert_eq!(out.stats.rows_out, 3); - assert_eq!(out.stats.dropped_wrong_code, 3); - assert_eq!(out.stats.dropped_negative_ts, 0); - assert_eq!(out.stats.dropped_invalid_ohlc, 0); - assert_eq!(out.stats.dropped_high_below_bound, 0); - assert_eq!(out.stats.dropped_low_above_bound, 0); - assert_eq!(out.stats.duplicate_collapsed, 0); - assert_eq!(out.stats.duplicate_conflict_dropped, 0); - - let expected_inputs = [b_zero, b_mid, b_late]; - for (row, src) in out.rows.iter().zip(expected_inputs) { - assert_eq!(row.pair, FX_PAIR_USDCAD); - assert_eq!(row.source, FX_1M_SOURCE_EOD); - assert_eq!(row.ts, src.ts); - assert_eq!(row.open.to_bits(), src.open.to_bits()); - assert_eq!(row.high.to_bits(), src.high.to_bits()); - assert_eq!(row.low.to_bits(), src.low.to_bits()); - assert_eq!(row.close.to_bits(), src.close.to_bits()); - } -} - -#[test] -fn every_reject_reason_counted_separately_with_strict_precedence() { - let base_ts = 1_718_000_000_000_000_i64; - let bars = vec![ - // 1. Wrong code (also has negative ts and NaN OHLC to verify wrong_code precedence). - raw_bar("USD.FOREX", -1, f64::NAN, 1.0, 2.0, 0.0, 0.0), - // 2. Negative timestamps (second also has NaN OHLC to verify negative_ts precedence). - raw_bar(EOD_CAD_FOREX_CODE, -1, 1.35, 1.36, 1.34, 1.35, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, i64::MIN, f64::NAN, 1.36, 1.34, 1.35, 0.0), - // 3. Invalid OHLC: NaN, +inf, -inf, +0.0, -0.0, negative price. - raw_bar(EOD_CAD_FOREX_CODE, base_ts, f64::NAN, 1.36, 1.34, 1.35, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 1, 1.35, f64::INFINITY, 1.34, 1.35, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 2, 1.35, 1.36, f64::NEG_INFINITY, 1.35, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 3, 1.35, 1.36, 1.34, 0.0, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 4, -0.0, 1.36, 1.34, 1.35, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 5, 1.35, 1.36, -1.34, 1.35, 0.0), - // 4. high < max(open, close, low): - // - high < open - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 6, 1.37, 1.36, 1.34, 1.35, 0.0), - // - high < close - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 7, 1.35, 1.36, 1.34, 1.37, 0.0), - // - high < low (while high >= open/close is impossible if low > open/close, test open=close=1.35, high=1.35, low=1.36) - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 8, 1.35, 1.35, 1.36, 1.35, 0.0), - // - overlapping high < open AND low > close -> pinned to dropped_high_below_bound - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 9, 1.38, 1.36, 1.37, 1.35, 0.0), - // 5. low > min(open, close) (with high >= max(open, close, low)): - // - low > open - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 10, 1.33, 1.36, 1.34, 1.35, 0.0), - // - low > close - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 11, 1.35, 1.36, 1.34, 1.33, 0.0), - // Valid bar. - raw_bar(EOD_CAD_FOREX_CODE, base_ts + 12, 1.35, 1.36, 1.34, 1.355, 0.0), - ]; - - let out = build_fx_1m(bars); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.bars_in, 16); - assert_eq!(out.stats.dropped_wrong_code, 1); - assert_eq!(out.stats.dropped_negative_ts, 2); - assert_eq!(out.stats.dropped_invalid_ohlc, 6); - assert_eq!(out.stats.dropped_high_below_bound, 4); - assert_eq!(out.stats.dropped_low_above_bound, 2); - assert_eq!(out.stats.duplicate_collapsed, 0); - assert_eq!(out.stats.duplicate_conflict_dropped, 0); - assert_eq!(out.stats.rows_out, 1); - assert_eq!(out.rows[0].ts, base_ts + 12); -} - -#[test] -fn dedup_collapses_identical_ohlc_drops_conflicting_group_and_is_permutation_invariant() { - let ts_identical = 1_718_000_060_000_000_i64; - let ts_conflict = 1_718_000_120_000_000_i64; - let ts_valid_plus_bad = 1_718_000_180_000_000_i64; - - // Group 1: three bitwise-identical OHLC bars with differing volumes -> collapse to 1. - let id1 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, 0.0); - let id2 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, 42.0); - let id3 = raw_bar(EOD_CAD_FOREX_CODE, ts_identical, 1.3610, 1.3620, 1.3605, 1.3615, f64::NAN); - - // Group 2: two identical rows + one conflicting close -> drop all 3. - let cf1 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3625, 1.0); - let cf2 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3625, 1.0); - let cf3 = raw_bar(EOD_CAD_FOREX_CODE, ts_conflict, 1.3620, 1.3630, 1.3615, 1.3626, 1.0); - - // Group 3: one valid row + one invalid row at same ts -> invalid rejected early, valid survives. - let ok = raw_bar(EOD_CAD_FOREX_CODE, ts_valid_plus_bad, 1.3630, 1.3640, 1.3625, 1.3635, 0.0); - let bad = raw_bar(EOD_CAD_FOREX_CODE, ts_valid_plus_bad, f64::NAN, 1.3640, 1.3625, 1.3635, 0.0); - - let perm_a = [id1, id2, id3, cf1, cf2, cf3, ok, bad]; - let perm_b = [cf3, bad, id3, cf1, ok, id1, cf2, id2]; - let perm_c = [ok, cf2, id2, cf3, id1, bad, cf1, id3]; - - let out_a = build_fx_1m(perm_a); - let out_b = build_fx_1m(perm_b); - let out_c = build_fx_1m(perm_c); - - assert_conservation_and_order(&out_a); - assert_conservation_and_order(&out_b); - assert_conservation_and_order(&out_c); - assert_eq!(out_a, out_b); - assert_eq!(out_a, out_c); - - assert_eq!(out_a.stats.bars_in, 8); - assert_eq!(out_a.stats.dropped_invalid_ohlc, 1); - assert_eq!(out_a.stats.duplicate_collapsed, 2); - assert_eq!(out_a.stats.duplicate_conflict_dropped, 3); - assert_eq!(out_a.stats.rows_out, 2); - - assert_eq!(out_a.rows[0].ts, ts_identical); - assert_eq!(out_a.rows[0].close.to_bits(), 1.3615_f64.to_bits()); - assert_eq!(out_a.rows[1].ts, ts_valid_plus_bad); - assert_eq!(out_a.rows[1].close.to_bits(), 1.3635_f64.to_bits()); -} - -#[test] -fn writer_streams_two_chunks_through_one_writer_matches_encode_fx_1m_and_routes_one_shard() { - let ts1 = 1_718_000_000_000_000_i64; - let ts2 = 1_718_000_060_000_000_i64; - let ts3 = 1_718_000_120_000_000_i64; - - // Chunk 1 given out of order plus an unrelated ticker. - let chunk1 = [ - raw_bar(EOD_CAD_FOREX_CODE, ts2, 1.3710, 1.3720, 1.3705, 1.3715, 0.0), - raw_bar("EUR.FOREX", ts1, 1.0800, 1.0810, 1.0790, 1.0805, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, ts1, 1.3700, 1.3710, 1.3695, 1.3705, 0.0), - ]; - // Chunk 2 chronologically after chunk 1. - let chunk2 = [raw_bar( - EOD_CAD_FOREX_CODE, - ts3, - 1.3715, - 1.3725, - 1.3710, - 1.3722, - 0.0, - )]; - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let mut s2 = Vec::new(); - let mut s3 = Vec::new(); - let (rep1, rep2, ilp_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1, &mut s2, &mut s3], - IlpWriterOptions::default(), - ) - .unwrap(); - let rep1 = curate_and_write_fx_1m(chunk1, &mut writer).unwrap(); - // Writer remains open (finish was NOT called) so chunk 2 streams into the same writer. - let rep2 = curate_and_write_fx_1m(chunk2, &mut writer).unwrap(); - let stats = writer.finish().unwrap(); - (rep1, rep2, stats) - }; - - assert_eq!(rep1.curate_stats.bars_in, 3); - assert_eq!(rep1.curate_stats.dropped_wrong_code, 1); - assert_eq!(rep1.curate_stats.rows_out, 2); - assert_eq!(rep1.rows_written, 2); - - assert_eq!(rep2.curate_stats.bars_in, 1); - assert_eq!(rep2.curate_stats.rows_out, 1); - assert_eq!(rep2.rows_written, 1); - - assert_eq!(ilp_stats.rows, rep1.rows_written + rep2.rows_written); - assert_eq!(ilp_stats.rows, 3); - - let expected_rows = [ - Fx1mRow { - pair: FX_PAIR_USDCAD, - ts: ts1, - open: 1.3700, - high: 1.3710, - low: 1.3695, - close: 1.3705, - source: FX_1M_SOURCE_EOD, - }, - Fx1mRow { - pair: FX_PAIR_USDCAD, - ts: ts2, - open: 1.3710, - high: 1.3720, - low: 1.3705, - close: 1.3715, - source: FX_1M_SOURCE_EOD, - }, - Fx1mRow { - pair: FX_PAIR_USDCAD, - ts: ts3, - open: 1.3715, - high: 1.3725, - low: 1.3710, - close: 1.3722, - source: FX_1M_SOURCE_EOD, - }, - ]; - let mut expected_bytes = Vec::new(); - for row in &expected_rows { - encode_fx_1m(&mut expected_bytes, row).unwrap(); - } - - let target_shard = shard_for_fx_pair(FX_PAIR_USDCAD, 4); - let actual_shards = [&s0, &s1, &s2, &s3]; - for (idx, shard_bytes) in actual_shards.iter().enumerate() { - if idx == target_shard { - assert_eq!(*shard_bytes, &expected_bytes, "target shard ILP mismatch"); - } else { - assert!( - shard_bytes.is_empty(), - "non-target shard {idx} should be empty" - ); - } - } - assert_eq!(ilp_stats.per_shard_rows[target_shard], 3); -} - -#[test] -fn bson_stream_handles_mixed_docs_matches_builder_and_supports_writer_reuse() { - let ts1_sec = 1_718_000_000_i64; - let ts2_sec = 1_718_000_060_i64; - let ts3_sec = 1_718_000_120_i64; - - // Out-of-order CAD.FOREX docs + an identical duplicate + a decodable other code + a malformed doc. - let doc_late = - make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts2_sec, 1.3720, 1.3730, 1.3715, 1.3725, 0.0); - let doc_other = - make_eod_intraday_bson_doc("AAPL.US", ts1_sec, 195.0, 196.0, 194.5, 195.5, 1200.0); - // Correctly framed BSON document missing required field `close`. - let mut doc_missing_close = RawDocumentBuf::new(); - doc_missing_close.append(cstr!("eodSearchCode"), EOD_CAD_FOREX_CODE); - doc_missing_close.append(cstr!("timestamp"), ts1_sec); - doc_missing_close.append(cstr!("open"), 1.3700_f64); - doc_missing_close.append(cstr!("high"), 1.3710_f64); - doc_missing_close.append(cstr!("low"), 1.3695_f64); - doc_missing_close.append(cstr!("volume"), 0.0_f64); - - let doc_early = - make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts1_sec, 1.3700, 1.3710, 1.3695, 1.3705, 0.0); - let doc_early_dup = - make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts1_sec, 1.3700, 1.3710, 1.3695, 1.3705, 5.0); - - let mut chunk1_bytes = Vec::new(); - chunk1_bytes.extend_from_slice(doc_late.as_bytes()); - chunk1_bytes.extend_from_slice(doc_other.as_bytes()); - chunk1_bytes.extend_from_slice(doc_missing_close.as_bytes()); - chunk1_bytes.extend_from_slice(doc_early.as_bytes()); - chunk1_bytes.extend_from_slice(doc_early_dup.as_bytes()); - - let doc_chunk2 = - make_eod_intraday_bson_doc(EOD_CAD_FOREX_CODE, ts3_sec, 1.3725, 1.3735, 1.3720, 1.3731, 0.0); - let chunk2_bytes = doc_chunk2.as_bytes().to_vec(); - - // Small chunk capacity forces multi-chunk framing across documents. - let stream_opts = BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: 4096, - }; - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let (rep1, rep2, ilp_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1], - IlpWriterOptions::default(), - ) - .unwrap(); - let rep1 = - curate_and_write_fx_1m_from_bson(Cursor::new(&chunk1_bytes), stream_opts, &mut writer) - .unwrap(); - let rep2 = - curate_and_write_fx_1m_from_bson(Cursor::new(&chunk2_bytes), stream_opts, &mut writer) - .unwrap(); - let stats = writer.finish().unwrap(); - (rep1, rep2, stats) - }; - - // Decode accounting: 5 docs seen = 4 decoded + 1 missing_field reject. - assert_eq!(rep1.decode_stats.docs_seen, 5); - assert_eq!(rep1.decode_stats.rows_decoded, 4); - assert_eq!(rep1.decode_stats.rejected_missing_field, 1); - assert_eq!( - rep1.decode_stats.docs_seen, - rep1.decode_stats.rows_decoded + rep1.decode_stats.rejected_total() - ); - - // Builder input equals rows_decoded. - assert_eq!( - rep1.write_report.curate_stats.bars_in, - rep1.decode_stats.rows_decoded - ); - assert_eq!(rep1.write_report.curate_stats.dropped_wrong_code, 1); - assert_eq!(rep1.write_report.curate_stats.duplicate_collapsed, 1); - assert_eq!(rep1.write_report.curate_stats.rows_out, 2); - assert_eq!(rep1.write_report.rows_written, 2); - - // Compare chunk 1 curation stats directly against `build_fx_1m` on the same decoded inputs. - let direct_expected = build_fx_1m([ - raw_bar(EOD_CAD_FOREX_CODE, ts2_sec * 1_000_000, 1.3720, 1.3730, 1.3715, 1.3725, 0.0), - raw_bar("AAPL.US", ts1_sec * 1_000_000, 195.0, 196.0, 194.5, 195.5, 1200.0), - raw_bar(EOD_CAD_FOREX_CODE, ts1_sec * 1_000_000, 1.3700, 1.3710, 1.3695, 1.3705, 0.0), - raw_bar(EOD_CAD_FOREX_CODE, ts1_sec * 1_000_000, 1.3700, 1.3710, 1.3695, 1.3705, 5.0), - ]); - assert_eq!(rep1.write_report.curate_stats, direct_expected.stats); - - // Chunk 2 stats & aggregate ILP stats. - assert_eq!(rep2.decode_stats.docs_seen, 1); - assert_eq!(rep2.decode_stats.rows_decoded, 1); - assert_eq!(rep2.write_report.rows_written, 1); - assert_eq!(ilp_stats.rows, 3); - - // Exact ILP bytes match `encode_fx_1m` of chunk 1 + chunk 2 expected rows in order. - let mut expected_bytes = Vec::new(); - for row in &direct_expected.rows { - encode_fx_1m(&mut expected_bytes, row).unwrap(); - } - encode_fx_1m( - &mut expected_bytes, - &Fx1mRow { - pair: FX_PAIR_USDCAD, - ts: ts3_sec * 1_000_000, - open: 1.3725, - high: 1.3735, - low: 1.3720, - close: 1.3731, - source: FX_1M_SOURCE_EOD, - }, - ) - .unwrap(); - - let target_shard = shard_for_fx_pair(FX_PAIR_USDCAD, 2); - let other_shard = 1 - target_shard; - let shards = [&s0, &s1]; - assert_eq!(shards[target_shard], &expected_bytes); - assert!(shards[other_shard].is_empty()); -} - -#[test] -fn truncated_bson_stream_fails_closed_with_zero_rows_written_and_typed_errors_format() { - let doc1 = make_eod_intraday_bson_doc( - EOD_CAD_FOREX_CODE, - 1_718_000_000, - 1.3700, - 1.3710, - 1.3695, - 1.3705, - 0.0, - ); - let doc2 = make_eod_intraday_bson_doc( - EOD_CAD_FOREX_CODE, - 1_718_000_060, - 1.3710, - 1.3720, - 1.3705, - 1.3715, - 0.0, - ); - - let mut truncated_bytes = Vec::new(); - truncated_bytes.extend_from_slice(doc1.as_bytes()); - let doc2_bytes = doc2.as_bytes(); - truncated_bytes.extend_from_slice(&doc2_bytes[..doc2_bytes.len() / 2]); - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let (stream_err, stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_fx_1m_from_bson( - Cursor::new(&truncated_bytes), - BsonStreamOptions::default(), - &mut writer, - ) - .unwrap_err(); - let stats = writer.finish().unwrap(); - (err, stats) - }; - - assert!(matches!( - stream_err, - CurateFx1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) - )); - assert!(stream_err.source().is_some()); - assert!(stream_err.to_string().contains("fx_1m BSON stream failed")); - assert_eq!(stats.rows, 0); - assert!(s0.is_empty()); - assert!(s1.is_empty()); - - // Writer I/O failure surfaces as `CurateFx1mBsonError::Write(IlpWriterError::Io { .. })`. - let mut failing_writer = IlpShardedWriter::new( - vec![FailingSink], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - let write_err = curate_and_write_fx_1m_from_bson( - Cursor::new(doc1.as_bytes()), - BsonStreamOptions::default(), - &mut failing_writer, - ) - .unwrap_err(); - assert!(matches!( - write_err, - CurateFx1mBsonError::Write(IlpWriterError::Io { shard: 0, .. }) - )); - assert!(write_err.source().is_some()); - assert!(write_err.to_string().contains("fx_1m ILP write failed")); -} diff --git a/tools/curate-etl/src/curate_qm_bars_1m.rs b/tools/curate-etl/src/curate_qm_bars_1m.rs deleted file mode 100644 index 19fb6e0c..00000000 --- a/tools/curate-etl/src/curate_qm_bars_1m.rs +++ /dev/null @@ -1,206 +0,0 @@ -//! Pure, in-memory `bars_1m` curation stage for raw QuoteMedia `qmIntraday` bars (`M2.3j`), -//! joining [`crate::bars_1m::build_bars_1m`], [`crate::provider_mapping::ProviderMappingTable`], -//! [`crate::ilp::IlpShardedWriter`], and [`crate::bson_stream::decode_qm_intraday_stream`]. -//! -//! # Contract & Point-in-Time Rules -//! - Uses [`EodIntradayBar`] as the existing source-keyed carrier for canonical raw QuoteMedia -//! OHLCV and `qmSearchCode`. -//! - **No split un-adjustment:** `qmIntraday` raw fields (`open`, `high`, `low`, `close`, -//! `sharevolume`) are already un-adjusted (`design/DATA-CONTRACTS.md` §1). This stage takes no -//! [`SplitTable`] and invokes [`build_bars_1m`] with an internal empty [`SplitTable`] so valid -//! OHLCV values pass through bit-identical while reusing Eastern Time session tagging, OHLCV -//! validation, and same-key deduplication. -//! - **Signed-zero volume normalization:** [`crate::bson_qm_intraday::decode_qm_intraday_doc`] -//! normalizes `-0.0` `sharevolume` to `+0.0` during BSON decode, and [`build_bars_1m`] applies -//! the same `-0.0 -> +0.0` normalization for direct in-memory inputs. -//! - Resolves each built row's `(mapping_source, qmSearchCode, session_date)` to a permanent -//! `listing_id: i32` on its Eastern Time `session_date`, stamps [`BARS_1M_SOURCE_QM`] -//! (`"qm_raw"`), re-sorts in place by `(listing_id, ts)`, and compacts cross-`source_id` -//! collisions using the same bitwise-equality / conflict-drop rule as [`crate::curate_bars_1m`]. -//! - Writes sorted `Bar1mRow` rows into a caller-owned [`IlpShardedWriter`] without calling -//! [`IlpShardedWriter::finish`], allowing multiple chunks to stream through one writer. - -use std::error::Error; -use std::fmt; -use std::hash::Hash; -use std::io::{self, Write}; - -use crate::bars_1m::{build_bars_1m, EodIntradayBar, BARS_1M_SOURCE_QM}; -use crate::bson_qm_intraday::BsonQmIntradayDecodeStats; -use crate::bson_stream::{decode_qm_intraday_stream, BsonStreamError, BsonStreamOptions}; -use crate::curate_bars_1m::{ - map_bars_1m, CurateBars1mError, CurateBars1mOutput, CurateBars1mWriteError, - CurateBars1mWriteReport, -}; -use crate::ilp::IlpShardedWriter; -use crate::provider_mapping::ProviderMappingTable; -use crate::split::SplitTable; - -/// Combined decode and write summary returned by [`curate_and_write_qm_bars_1m_from_bson`]. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct CurateQmBars1mBsonReport { - pub decode_stats: BsonQmIntradayDecodeStats, - pub write_report: CurateBars1mWriteReport, -} - -/// Typed error returned by [`curate_and_write_qm_bars_1m_from_bson`]. -#[derive(Debug)] -pub enum CurateQmBars1mBsonError { - Stream(BsonStreamError), - Write(CurateBars1mWriteError), -} - -impl fmt::Display for CurateQmBars1mBsonError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Stream(err) => write!(f, "qmIntraday bars_1m BSON stream failed: {err}"), - Self::Write(err) => write!(f, "{err}"), - } - } -} - -impl Error for CurateQmBars1mBsonError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Stream(err) => Some(err), - Self::Write(err) => Some(err), - } - } -} - -impl From for CurateQmBars1mBsonError { - fn from(err: BsonStreamError) -> Self { - Self::Stream(err) - } -} - -impl From for CurateQmBars1mBsonError { - fn from(err: CurateBars1mWriteError) -> Self { - Self::Write(err) - } -} - -/// Pure `qmIntraday` -> `bars_1m` curation stage: validates, session-tags, and deduplicates -/// already-raw QuoteMedia 1-minute bars via [`build_bars_1m`] with an internal empty -/// [`SplitTable`] (no split un-adjustment), resolves -/// `(mapping_source, qmSearchCode, session_date) -> listing_id` on each bar's Eastern Time -/// `session_date`, stamps [`BARS_1M_SOURCE_QM`], and emits [`crate::bars_1m::Bar1mRow`] rows -/// sorted and unique by `(listing_id, ts)`. -/// -/// - Rejects empty or whitespace-only `mapping_source` with [`CurateBars1mError::EmptyMappingSource`] -/// before consuming `bars`. Non-blank `mapping_source` values are looked up verbatim. -/// - Accepts no [`SplitTable`]: raw `qmIntraday` OHLCV passes through bit-identical (aside from -/// `-0.0 -> +0.0` volume normalization). -/// - Shares [`CurateBars1mOutput`], [`crate::curate_bars_1m::CurateBars1mStats`], and -/// [`CurateBars1mError`] with [`crate::curate_bars_1m::curate_bars_1m`]. -pub fn curate_qm_bars_1m( - bars: B, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, -) -> Result -where - K: Ord + Eq + Hash + Clone + AsRef, - B: IntoIterator>, -{ - if mapping_source.trim().is_empty() { - return Err(CurateBars1mError::EmptyMappingSource); - } - - let empty_splits = SplitTable::::default(); - let built = build_bars_1m(bars, &empty_splits); - Ok(map_bars_1m( - built, - provider_mapping, - mapping_source, - BARS_1M_SOURCE_QM, - )) -} - -/// Runs [`curate_qm_bars_1m`] and streams every curated row in `(listing_id, ts)` order into the -/// caller-owned [`IlpShardedWriter`] using `known_at_micros`. -/// -/// Intentionally does **not** call [`IlpShardedWriter::finish`], so callers may stream multiple -/// chunks through a single writer before flushing and collecting aggregate -/// [`crate::ilp::IlpWriteStats`]. -pub fn curate_and_write_qm_bars_1m( - bars: B, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - writer: &mut IlpShardedWriter, - known_at_micros: i64, -) -> Result -where - W: Write + Send, - K: Ord + Eq + Hash + Clone + AsRef, - B: IntoIterator>, -{ - let curated = curate_qm_bars_1m(bars, provider_mapping, mapping_source)?; - let mut rows_written = 0usize; - for row in &curated.rows { - writer.write_bar_1m(row, known_at_micros)?; - rows_written += 1; - } - - Ok(CurateBars1mWriteReport { - curate_stats: curated.stats, - rows_written, - }) -} - -/// Decodes a concatenated raw BSON `qmIntraday` stream via [`decode_qm_intraday_stream`], -/// converts each valid document via -/// [`crate::bson_qm_intraday::RawQmIntradayBar::into_eod_intraday_bar`], and runs -/// [`curate_and_write_qm_bars_1m`] against the caller-owned [`IlpShardedWriter`]. -/// -/// - Rejects empty or whitespace-only `mapping_source` before reading `reader` or writing to -/// `writer`. -/// - Per-document semantic decode errors are counted and skipped in [`BsonQmIntradayDecodeStats`]; -/// fatal stream framing or I/O errors abort before any row from this call is written to `writer`. -/// -/// # Memory note -/// This helper buffers all decoded [`EodIntradayBar`] rows for a single call in memory -/// before curating and writing. Bounded chunking by listing or calendar month is handled by -/// higher-level runner stages. -pub fn curate_and_write_qm_bars_1m_from_bson( - reader: R, - options: BsonStreamOptions, - provider_mapping: &ProviderMappingTable, - mapping_source: &str, - writer: &mut IlpShardedWriter, - known_at_micros: i64, -) -> Result -where - R: io::Read, - W: Write + Send, -{ - if mapping_source.trim().is_empty() { - return Err(CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource).into()); - } - - let mut bars: Vec> = Vec::new(); - let decode_stats = decode_qm_intraday_stream( - reader, - options, - |raw| { - bars.push(raw.into_eod_intraday_bar(|code, _| code.to_owned())); - }, - |_offset, _err| {}, - )?; - - let write_report = curate_and_write_qm_bars_1m( - bars, - provider_mapping, - mapping_source, - writer, - known_at_micros, - )?; - - Ok(CurateQmBars1mBsonReport { - decode_stats, - write_report, - }) -} - -#[cfg(test)] -#[path = "curate_qm_bars_1m_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/curate_qm_bars_1m_tests.rs b/tools/curate-etl/src/curate_qm_bars_1m_tests.rs deleted file mode 100644 index 22a3eff9..00000000 --- a/tools/curate-etl/src/curate_qm_bars_1m_tests.rs +++ /dev/null @@ -1,823 +0,0 @@ -use std::error::Error; -use std::io::{self, Cursor, Read}; - -use bson::raw::{cstr, RawDocumentBuf}; -use bson::DateTime; - -use super::*; -use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD, BARS_1M_SOURCE_QM}; -use crate::bson_qm_intraday::decode_qm_intraday_bytes; -use crate::curate_bars_1m::curate_bars_1m; -use crate::ilp::{encode_bar_1m, shard_for_listing_id, IlpWriterOptions, TABLE_BARS_1M}; -use crate::provider_mapping::ProviderMappingRow; -use crate::shorts::et_to_utc_micros; -use crate::split::{ymd_to_epoch_days, SplitEvent, SplitTable}; - -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 bar_1m( - key: &str, - ts: i64, - open: f64, - high: f64, - low: f64, - close: f64, - volume: f64, -) -> EodIntradayBar { - EodIntradayBar { - key: key.to_string(), - ts, - open, - high, - low, - close, - volume, - } -} - -fn map_row( - source: &str, - source_id: &str, - valid_from: i32, - valid_to: Option, - listing_id: i32, -) -> ProviderMappingRow { - ProviderMappingRow { - source: source.to_string(), - source_id: source_id.to_string(), - valid_from, - valid_to, - listing_id, - } -} - -#[allow(clippy::too_many_arguments)] -fn make_qm_bson_doc( - code: &str, - ts_micros: i64, - open: f64, - high: f64, - low: f64, - close: f64, - sharevolume: f64, -) -> RawDocumentBuf { - assert_eq!(ts_micros % 1_000, 0, "qm timestamp must be millisecond-aligned"); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("qmSearchCode"), code); - doc.append(cstr!("timestamp"), DateTime::from_millis(ts_micros / 1_000)); - doc.append(cstr!("open"), open); - doc.append(cstr!("high"), high); - doc.append(cstr!("low"), low); - doc.append(cstr!("close"), close); - doc.append(cstr!("sharevolume"), sharevolume); - doc -} - -fn assert_conservation_and_order(out: &CurateBars1mOutput) { - let s = &out.stats; - assert_eq!( - s.rows_in, s.builder.rows_out, - "rows_in != builder.rows_out: {s:?}" - ); - assert_eq!(s.rows_out, out.rows.len(), "rows_out != rows.len(): {s:?}"); - assert_eq!( - s.rows_in, - s.rows_out - + s.dropped_unmapped - + s.listing_collision_collapsed - + s.listing_collision_dropped, - "curate_qm_bars_1m conservation invariant failed: {s:?}" - ); - assert_eq!( - s.rows_out, - s.pre_rows_out + s.rth_rows_out + s.post_rows_out, - "session breakdown != rows_out: {s:?}" - ); - - for pair in out.rows.windows(2) { - assert!( - (pair[0].key, pair[0].ts) < (pair[1].key, pair[1].ts), - "rows not strictly sorted and unique by (listing_id, ts): {:?} vs {:?}", - (pair[0].key, pair[0].ts), - (pair[1].key, pair[1].ts) - ); - } -} - -fn contains_subslice(haystack: &[u8], needle: &[u8]) -> bool { - !needle.is_empty() && haystack.windows(needle.len()).any(|w| w == needle) -} - -#[test] -fn raw_qm_passthrough_preserves_ohlcv_bits_across_future_split_unlike_eod_control() { - let pre_day = day(2024, 6, 7); - let ex_date = day(2024, 6, 10); - let nvda_listing_id = 77_001; - let pre_ts = et_ts(2024, 6, 7, 15, 59); - - // Pre-split NVDA raw values vs 10:1 retroactively split-adjusted values. - let raw_open = 1205.0_f64; - let raw_high = 1210.0_f64; - let raw_low = 1204.0_f64; - let raw_close = 1208.88_f64; - let raw_vol = 41_239.0_f64; - - let mut qm_doc = make_qm_bson_doc( - "NVDA", - pre_ts, - raw_open, - raw_high, - raw_low, - raw_close, - raw_vol, - ); - // Distinct adjusted fields in the same BSON document must be ignored. - qm_doc.append(cstr!("adjustedopen"), 120.50_f64); - qm_doc.append(cstr!("adjustedhigh"), 121.00_f64); - qm_doc.append(cstr!("adjustedlow"), 120.40_f64); - qm_doc.append(cstr!("adjustedclose"), 120.888_f64); - qm_doc.append(cstr!("avolume"), 412_390.0_f64); - - let decoded = decode_qm_intraday_bytes(qm_doc.as_bytes()).unwrap(); - let qm_bar = decoded.into_eod_intraday_bar(|code, _| code.to_owned()); - - let splits = SplitTable::from_events([( - "NVDA".to_string(), - SplitEvent { - ex_date, - ratio: 10.0, - }, - )]) - .unwrap(); - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(2020, 1, 1), - None, - nvda_listing_id, - )]) - .unwrap(); - - // Control: EOD stage with the 10:1 split DOES scale OHLCV (and stamps BARS_1M_SOURCE_EOD). - let eod_control = curate_bars_1m([qm_bar.clone()], &splits, &mapping, "qm").unwrap(); - assert_eq!(eod_control.rows.len(), 1); - let eod_row = &eod_control.rows[0]; - assert_eq!(eod_row.source, BARS_1M_SOURCE_EOD); - assert_ne!(eod_row.open.to_bits(), qm_bar.open.to_bits()); - assert_ne!(eod_row.high.to_bits(), qm_bar.high.to_bits()); - assert_ne!(eod_row.low.to_bits(), qm_bar.low.to_bits()); - assert_ne!(eod_row.close.to_bits(), qm_bar.close.to_bits()); - assert_ne!(eod_row.volume.to_bits(), qm_bar.volume.to_bits()); - - // QuoteMedia stage accepts no SplitTable and preserves all five OHLCV fields bit-identically. - let qm_out = curate_qm_bars_1m([qm_bar.clone()], &mapping, "qm").unwrap(); - assert_conservation_and_order(&qm_out); - assert_eq!(qm_out.rows.len(), 1); - let row = &qm_out.rows[0]; - assert_eq!(row.key, nvda_listing_id); - assert_eq!(row.ts, pre_ts); - assert_eq!(row.session_date, pre_day); - assert_eq!(row.session, IntradaySession::Rth); - assert_eq!(row.source, BARS_1M_SOURCE_QM); - assert_ne!(row.source, BARS_1M_SOURCE_EOD); - assert_eq!(row.open.to_bits(), raw_open.to_bits()); - assert_eq!(row.high.to_bits(), raw_high.to_bits()); - assert_eq!(row.low.to_bits(), raw_low.to_bits()); - assert_eq!(row.close.to_bits(), raw_close.to_bits()); - assert_eq!(row.volume.to_bits(), raw_vol.to_bits()); -} - -#[test] -fn mapping_uses_eastern_time_session_date_boundaries_gaps_and_is_shuffle_invariant() { - // 2024-06-10 20:30 ET (EDT = UTC-4) is 2024-06-11 00:30 UTC (next UTC calendar day). - // Mapping ends inclusively on 2024-06-10, so ET session_date resolves while UTC date would drop. - let d_start = day(2024, 6, 10); - let d_gap = day(2024, 6, 11); - let d_resume = day(2024, 6, 12); - - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "ACME:CA", d_start, Some(d_start), 101), - map_row("qm", "ACME:CA", d_resume, None, 202), - map_row("qm", "BETA", d_start, Some(d_resume), 303), - ]) - .unwrap(); - - // PRE on inclusive valid_from (2024-06-10 08:00 ET) -> listing 101 - let b_pre = bar_1m("ACME:CA", et_ts(2024, 6, 10, 8, 0), 10.0, 10.2, 9.9, 10.1, 100.0); - // POST on inclusive valid_to whose UTC date is 2024-06-11 -> listing 101 - let b_post_utc_next = bar_1m("ACME:CA", et_ts(2024, 6, 10, 20, 30), 10.1, 10.3, 10.0, 10.2, 50.0); - // Date inside gap (2024-06-11) -> dropped_unmapped - let b_gap = bar_1m("ACME:CA", et_ts(2024, 6, 11, 10, 0), 10.5, 10.6, 10.4, 10.5, 200.0); - // RTH on inclusive second range valid_from (2024-06-12) -> listing 202 - let b_resumed = bar_1m("ACME:CA", et_ts(2024, 6, 12, 10, 0), 11.0, 11.2, 10.9, 11.1, 300.0); - // RTH for BETA on 2024-06-11 -> listing 303 - let b_beta = bar_1m("BETA", et_ts(2024, 6, 11, 14, 15), 25.0, 25.5, 24.8, 25.2, 400.0); - // Unknown qmSearchCode -> dropped_unmapped - let b_unknown = bar_1m("UNKNOWN", et_ts(2024, 6, 10, 10, 0), 5.0, 5.1, 4.9, 5.0, 10.0); - - let ordered = vec![ - b_pre.clone(), - b_post_utc_next.clone(), - b_gap.clone(), - b_resumed.clone(), - b_beta.clone(), - b_unknown.clone(), - ]; - let shuffled = vec![ - b_unknown, - b_resumed, - b_post_utc_next, - b_beta, - b_gap, - b_pre, - ]; - - let out_ordered = curate_qm_bars_1m(ordered, &mapping, "qm").unwrap(); - let out_shuffled = curate_qm_bars_1m(shuffled, &mapping, "qm").unwrap(); - - assert_conservation_and_order(&out_ordered); - assert_conservation_and_order(&out_shuffled); - assert_eq!(out_ordered, out_shuffled); - - assert_eq!(out_ordered.stats.rows_in, 6); - assert_eq!(out_ordered.stats.rows_out, 4); - assert_eq!(out_ordered.stats.dropped_unmapped, 2); - assert_eq!(out_ordered.stats.listings_out, 3); - assert_eq!(out_ordered.stats.pre_rows_out, 1); - assert_eq!(out_ordered.stats.rth_rows_out, 2); - assert_eq!(out_ordered.stats.post_rows_out, 1); - - // Verify exact ET session_date and listing assignment on the UTC-next-day POST bar. - let post_row = out_ordered - .rows - .iter() - .find(|r| r.session == IntradaySession::Post) - .expect("POST row present"); - assert_eq!(post_row.key, 101); - assert_eq!(post_row.session_date, d_start); - assert_ne!(post_row.session_date, d_gap); - assert!(out_ordered.rows.iter().all(|r| r.source == BARS_1M_SOURCE_QM)); -} - -#[test] -fn same_code_duplicates_and_cross_code_alias_collisions_enforce_conservation() { - let listing_id = 505; - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "OLD:CA", day(2024, 1, 1), None, listing_id), - map_row("qm", "NEW:CA", day(2024, 1, 1), None, listing_id), - map_row("qm", "ALT:CA", day(2024, 1, 1), None, listing_id), - ]) - .unwrap(); - - let ts_same_dup = et_ts(2024, 6, 10, 9, 30); - let ts_alias_ok = et_ts(2024, 6, 10, 9, 31); - let ts_alias_conflict = et_ts(2024, 6, 10, 9, 32); - let ts_unique_post = et_ts(2024, 6, 10, 16, 5); - - let bars = vec![ - // Same-code exact duplicate -> collapsed in builder (duplicate_collapsed = 1). - bar_1m("OLD:CA", ts_same_dup, 10.0, 10.5, 9.8, 10.2, 100.0), - bar_1m("OLD:CA", ts_same_dup, 10.0, 10.5, 9.8, 10.2, 100.0), - // Three distinct qmSearchCodes with bit-identical OHLCV -> group of 3 collapses by g-1 = 2. - bar_1m("OLD:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), - bar_1m("NEW:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), - bar_1m("ALT:CA", ts_alias_ok, 10.2, 10.6, 10.1, 10.4, 250.0), - // Two distinct qmSearchCodes with conflicting close -> entire group of g = 2 dropped. - bar_1m("OLD:CA", ts_alias_conflict, 10.4, 10.8, 10.3, 10.5, 300.0), - bar_1m("NEW:CA", ts_alias_conflict, 10.4, 10.8, 10.3, 10.6, 300.0), - // Clean POST row. - bar_1m("NEW:CA", ts_unique_post, 10.6, 10.7, 10.5, 10.65, 0.0), - ]; - - let out = curate_qm_bars_1m(bars, &mapping, "qm").unwrap(); - assert_conservation_and_order(&out); - - assert_eq!(out.stats.builder.bars_in, 8); - assert_eq!(out.stats.builder.duplicate_collapsed, 1); - assert_eq!(out.stats.builder.rows_out, 7); - assert_eq!(out.stats.rows_in, 7); - assert_eq!(out.stats.listing_collision_collapsed, 2); - assert_eq!(out.stats.listing_collision_dropped, 2); - assert_eq!(out.stats.dropped_unmapped, 0); - assert_eq!(out.stats.rows_out, 3); - assert_eq!(out.stats.listings_out, 1); - assert_eq!(out.stats.pre_rows_out, 0); - assert_eq!(out.stats.rth_rows_out, 2); - assert_eq!(out.stats.post_rows_out, 1); - - let emitted_ts: Vec = out.rows.iter().map(|r| r.ts).collect(); - assert_eq!(emitted_ts, vec![ts_same_dup, ts_alias_ok, ts_unique_post]); - assert!(out.rows.iter().all(|r| r.source == BARS_1M_SOURCE_QM)); -} - -#[test] -fn bson_to_ilp_streams_multi_chunk_writes_qm_raw_and_supports_writer_reuse() { - let known_at = 1_718_050_123_456_000_i64; - let mapping = ProviderMappingTable::from_rows([ - map_row("qm", "NVDA", day(2020, 1, 1), None, 101), - map_row("qm", "SHOP:CA", day(2020, 1, 1), None, 202), - ]) - .unwrap(); - - let ts1 = et_ts(2024, 6, 7, 15, 59); - let ts2 = et_ts(2024, 6, 10, 9, 30); - let ts3 = et_ts(2024, 6, 10, 16, 10); - - let doc1 = make_qm_bson_doc("NVDA", ts1, 1205.0, 1210.0, 1204.0, 1208.88, 41_239.0); - // Semantically invalid doc: missing required field `close`. - let mut bad_doc = RawDocumentBuf::new(); - bad_doc.append(cstr!("qmSearchCode"), "NVDA"); - bad_doc.append(cstr!("timestamp"), DateTime::from_millis(ts2 / 1_000)); - bad_doc.append(cstr!("open"), 120.0_f64); - bad_doc.append(cstr!("high"), 121.0_f64); - bad_doc.append(cstr!("low"), 119.5_f64); - bad_doc.append(cstr!("sharevolume"), 1_000.0_f64); - let doc2 = make_qm_bson_doc("SHOP:CA", ts2, 88.0, 89.0, 87.5, 88.4, 2_500.0); - - let mut chunk1_bytes = Vec::new(); - chunk1_bytes.extend_from_slice(doc1.as_bytes()); - chunk1_bytes.extend_from_slice(bad_doc.as_bytes()); - chunk1_bytes.extend_from_slice(doc2.as_bytes()); - - let doc3 = make_qm_bson_doc("NVDA", ts3, 121.0, 121.5, 120.8, 121.2, 5_000.0); - let chunk2_bytes = doc3.as_bytes().to_vec(); - - // Force multi-chunk streaming with a tiny chunk capacity smaller than two documents. - let stream_opts = BsonStreamOptions { - chunk_capacity_bytes: 64, - max_doc_bytes: 4096, - }; - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let mut s2 = Vec::new(); - let mut s3 = Vec::new(); - let (rep1, rep2, ilp_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1, &mut s2, &mut s3], - IlpWriterOptions::default(), - ) - .unwrap(); - let rep1 = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&chunk1_bytes), - stream_opts, - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap(); - // Reuse the same open writer for a second call. - let rep2 = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&chunk2_bytes), - stream_opts, - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap(); - let stats = writer.finish().unwrap(); - (rep1, rep2, stats) - }; - - assert_eq!(rep1.decode_stats.docs_seen, 3); - assert_eq!(rep1.decode_stats.rows_decoded, 2); - assert_eq!(rep1.decode_stats.rejected_missing_field, 1); - assert_eq!( - rep1.decode_stats.docs_seen, - rep1.decode_stats.rows_decoded + rep1.decode_stats.rejected_total() - ); - assert_eq!(rep1.write_report.rows_written, 2); - assert_eq!( - rep1.write_report.rows_written, - rep1.write_report.curate_stats.rows_out - ); - - assert_eq!(rep2.decode_stats.docs_seen, 1); - assert_eq!(rep2.decode_stats.rows_decoded, 1); - assert_eq!(rep2.write_report.rows_written, 1); - assert_eq!( - ilp_stats.rows, - rep1.write_report.rows_written + rep2.write_report.rows_written - ); - assert_eq!(ilp_stats.rows, 3); - - // Build expected exact ILP lines for each emitted row and verify per-shard routing, - // `source=qm_raw`, exact `known_at`, and per-shard ordering. - let expected_row1 = Bar1mRow { - key: 101, - ts: ts1, - session_date: day(2024, 6, 7), - open: 1205.0, - high: 1210.0, - low: 1204.0, - close: 1208.88, - volume: 41_239.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_QM, - }; - let expected_row2 = Bar1mRow { - key: 202, - ts: ts2, - session_date: day(2024, 6, 10), - open: 88.0, - high: 89.0, - low: 87.5, - close: 88.4, - volume: 2_500.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_QM, - }; - let expected_row3 = Bar1mRow { - key: 101, - ts: ts3, - session_date: day(2024, 6, 10), - open: 121.0, - high: 121.5, - low: 120.8, - close: 121.2, - volume: 5_000.0, - session: IntradaySession::Post, - source: BARS_1M_SOURCE_QM, - }; - - let mut expected_shards = vec![Vec::::new(); 4]; - for row in [&expected_row1, &expected_row2, &expected_row3] { - let shard = shard_for_listing_id(row.key, 4); - encode_bar_1m(&mut expected_shards[shard], row, known_at).unwrap(); - } - - let actual_shards = [&s0, &s1, &s2, &s3]; - for (idx, (actual, expected)) in actual_shards.iter().zip(&expected_shards).enumerate() { - assert_eq!(*actual, expected, "shard {idx} ILP bytes mismatch"); - } - - let all_bytes: Vec = actual_shards.iter().flat_map(|s| s.iter().copied()).collect(); - assert!(contains_subslice(&all_bytes, TABLE_BARS_1M.as_bytes())); - assert!(contains_subslice( - &all_bytes, - format!("source={BARS_1M_SOURCE_QM}").as_bytes() - )); - assert!(!contains_subslice( - &all_bytes, - format!("source={BARS_1M_SOURCE_EOD}").as_bytes() - )); - assert!(contains_subslice( - &all_bytes, - format!("known_at={known_at}t").as_bytes() - )); -} - -struct CountingReader { - inner: R, - reads: usize, -} - -impl Read for CountingReader { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.reads += 1; - self.inner.read(buf) - } -} - -#[test] -fn truncated_stream_and_blank_mapping_source_fail_closed_with_zero_writes() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "NVDA", - day(2020, 1, 1), - None, - 101, - )]) - .unwrap(); - let known_at = 1_718_050_000_000_000_i64; - - let doc1 = make_qm_bson_doc( - "NVDA", - et_ts(2024, 6, 7, 15, 59), - 1205.0, - 1210.0, - 1204.0, - 1208.88, - 41_239.0, - ); - let doc2 = make_qm_bson_doc( - "NVDA", - et_ts(2024, 6, 10, 15, 59), - 121.0, - 121.5, - 120.8, - 121.2, - 5_000.0, - ); - - // Truncated tail after a valid document with max_batch_rows = 1 must write zero bytes. - let mut truncated_bytes = Vec::new(); - truncated_bytes.extend_from_slice(doc1.as_bytes()); - let doc2_bytes = doc2.as_bytes(); - truncated_bytes.extend_from_slice(&doc2_bytes[..doc2_bytes.len() / 2]); - - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - let (err, trunc_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&truncated_bytes), - BsonStreamOptions::default(), - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap_err(); - let stats = writer.finish().unwrap(); - (err, stats) - }; - assert!(matches!( - err, - CurateQmBars1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) - )); - assert!(err.source().is_some()); - assert_eq!(trunc_stats.rows, 0); - assert!(s0.is_empty()); - assert!(s1.is_empty()); - - // Blank mapping_source on pure stage returns EmptyMappingSource. - let pure_err = curate_qm_bars_1m( - [bar_1m("NVDA", et_ts(2024, 6, 7, 15, 59), 10.0, 11.0, 9.0, 10.5, 100.0)], - &mapping, - " \t", - ) - .unwrap_err(); - assert_eq!(pure_err, CurateBars1mError::EmptyMappingSource); - - // Blank mapping_source on BSON stage rejects before any read or write. - let mut counting_reader = CountingReader { - inner: Cursor::new(doc1.as_bytes()), - reads: 0, - }; - let mut sink = Vec::new(); - let (blank_err, blank_stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut sink], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_qm_bars_1m_from_bson( - &mut counting_reader, - BsonStreamOptions::default(), - &mapping, - " \n\t ", - &mut writer, - known_at, - ) - .unwrap_err(); - let stats = writer.finish().unwrap(); - (err, stats) - }; - assert!(matches!( - blank_err, - CurateQmBars1mBsonError::Write(CurateBars1mWriteError::Curate( - CurateBars1mError::EmptyMappingSource - )) - )); - assert!(blank_err.source().is_some()); - assert_eq!(counting_reader.reads, 0); - assert_eq!(blank_stats.rows, 0); - assert!(sink.is_empty()); -} - -// --------------------------------------------------------------------------------------------- -// QA (T-152) additional coverage. -// --------------------------------------------------------------------------------------------- - -#[test] -fn qa_bson_to_ilp_reorders_reverse_ts_rows_within_one_shard_and_reuses_writer() { - // Two valid bars for the same listing in REVERSE timestamp order in one BSON call: the shard - // must receive them ascending by ts. A single shard makes every row share one sink. - let known_at = 1_718_100_000_000_000_i64; - let mapping = - ProviderMappingTable::from_rows([map_row("qm", "NVDA", day(2020, 1, 1), None, 101)]) - .unwrap(); - let ts_early = et_ts(2024, 6, 10, 9, 30); - let ts_late = et_ts(2024, 6, 10, 9, 45); - let ts_next = et_ts(2024, 6, 11, 9, 30); - - let late = make_qm_bson_doc("NVDA", ts_late, 121.0, 122.0, 120.5, 121.5, 900.0); - let early = make_qm_bson_doc("NVDA", ts_early, 120.0, 120.9, 119.8, 120.6, 700.0); - let mut call1 = Vec::new(); - call1.extend_from_slice(late.as_bytes()); - call1.extend_from_slice(early.as_bytes()); - let call2 = make_qm_bson_doc("NVDA", ts_next, 123.0, 123.5, 122.5, 123.1, 1_100.0) - .as_bytes() - .to_vec(); - - let opts = BsonStreamOptions { - chunk_capacity_bytes: 48, - max_doc_bytes: 4096, - }; - let mut sink = Vec::new(); - let (rep1, rep2, stats) = { - let mut writer = IlpShardedWriter::new( - vec![&mut sink], - IlpWriterOptions { - max_batch_bytes: 1 << 16, - max_batch_rows: 1, - }, - ) - .unwrap(); - let rep1 = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&call1), - opts, - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap(); - let rep2 = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&call2), - opts, - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap(); - (rep1, rep2, writer.finish().unwrap()) - }; - assert_eq!(rep1.write_report.rows_written, 2); - assert_eq!(rep2.write_report.rows_written, 1); - assert_eq!(stats.rows, 3); - - let row = |ts: i64, o: f64, h: f64, l: f64, c: f64, v: f64, date: i32| Bar1mRow { - key: 101, - ts, - session_date: date, - open: o, - high: h, - low: l, - close: c, - volume: v, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_QM, - }; - let mut expected = Vec::new(); - for r in [ - row(ts_early, 120.0, 120.9, 119.8, 120.6, 700.0, day(2024, 6, 10)), - row(ts_late, 121.0, 122.0, 120.5, 121.5, 900.0, day(2024, 6, 10)), - row(ts_next, 123.0, 123.5, 122.5, 123.1, 1_100.0, day(2024, 6, 11)), - ] { - encode_bar_1m(&mut expected, &r, known_at).unwrap(); - } - assert_eq!(sink, expected, "shard must receive rows ascending by ts across calls"); -} - -#[test] -fn qa_invalid_ohlcv_and_out_of_range_dates_are_accounted_and_volume_neg_zero_normalized() { - let mapping = ProviderMappingTable::from_rows([map_row( - "qm", - "ACME", - day(2024, 6, 10), - Some(day(2024, 6, 10)), - 9, - )]) - .unwrap(); - let bars = vec![ - // Valid, -0.0 volume -> +0.0. - bar_1m("ACME", et_ts(2024, 6, 10, 10, 0), 10.0, 10.5, 9.5, 10.2, -0.0), - // high < low -> builder drops (inconsistent). - bar_1m("ACME", et_ts(2024, 6, 10, 10, 1), 10.0, 9.0, 9.5, 10.2, 1.0), - // NaN close -> builder drops. - bar_1m("ACME", et_ts(2024, 6, 10, 10, 2), 10.0, 10.5, 9.5, f64::NAN, 1.0), - // Negative volume -> builder drops. - bar_1m("ACME", et_ts(2024, 6, 10, 10, 3), 10.0, 10.5, 9.5, 10.2, -5.0), - // Day before valid_from and day after valid_to -> dropped_unmapped. - bar_1m("ACME", et_ts(2024, 6, 7, 10, 0), 10.0, 10.5, 9.5, 10.2, 1.0), - bar_1m("ACME", et_ts(2024, 6, 11, 10, 0), 10.0, 10.5, 9.5, 10.2, 1.0), - ]; - let out = curate_qm_bars_1m(bars, &mapping, "qm").unwrap(); - assert_conservation_and_order(&out); - let b = &out.stats.builder; - assert_eq!(b.bars_in, 6); - assert_eq!( - b.dropped_invalid_ohlc + b.dropped_inconsistent_ohlc + b.dropped_invalid_volume, - 3, - "{b:?}" - ); - assert_eq!(out.stats.rows_in, 3); - assert_eq!(out.stats.dropped_unmapped, 2); - assert_eq!(out.rows.len(), 1); - assert_eq!(out.rows[0].volume.to_bits(), 0.0_f64.to_bits()); - assert_eq!(out.rows[0].source, BARS_1M_SOURCE_QM); -} - -#[test] -fn qa_mapping_source_is_namespace_scoped_and_matched_verbatim() { - // Same code under a different provider namespace (`eod`) must not resolve for `qm`. - let mapping = ProviderMappingTable::from_rows([ - map_row("eod", "NVDA", day(2020, 1, 1), None, 1), - map_row("qm", "NVDA", day(2020, 1, 1), None, 2), - ]) - .unwrap(); - let bars = || [bar_1m("NVDA", et_ts(2024, 6, 10, 10, 0), 1.0, 1.0, 1.0, 1.0, 1.0)]; - let qm = curate_qm_bars_1m(bars(), &mapping, "qm").unwrap(); - assert_eq!(qm.rows.len(), 1); - assert_eq!(qm.rows[0].key, 2); - // Padded namespace is non-blank and looked up verbatim -> nothing matches. - let padded = curate_qm_bars_1m(bars(), &mapping, " qm").unwrap(); - assert_conservation_and_order(&padded); - assert_eq!(padded.rows.len(), 0); - assert_eq!(padded.stats.dropped_unmapped, 1); -} - -#[test] -fn qa_curate_and_write_blank_namespace_and_multichunk_truncation_write_nothing() { - let mapping = - ProviderMappingTable::from_rows([map_row("qm", "NVDA", day(2020, 1, 1), None, 101)]) - .unwrap(); - let known_at = 1_718_000_000_000_000_i64; - - // In-memory write path: blank namespace -> Curate error, zero bytes. - let mut sink = Vec::new(); - { - let mut writer = IlpShardedWriter::new( - vec![&mut sink], - IlpWriterOptions { - max_batch_bytes: 1, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_qm_bars_1m( - [bar_1m("NVDA", et_ts(2024, 6, 10, 10, 0), 1.0, 1.0, 1.0, 1.0, 1.0)], - &mapping, - "", - &mut writer, - known_at, - ) - .unwrap_err(); - assert!(matches!( - err, - CurateBars1mWriteError::Curate(CurateBars1mError::EmptyMappingSource) - )); - assert_eq!(writer.finish().unwrap().rows, 0); - } - assert!(sink.is_empty()); - - // Many valid docs streamed across many small chunks, then a truncated tail: zero bytes. - let mut bytes = Vec::new(); - for m in 0..20u8 { - let doc = make_qm_bson_doc("NVDA", et_ts(2024, 6, 10, 10, m), 1.0, 1.0, 1.0, 1.0, 1.0); - bytes.extend_from_slice(doc.as_bytes()); - } - bytes.extend_from_slice(&200_i32.to_le_bytes()); - bytes.extend_from_slice(&[0x02, b'x']); - let mut s0 = Vec::new(); - let mut s1 = Vec::new(); - { - let mut writer = IlpShardedWriter::new( - vec![&mut s0, &mut s1], - IlpWriterOptions { - max_batch_bytes: 1, - max_batch_rows: 1, - }, - ) - .unwrap(); - let err = curate_and_write_qm_bars_1m_from_bson( - Cursor::new(&bytes), - BsonStreamOptions { - chunk_capacity_bytes: 40, - max_doc_bytes: 4096, - }, - &mapping, - "qm", - &mut writer, - known_at, - ) - .unwrap_err(); - assert!(matches!( - err, - CurateQmBars1mBsonError::Stream(BsonStreamError::TruncatedDocument { .. }) - )); - assert_eq!(writer.finish().unwrap().rows, 0); - } - assert!(s0.is_empty() && s1.is_empty()); -} diff --git a/tools/curate-etl/src/fundamentals.rs b/tools/curate-etl/src/fundamentals.rs deleted file mode 100644 index 7ac7cae6..00000000 --- a/tools/curate-etl/src/fundamentals.rs +++ /dev/null @@ -1,1030 +0,0 @@ -//! Pure, in-memory point-in-time `fundamentals` builder (`qmFinancials` × `qmFilings` → -//! `fundamentals_bitemporal` rows → 2D `fundamentals_pit` snapshots + 4-quarter TTM). -//! -//! Aligned with `design/DATA-CONTRACTS.md` (§1 `qmFinancials`/`qmFilings` and §3A -//! `fundamentals_bitemporal` / `fundamentals_pit`): -//! -//! ## Stage 1 — Bitemporal Rows (`build_fundamentals_rows`) -//! - **Filing classification & timestamp parsing:** reuses [`crate::events::classify_form_type`], -//! [`FilingFormGroup::is_periodic_financial_report`], and -//! [`crate::events::parse_filing_timefiled`]. `10-Q` and SEDAR `Interim financial statements` -//! map to [`FiscalPeriod::Quarterly`]; `10-K`, `40-F`, and SEDAR `Annual financial statements` -//! map to [`FiscalPeriod::Annual`]. Non-periodic forms (such as `8-K`, `4`, `144`, `MD&A`, -//! `News release`) are never linked. -//! - **Heuristic filing-link rules (sampled `qmFilings` carries no statement-period field):** -//! - **Dated observation (`report_date: Some(rd)`):** `report_date` is assumed to identify the -//! observation's Eastern Time filing/vintage date. Links to the earliest matching periodic -//! filing (amended or unamended) for the same `(key, fiscal_period)` with `et_date == rd` -//! (strictly after `period_end`, because `rd <= period_end` is rejected). A same-day match can -//! anchor a late restatement/amendment beyond the inference windows below. -//! - **Undated observation (`report_date: None`):** links to the earliest matching -//! **non-amended** periodic filing for the same `(key, fiscal_period)` strictly after -//! `period_end` and within an inclusive calendar-day window of -//! [`QUARTERLY_FILING_LINK_WINDOW_DAYS`] (`75` days) for quarterly reports or -//! [`ANNUAL_FILING_LINK_WINDOW_DAYS`] (`150` days) for annual reports. -//! - Linked rows carry `known_at_utc_micros = parsed.utc_micros` and -//! `known_at_source = "filing_timestamp"`. -//! - **Statutory-lag fallback (unlinked observations):** -//! - `lag_date = period_end + venue.lag_days(fiscal_period)`: -//! - US & TSX ([`StatutoryLagVenue::UsTsx`]): `+45` calendar days (Q) / `+90` calendar days (FY). -//! - TSXV & CSE ([`StatutoryLagVenue::TsxvCse`]): `+60` calendar days (Q) / `+120` calendar days (FY). -//! - If a dated observation (`report_date: Some(rd)`) has no same-day filing link and -//! `rd > lag_date`, it is dropped and counted as an unanchored vintage -//! (`observations_dropped_unanchored_vintage`) rather than backdating `known_at` before its -//! observed `report_date`. -//! - If a dated statutory-lag estimate (`report_date: Some(rd_a)`) for `(key, period_end, -//! fiscal_period)` would become visible at or after an accepted newer dated version -//! (`rd_b > rd_a`, `known_at_b <= lag_micros`) of the same statement, the stale estimate is -//! dropped and counted in `observations_dropped_stale_estimate` so an older vintage never rolls -//! a newer filing backward. -//! - Otherwise `known_at_utc_micros` is `lag_date` at `16:05:00 America/Toronto` -//! ([`FUNDAMENTALS_FALLBACK_HOUR_ET`]:[`FUNDAMENTALS_FALLBACK_MINUTE_ET`]) via -//! [`crate::shorts::et_to_utc_micros`], tagged `known_at_source = "statutory_lag_estimate"`. -//! - **Calendar bounds & bad-row resilience:** statement `period_end`, optional `report_date`, -//! periodic filing Eastern days, and computed `lag_date` are validated against -//! [`MIN_SUPPORTED_DATE`]..=[`MAX_SUPPORTED_DATE`] (`2008-01-01..=2030-12-31`). Periodic filings -//! with `et_date <= earliest_period_end` for that `(key, fiscal_period)` are excluded and counted -//! in `filings_dropped_before_period_end`. Bad rows never panic; each category is counted in -//! [`FundamentalsStats`]. -//! - **Normalization, deduplication & sort:** `-0.0` normalizes to `0.0`. Rows are sorted by -//! `(key, period_end, known_at_utc_micros)`. Bitwise-identical duplicates at the same -//! `(key, period_end, known_at_utc_micros)` collapse (`duplicate_collapsed`); conflicting groups -//! (differing values, currency, fiscal period, or provenance) are discarded entirely -//! (`duplicate_conflict_dropped`). Distinct `known_at_utc_micros` versions for the same -//! `(key, period_end)` are preserved as separate restatement versions. -//! -//! ## Stage 2 — 2D PIT Snapshots & TTM (`build_fundamentals_snapshots`, `as_of`) -//! - Sweeps rows in `(key, known_at_utc_micros, period_end)` order, applying all updates sharing -//! `(key, effective_known_at_utc_micros)` before emitting one [`FundamentalsSnapshot`]. -//! - Maintains the latest visible version per `period_end`, carrying `None` fields forward from -//! the previous visible version of the **same** `(period_end, fiscal_period, currency)` along -//! with per-field provenance. -//! - Emits the latest `k` visible periods in descending `period_end` order (annual rows may occupy -//! slots; stock fields remain reported period values). -//! - Independently of `k` and of annual (`FY`) rows sharing a `period_end` (such as a calendar -//! year-end `10-K` sharing December 31 with standalone `Q4`), resolves standalone quarterly -//! versions separately and computes 4-quarter TTM sums for flow fields (`revenue`, `net_income`, -//! `operating_cash_flow`) from the 4 latest visible standalone quarterly periods when adjacent -//! `period_end` spacing is within [`TTM_CONSECUTIVE_QUARTER_MIN_DAYS`]..=[`TTM_CONSECUTIVE_QUARTER_MAX_DAYS`] -//! (`77..=105` calendar days, a heuristic given the input lacks a fiscal-quarter ordinal) and -//! all 4 share one currency. Missing flow inputs or non-finite sums produce `None` for that -//! field. -//! - Flags `has_estimated_lag = true` (and `known_at_source = "statutory_lag_estimate"`) if any -//! visible period slot or any quarter contributing to `ttm` used `statutory_lag_estimate` -//! (directly or via an inherited field). - -use std::borrow::Borrow; -use std::cmp::Ordering; -use std::collections::BTreeMap; -use std::error::Error; -use std::fmt; - -use crate::events::{ - classify_form_type, parse_filing_timefiled, FilingFormGroup, QmFiling, - KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, -}; -use crate::shorts::{et_to_utc_micros, MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE}; - -/// Statutory quarterly reporting lag (calendar days) for US & TSX listings (`design/DATA-CONTRACTS.md` §1). -pub const STATUTORY_LAG_US_TSX_QUARTERLY_DAYS: i32 = 45; - -/// Statutory annual reporting lag (calendar days) for US & TSX listings (`design/DATA-CONTRACTS.md` §1). -pub const STATUTORY_LAG_US_TSX_ANNUAL_DAYS: i32 = 90; - -/// Statutory quarterly reporting lag (calendar days) for TSXV & CSE listings (`design/DATA-CONTRACTS.md` §1). -pub const STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS: i32 = 60; - -/// Statutory annual reporting lag (calendar days) for TSXV & CSE listings (`design/DATA-CONTRACTS.md` §1). -pub const STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS: i32 = 120; - -/// Conservative fallback hour (`16:05 America/Toronto`) for statutory-lag `known_at` timestamps. -pub const FUNDAMENTALS_FALLBACK_HOUR_ET: u8 = 16; - -/// Conservative fallback minute (`16:05 America/Toronto`) for statutory-lag `known_at` timestamps. -pub const FUNDAMENTALS_FALLBACK_MINUTE_ET: u8 = 5; - -/// Inclusive heuristic filing-link window (calendar days strictly after `period_end`) for undated -/// quarterly observations when `qmFilings` carries no statement-period field. -pub const QUARTERLY_FILING_LINK_WINDOW_DAYS: i32 = 75; - -/// Inclusive heuristic filing-link window (calendar days strictly after `period_end`) for undated -/// annual observations when `qmFilings` carries no statement-period field. -pub const ANNUAL_FILING_LINK_WINDOW_DAYS: i32 = 150; - -/// Minimum inclusive calendar-day gap between adjacent quarterly `period_end` dates to be treated -/// as consecutive for 4-quarter TTM summation. -pub const TTM_CONSECUTIVE_QUARTER_MIN_DAYS: i32 = 77; - -/// Maximum inclusive calendar-day gap between adjacent quarterly `period_end` dates to be treated -/// as consecutive for 4-quarter TTM summation. -pub const TTM_CONSECUTIVE_QUARTER_MAX_DAYS: i32 = 105; - -/// Number of consecutive standalone quarters required to compute TTM flow sums. -pub const TTM_QUARTER_COUNT: usize = 4; - -/// Fiscal statement period kind. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum FiscalPeriod { - Quarterly, - Annual, -} - -impl FiscalPeriod { - /// Canonical contract label (`"Q"` or `"FY"`). - #[inline] - pub const fn as_str(self) -> &'static str { - match self { - Self::Quarterly => "Q", - Self::Annual => "FY", - } - } - - /// Inclusive heuristic link window in calendar days for undated observations. - #[inline] - pub const fn undated_link_window_days(self) -> i32 { - match self { - Self::Quarterly => QUARTERLY_FILING_LINK_WINDOW_DAYS, - Self::Annual => ANNUAL_FILING_LINK_WINDOW_DAYS, - } - } -} - -/// Per-listing venue class governing statutory deadline lag fallback. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum StatutoryLagVenue { - /// US exchanges and Toronto Stock Exchange (`+45d` Q / `+90d` FY). - UsTsx, - /// TSX Venture Exchange and Canadian Securities Exchange (`+60d` Q / `+120d` FY). - TsxvCse, -} - -impl StatutoryLagVenue { - /// Exact calendar-day statutory deadline lag for `(self, fiscal_period)`. - #[inline] - pub const fn lag_days(self, fiscal_period: FiscalPeriod) -> i32 { - match (self, fiscal_period) { - (Self::UsTsx, FiscalPeriod::Quarterly) => STATUTORY_LAG_US_TSX_QUARTERLY_DAYS, - (Self::UsTsx, FiscalPeriod::Annual) => STATUTORY_LAG_US_TSX_ANNUAL_DAYS, - (Self::TsxvCse, FiscalPeriod::Quarterly) => STATUTORY_LAG_TSXV_CSE_QUARTERLY_DAYS, - (Self::TsxvCse, FiscalPeriod::Annual) => STATUTORY_LAG_TSXV_CSE_ANNUAL_DAYS, - } - } -} - -/// Standardized numeric statement fields (single source of truth for Stage 1 and Stage 2). -/// -/// Flow fields (`revenue`, `net_income`, `operating_cash_flow`) are summed across 4 consecutive -/// standalone quarters for TTM. Stock fields (`total_assets`, `total_equity`, `shares_outstanding`) -/// are point-in-time balance/count values and are never summed for TTM. -#[derive(Debug, Clone, Copy, Default, PartialEq)] -pub struct FundamentalsFields { - // Flow fields (TTM-eligible) - pub revenue: Option, - pub net_income: Option, - pub operating_cash_flow: Option, - // Stock fields (never TTM-summed) - pub total_assets: Option, - pub total_equity: Option, - pub shares_outstanding: Option, -} - -impl FundamentalsFields { - #[inline] - fn all_finite(&self) -> bool { - opt_is_finite(self.revenue) - && opt_is_finite(self.net_income) - && opt_is_finite(self.operating_cash_flow) - && opt_is_finite(self.total_assets) - && opt_is_finite(self.total_equity) - && opt_is_finite(self.shares_outstanding) - } - - #[inline] - fn normalize_zeros(self) -> Self { - Self { - revenue: self.revenue.map(normalize_zero), - net_income: self.net_income.map(normalize_zero), - operating_cash_flow: self.operating_cash_flow.map(normalize_zero), - total_assets: self.total_assets.map(normalize_zero), - total_equity: self.total_equity.map(normalize_zero), - shares_outstanding: self.shares_outstanding.map(normalize_zero), - } - } - - #[inline] - fn bit_eq(&self, other: &Self) -> bool { - self.revenue.map(f64::to_bits) == other.revenue.map(f64::to_bits) - && self.net_income.map(f64::to_bits) == other.net_income.map(f64::to_bits) - && self.operating_cash_flow.map(f64::to_bits) - == other.operating_cash_flow.map(f64::to_bits) - && self.total_assets.map(f64::to_bits) == other.total_assets.map(f64::to_bits) - && self.total_equity.map(f64::to_bits) == other.total_equity.map(f64::to_bits) - && self.shares_outstanding.map(f64::to_bits) - == other.shares_outstanding.map(f64::to_bits) - } -} - -/// 4-quarter trailing twelve months (TTM) sums for flow fields. -#[derive(Debug, Clone, Copy, Default, PartialEq)] -pub struct TtmFlowFields { - pub revenue: Option, - pub net_income: Option, - pub operating_cash_flow: Option, -} - -/// Precomputed 4-quarter TTM summary attached to a [`FundamentalsSnapshot`]. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsTtm { - /// `period_end` epoch day of the latest (4th) quarter in the TTM window. - pub ending_period_end: i32, - /// Shared currency across all 4 contributing quarters. - pub currency: String, - /// Trailing 4-quarter sums for each flow field (`None` if any quarter lacks the field or if - /// the sum overflows to non-finite). - pub flows: TtmFlowFields, - /// `true` if any of the 4 contributing quarters used `statutory_lag_estimate` (directly or via - /// an inherited field). - pub has_estimated_lag: bool, -} - -/// A single raw financial-statement observation input (`qmFinancials`-shaped, BSON-free). -#[derive(Debug, Clone, PartialEq)] -pub struct FinancialObservation { - pub key: K, - /// Fiscal period end date as days since `1970-01-01` (UTC Gregorian). - pub period_end: i32, - pub fiscal_period: FiscalPeriod, - /// ISO currency code (e.g. `"USD"`, `"CAD"`). - pub currency: String, - /// Optional Eastern Time report/vintage date as days since `1970-01-01`. - pub report_date: Option, - pub fields: FundamentalsFields, -} - -/// A single curated bitemporal fundamentals row matching `fundamentals_bitemporal` in -/// `design/DATA-CONTRACTS.md` §3A, sorted and unique by `(key, period_end, known_at_utc_micros)`. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsRow { - pub key: K, - pub period_end: i32, - pub fiscal_period: FiscalPeriod, - pub currency: String, - pub known_at_utc_micros: i64, - pub known_at_source: &'static str, - pub fields: FundamentalsFields, -} - -/// A single resolved period entry inside a [`FundamentalsSnapshot`]. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsPeriodSlot { - pub period_end: i32, - pub fiscal_period: FiscalPeriod, - pub currency: String, - pub known_at_utc_micros: i64, - pub known_at_source: &'static str, - /// `true` if this period's latest version used `statutory_lag_estimate` or any field was - /// carried forward from an earlier `statutory_lag_estimate` version. - pub has_estimated_lag: bool, - pub fields: FundamentalsFields, -} - -/// A single 2D point-in-time snapshot matching `fundamentals_pit` in `design/DATA-CONTRACTS.md` -/// §3A, keyed by `(key, effective_known_at_utc_micros)`. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsSnapshot { - pub key: K, - pub effective_known_at_utc_micros: i64, - /// `"statutory_lag_estimate"` if [`Self::has_estimated_lag`] is `true`, otherwise - /// `"filing_timestamp"`. - pub known_at_source: &'static str, - /// `true` if any visible period slot or any quarter contributing to [`Self::ttm`] used - /// `statutory_lag_estimate` (directly or via an inherited field). - pub has_estimated_lag: bool, - /// Latest `k` visible periods ordered by `period_end` descending (`periods[0]` is latest). - pub periods: Vec, - /// Precomputed 4-quarter TTM flow sums, computed independently of `k`. - pub ttm: Option, -} - -/// Summary accounting counters produced alongside [`FundamentalsBuild::rows`]. -/// -/// Conservation invariants: -/// - Observations: -/// `observations_in == rows_out + observations_dropped_unknown_key + observations_dropped_non_finite + observations_dropped_date_out_of_range + observations_dropped_report_date_not_after_period_end + observations_dropped_unanchored_vintage + observations_dropped_stale_estimate + duplicate_collapsed + duplicate_conflict_dropped` -/// - Output provenance: -/// `rows_out == rows_linked_to_filing + rows_statutory_lag_estimate` -/// - Filings: -/// `filings_in == filings_eligible + filings_dropped_unknown_key + filings_ignored_non_periodic + filings_dropped_invalid_timestamp + filings_dropped_date_out_of_range + filings_dropped_before_period_end` -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct FundamentalsStats { - pub observations_in: usize, - pub rows_out: usize, - pub keys_out: usize, - pub rows_linked_to_filing: usize, - pub rows_statutory_lag_estimate: usize, - pub observations_dropped_unknown_key: usize, - pub observations_dropped_non_finite: usize, - pub observations_dropped_date_out_of_range: usize, - pub observations_dropped_report_date_not_after_period_end: usize, - pub observations_dropped_unanchored_vintage: usize, - pub observations_dropped_stale_estimate: usize, - pub duplicate_collapsed: usize, - pub duplicate_conflict_dropped: usize, - pub filings_in: usize, - pub filings_eligible: usize, - pub filings_dropped_unknown_key: usize, - pub filings_ignored_non_periodic: usize, - pub filings_dropped_invalid_timestamp: usize, - pub filings_dropped_date_out_of_range: usize, - pub filings_dropped_before_period_end: usize, -} - -/// Output of [`build_fundamentals_rows`]: sorted, unique bitemporal rows and reconciling stats. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsBuild { - pub rows: Vec>, - pub stats: FundamentalsStats, -} - -/// Typed caller errors returned by [`build_fundamentals_snapshots`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum FundamentalsError { - /// Caller-supplied `k` (maximum periods retained per snapshot) was zero. - InvalidPeriodLimit { k: usize }, -} - -impl fmt::Display for FundamentalsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Self::InvalidPeriodLimit { k } => { - write!(f, "invalid snapshot period limit k={k}: must be >= 1") - } - } - } -} - -impl Error for FundamentalsError {} - -#[inline] -fn opt_is_finite(v: Option) -> bool { - v.is_none_or(f64::is_finite) -} - -#[inline] -fn normalize_zero(v: f64) -> f64 { - if v == 0.0 { - 0.0 - } else { - v - } -} - -#[inline] -fn is_supported_date(epoch_day: i32) -> bool { - (MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&epoch_day) -} - -#[inline] -fn periodic_group_to_fiscal_period(group: FilingFormGroup) -> Option { - if !group.is_periodic_financial_report() { - return None; - } - match group { - FilingFormGroup::Form10Q | FilingFormGroup::InterimFinancials => { - Some(FiscalPeriod::Quarterly) - } - FilingFormGroup::Form10K - | FilingFormGroup::Form40F - | FilingFormGroup::AnnualFinancials => Some(FiscalPeriod::Annual), - _ => None, - } -} - -struct EligibleObservation { - key: K, - period_end: i32, - fiscal_period: FiscalPeriod, - currency: String, - report_date: Option, - venue: StatutoryLagVenue, - fields: FundamentalsFields, -} - -#[derive(Debug, Clone, Copy)] -struct IndexedFiling { - et_date: i32, - utc_micros: i64, - is_amendment: bool, -} - -struct ParsedPeriodicFiling { - key: K, - fiscal_period: FiscalPeriod, - et_date: i32, - utc_micros: i64, - is_amendment: bool, -} - -struct CandidateRow { - row: FundamentalsRow, - report_date: Option, -} - -/// Builds sorted, unique bitemporal fundamentals rows from financial observations, periodic -/// filings, and per-listing statutory-lag venue classes. -/// -/// Any permutation of `observations` or `filings` yields bitwise-identical `rows` and `stats`. -pub fn build_fundamentals_rows( - observations: IO, - filings: IF, - venues: &BTreeMap, -) -> FundamentalsBuild -where - K: Ord + Clone, - IO: IntoIterator>, - IF: IntoIterator>, -{ - let obs_iter = observations.into_iter(); - let mut stats = FundamentalsStats::default(); - let mut eligible_obs: Vec> = Vec::with_capacity(obs_iter.size_hint().0); - let mut earliest_period_by_key_kind: BTreeMap<(K, FiscalPeriod), i32> = BTreeMap::new(); - - for obs in obs_iter { - stats.observations_in += 1; - - let Some(&venue) = venues.get(&obs.key) else { - stats.observations_dropped_unknown_key += 1; - continue; - }; - - if !obs.fields.all_finite() { - stats.observations_dropped_non_finite += 1; - continue; - } - - if !is_supported_date(obs.period_end) - || obs.report_date.is_some_and(|rd| !is_supported_date(rd)) - { - stats.observations_dropped_date_out_of_range += 1; - continue; - } - - if obs.report_date.is_some_and(|rd| rd <= obs.period_end) { - stats.observations_dropped_report_date_not_after_period_end += 1; - continue; - } - - earliest_period_by_key_kind - .entry((obs.key.clone(), obs.fiscal_period)) - .and_modify(|min_pe| { - if obs.period_end < *min_pe { - *min_pe = obs.period_end; - } - }) - .or_insert(obs.period_end); - - eligible_obs.push(EligibleObservation { - key: obs.key, - period_end: obs.period_end, - fiscal_period: obs.fiscal_period, - currency: obs.currency, - report_date: obs.report_date, - venue, - fields: obs.fields.normalize_zeros(), - }); - } - - let filings_iter = filings.into_iter(); - let mut parsed_filings: Vec> = Vec::new(); - - for filing in filings_iter { - stats.filings_in += 1; - - if !venues.contains_key(&filing.key) { - stats.filings_dropped_unknown_key += 1; - continue; - } - - let (group, is_amendment) = classify_form_type(&filing.form_type); - let Some(fiscal_period) = periodic_group_to_fiscal_period(group) else { - stats.filings_ignored_non_periodic += 1; - continue; - }; - - let Ok(parsed) = parse_filing_timefiled(&filing.timefiled) else { - stats.filings_dropped_invalid_timestamp += 1; - continue; - }; - - if !is_supported_date(parsed.et_date) { - stats.filings_dropped_date_out_of_range += 1; - continue; - } - - parsed_filings.push(ParsedPeriodicFiling { - key: filing.key, - fiscal_period, - et_date: parsed.et_date, - utc_micros: parsed.utc_micros, - is_amendment, - }); - } - - let mut filing_index: BTreeMap<(K, FiscalPeriod), Vec> = BTreeMap::new(); - for pf in parsed_filings { - let key_kind = (pf.key, pf.fiscal_period); - if let Some(&min_pe) = earliest_period_by_key_kind.get(&key_kind) { - if pf.et_date <= min_pe { - stats.filings_dropped_before_period_end += 1; - continue; - } - } - stats.filings_eligible += 1; - filing_index.entry(key_kind).or_default().push(IndexedFiling { - et_date: pf.et_date, - utc_micros: pf.utc_micros, - is_amendment: pf.is_amendment, - }); - } - - for bucket in filing_index.values_mut() { - bucket.sort_unstable_by(|a, b| { - a.et_date - .cmp(&b.et_date) - .then_with(|| a.utc_micros.cmp(&b.utc_micros)) - .then_with(|| a.is_amendment.cmp(&b.is_amendment)) - }); - } - - let mut candidates: Vec> = Vec::with_capacity(eligible_obs.len()); - - for obs in eligible_obs { - let linked_micros = filing_index - .get(&(obs.key.clone(), obs.fiscal_period)) - .and_then(|bucket| match obs.report_date { - Some(rd) => { - // Earliest matching periodic filing (amended or unamended) on Eastern day `rd`. - // `rd > obs.period_end` is guaranteed by validation above. - let pos = bucket.partition_point(|f| f.et_date < rd); - bucket - .get(pos) - .filter(|f| f.et_date == rd) - .map(|f| f.utc_micros) - } - None => { - // Earliest matching non-amended periodic filing strictly after `period_end` - // and within the inclusive calendar-day inference window. - let window_end = i64::from(obs.period_end) - + i64::from(obs.fiscal_period.undated_link_window_days()); - let pos = bucket.partition_point(|f| f.et_date <= obs.period_end); - bucket[pos..] - .iter() - .take_while(|f| i64::from(f.et_date) <= window_end) - .find(|f| !f.is_amendment) - .map(|f| f.utc_micros) - } - }); - - let (known_at_utc_micros, known_at_source) = if let Some(micros) = linked_micros { - (micros, KNOWN_AT_SOURCE_FILING_TIMESTAMP) - } else { - let lag_days = obs.venue.lag_days(obs.fiscal_period); - let lag_date_i64 = i64::from(obs.period_end) + i64::from(lag_days); - - if let Some(rd) = obs.report_date { - if i64::from(rd) > lag_date_i64 { - stats.observations_dropped_unanchored_vintage += 1; - continue; - } - } - - let Ok(lag_date) = i32::try_from(lag_date_i64) else { - stats.observations_dropped_date_out_of_range += 1; - continue; - }; - let Ok(micros) = et_to_utc_micros( - lag_date, - FUNDAMENTALS_FALLBACK_HOUR_ET, - FUNDAMENTALS_FALLBACK_MINUTE_ET, - 0, - ) else { - stats.observations_dropped_date_out_of_range += 1; - continue; - }; - (micros, KNOWN_AT_SOURCE_STATUTORY_LAG) - }; - - candidates.push(CandidateRow { - row: FundamentalsRow { - key: obs.key, - period_end: obs.period_end, - fiscal_period: obs.fiscal_period, - currency: obs.currency, - known_at_utc_micros, - known_at_source, - fields: obs.fields, - }, - report_date: obs.report_date, - }); - } - - candidates.sort_unstable_by(|a, b| { - a.row - .key - .cmp(&b.row.key) - .then_with(|| a.row.period_end.cmp(&b.row.period_end)) - .then_with(|| a.row.known_at_utc_micros.cmp(&b.row.known_at_utc_micros)) - }); - - let mut rows: Vec> = Vec::with_capacity(candidates.len()); - let mut survivors: Vec = Vec::new(); - let total = candidates.len(); - let mut pe_start = 0usize; - - while pe_start < total { - let mut pe_end = pe_start + 1; - while pe_end < total - && candidates[pe_end].row.key == candidates[pe_start].row.key - && candidates[pe_end].row.period_end == candidates[pe_start].row.period_end - { - pe_end += 1; - } - - // Track the newest accepted `report_date` seen at an earlier `known_at_utc_micros` for - // each `FiscalPeriod` so only accepted newer versions can suppress a stale statutory-lag - // estimate. - let mut max_accepted_rd_q: Option = None; - let mut max_accepted_rd_fy: Option = None; - - let mut g_start = pe_start; - while g_start < pe_end { - let group_ts = candidates[g_start].row.known_at_utc_micros; - let mut g_end = g_start + 1; - while g_end < pe_end && candidates[g_end].row.known_at_utc_micros == group_ts { - g_end += 1; - } - - // Filter out stale dated statutory-lag candidates before duplicate/conflict checks - // so a superseded estimate cannot cause an eligible estimate at the same fallback - // timestamp to be rejected as conflicting. - survivors.clear(); - for idx in g_start..g_end { - let cand = &candidates[idx]; - let prior_max_rd = match cand.row.fiscal_period { - FiscalPeriod::Quarterly => max_accepted_rd_q, - FiscalPeriod::Annual => max_accepted_rd_fy, - }; - let is_stale_estimate = cand.row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG - && cand - .report_date - .is_some_and(|rd_a| prior_max_rd.is_some_and(|rd_b| rd_b > rd_a)); - if is_stale_estimate { - stats.observations_dropped_stale_estimate += 1; - } else { - survivors.push(idx); - } - } - - if survivors.is_empty() { - g_start = g_end; - continue; - } - - let first = &candidates[survivors[0]].row; - let all_identical = survivors[1..].iter().all(|&idx| { - let other = &candidates[idx].row; - first.fiscal_period == other.fiscal_period - && first.currency == other.currency - && first.known_at_source == other.known_at_source - && first.fields.bit_eq(&other.fields) - }); - - if !all_identical { - stats.duplicate_conflict_dropped += survivors.len(); - g_start = g_end; - continue; - } - - let mut group_max_rd: Option = None; - for &idx in &survivors { - if let Some(rd) = candidates[idx].report_date { - group_max_rd = Some(group_max_rd.map_or(rd, |m| m.max(rd))); - } - } - if let Some(rd) = group_max_rd { - let slot = match first.fiscal_period { - FiscalPeriod::Quarterly => &mut max_accepted_rd_q, - FiscalPeriod::Annual => &mut max_accepted_rd_fy, - }; - *slot = Some(slot.map_or(rd, |m| m.max(rd))); - } - - stats.duplicate_collapsed += survivors.len() - 1; - if first.known_at_source == KNOWN_AT_SOURCE_FILING_TIMESTAMP { - stats.rows_linked_to_filing += 1; - } else { - stats.rows_statutory_lag_estimate += 1; - } - if rows.last().is_none_or(|prev| prev.key != first.key) { - stats.keys_out += 1; - } - rows.push(first.clone()); - - g_start = g_end; - } - - pe_start = pe_end; - } - - stats.rows_out = rows.len(); - FundamentalsBuild { rows, stats } -} - -#[derive(Clone)] -struct ResolvedPeriod { - period_end: i32, - fiscal_period: FiscalPeriod, - currency: String, - known_at_utc_micros: i64, - known_at_source: &'static str, - fields: FundamentalsFields, - /// Per-field flag: `true` iff that `Some` field originated from a `statutory_lag_estimate` row. - field_estimated: [bool; 6], -} - -impl ResolvedPeriod { - #[inline] - fn from_row(row: &FundamentalsRow) -> Self { - let est = row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG; - let fields = row.fields.normalize_zeros(); - let field_estimated = [ - est && fields.revenue.is_some(), - est && fields.net_income.is_some(), - est && fields.operating_cash_flow.is_some(), - est && fields.total_assets.is_some(), - est && fields.total_equity.is_some(), - est && fields.shares_outstanding.is_some(), - ]; - Self { - period_end: row.period_end, - fiscal_period: row.fiscal_period, - currency: row.currency.clone(), - known_at_utc_micros: row.known_at_utc_micros, - known_at_source: row.known_at_source, - fields, - field_estimated, - } - } - - #[inline] - fn apply_update(&mut self, row: &FundamentalsRow) { - if self.fiscal_period != row.fiscal_period || self.currency != row.currency { - *self = Self::from_row(row); - return; - } - - let est = row.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG; - let incoming = row.fields.normalize_zeros(); - - if let Some(v) = incoming.revenue { - self.fields.revenue = Some(v); - self.field_estimated[0] = est; - } - if let Some(v) = incoming.net_income { - self.fields.net_income = Some(v); - self.field_estimated[1] = est; - } - if let Some(v) = incoming.operating_cash_flow { - self.fields.operating_cash_flow = Some(v); - self.field_estimated[2] = est; - } - if let Some(v) = incoming.total_assets { - self.fields.total_assets = Some(v); - self.field_estimated[3] = est; - } - if let Some(v) = incoming.total_equity { - self.fields.total_equity = Some(v); - self.field_estimated[4] = est; - } - if let Some(v) = incoming.shares_outstanding { - self.fields.shares_outstanding = Some(v); - self.field_estimated[5] = est; - } - - self.known_at_utc_micros = row.known_at_utc_micros; - self.known_at_source = row.known_at_source; - } - - #[inline] - fn has_estimated_lag(&self) -> bool { - self.known_at_source == KNOWN_AT_SOURCE_STATUTORY_LAG - || self.field_estimated.iter().any(|&e| e) - } - - #[inline] - fn to_slot(&self) -> FundamentalsPeriodSlot { - FundamentalsPeriodSlot { - period_end: self.period_end, - fiscal_period: self.fiscal_period, - currency: self.currency.clone(), - known_at_utc_micros: self.known_at_utc_micros, - known_at_source: self.known_at_source, - has_estimated_lag: self.has_estimated_lag(), - fields: self.fields, - } - } -} - -#[inline] -fn sum_4_flows(values: [Option; 4]) -> Option { - let [v0, v1, v2, v3] = values; - let sum = v3? + v2? + v1? + v0?; - if sum.is_finite() { - Some(normalize_zero(sum)) - } else { - None - } -} - -fn compute_ttm(visible_quarters: &BTreeMap) -> Option { - let quarters: [&ResolvedPeriod; TTM_QUARTER_COUNT] = { - let mut iter = visible_quarters.values().rev(); - let q0 = iter.next()?; - let q1 = iter.next()?; - let q2 = iter.next()?; - let q3 = iter.next()?; - [q0, q1, q2, q3] - }; - - let min_gap = i64::from(TTM_CONSECUTIVE_QUARTER_MIN_DAYS); - let max_gap = i64::from(TTM_CONSECUTIVE_QUARTER_MAX_DAYS); - for pair in quarters.windows(2) { - let gap = i64::from(pair[0].period_end) - i64::from(pair[1].period_end); - if gap < min_gap || gap > max_gap { - return None; - } - } - - let currency = &quarters[0].currency; - if !quarters[1..].iter().all(|q| &q.currency == currency) { - return None; - } - - let flows = TtmFlowFields { - revenue: sum_4_flows([ - quarters[0].fields.revenue, - quarters[1].fields.revenue, - quarters[2].fields.revenue, - quarters[3].fields.revenue, - ]), - net_income: sum_4_flows([ - quarters[0].fields.net_income, - quarters[1].fields.net_income, - quarters[2].fields.net_income, - quarters[3].fields.net_income, - ]), - operating_cash_flow: sum_4_flows([ - quarters[0].fields.operating_cash_flow, - quarters[1].fields.operating_cash_flow, - quarters[2].fields.operating_cash_flow, - quarters[3].fields.operating_cash_flow, - ]), - }; - - let has_estimated_lag = quarters.iter().any(|q| q.has_estimated_lag()); - - Some(FundamentalsTtm { - ending_period_end: quarters[0].period_end, - currency: currency.clone(), - flows, - has_estimated_lag, - }) -} - -/// Builds 2D point-in-time [`FundamentalsSnapshot`] records sorted by -/// `(key, effective_known_at_utc_micros)` from bitemporal [`FundamentalsRow`] inputs. -/// -/// Returns [`FundamentalsError::InvalidPeriodLimit`] if `k == 0`. -pub fn build_fundamentals_snapshots( - rows: &[FundamentalsRow], - k: usize, -) -> Result>, FundamentalsError> -where - K: Ord + Clone, -{ - if k == 0 { - return Err(FundamentalsError::InvalidPeriodLimit { k }); - } - if rows.is_empty() { - return Ok(Vec::new()); - } - - let mut order: Vec = (0..rows.len()).collect(); - order.sort_unstable_by(|&a, &b| { - rows[a] - .key - .cmp(&rows[b].key) - .then_with(|| rows[a].known_at_utc_micros.cmp(&rows[b].known_at_utc_micros)) - .then_with(|| rows[a].period_end.cmp(&rows[b].period_end)) - .then_with(|| rows[a].fiscal_period.cmp(&rows[b].fiscal_period)) - }); - - let mut snapshots: Vec> = Vec::new(); - let total = order.len(); - let mut idx = 0usize; - - while idx < total { - let key = &rows[order[idx]].key; - let mut visible_periods: BTreeMap = BTreeMap::new(); - let mut visible_quarters: BTreeMap = BTreeMap::new(); - let mut visible_annuals: BTreeMap = BTreeMap::new(); - - while idx < total && &rows[order[idx]].key == key { - let effective_ts = rows[order[idx]].known_at_utc_micros; - - while idx < total - && &rows[order[idx]].key == key - && rows[order[idx]].known_at_utc_micros == effective_ts - { - let row = &rows[order[idx]]; - let by_kind = match row.fiscal_period { - FiscalPeriod::Quarterly => &mut visible_quarters, - FiscalPeriod::Annual => &mut visible_annuals, - }; - let resolved = match by_kind.get_mut(&row.period_end) { - Some(existing) => { - existing.apply_update(row); - existing.clone() - } - None => { - let created = ResolvedPeriod::from_row(row); - by_kind.insert(row.period_end, created.clone()); - created - } - }; - visible_periods.insert(row.period_end, resolved); - idx += 1; - } - - let periods: Vec = visible_periods - .values() - .rev() - .take(k) - .map(ResolvedPeriod::to_slot) - .collect(); - let ttm = compute_ttm(&visible_quarters); - let has_estimated_lag = periods.iter().any(|p| p.has_estimated_lag) - || ttm.as_ref().is_some_and(|t| t.has_estimated_lag); - let known_at_source = if has_estimated_lag { - KNOWN_AT_SOURCE_STATUTORY_LAG - } else { - KNOWN_AT_SOURCE_FILING_TIMESTAMP - }; - - snapshots.push(FundamentalsSnapshot { - key: key.clone(), - effective_known_at_utc_micros: effective_ts, - known_at_source, - has_estimated_lag, - periods, - ttm, - }); - } - } - - Ok(snapshots) -} - -/// Returns the latest [`FundamentalsSnapshot`] for `key` with -/// `effective_known_at_utc_micros <= as_of_micros` (inclusive). -/// -/// Requires `snapshots` to be sorted by `(key, effective_known_at_utc_micros)` (as returned by -/// [`build_fundamentals_snapshots`]). -pub fn as_of<'a, K, Q>( - snapshots: &'a [FundamentalsSnapshot], - key: &Q, - as_of_micros: i64, -) -> Option<&'a FundamentalsSnapshot> -where - K: Borrow + Ord, - Q: Ord + ?Sized, -{ - let pos = snapshots.partition_point(|s| match s.key.borrow().cmp(key) { - Ordering::Less => true, - Ordering::Equal => s.effective_known_at_utc_micros <= as_of_micros, - Ordering::Greater => false, - }); - if pos == 0 { - return None; - } - let candidate = &snapshots[pos - 1]; - if candidate.key.borrow() == key { - Some(candidate) - } else { - None - } -} - -#[cfg(test)] -#[path = "fundamentals_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/fundamentals_tests.rs b/tools/curate-etl/src/fundamentals_tests.rs deleted file mode 100644 index a3919caf..00000000 --- a/tools/curate-etl/src/fundamentals_tests.rs +++ /dev/null @@ -1,1069 +0,0 @@ -use super::*; -use crate::split::ymd_to_epoch_days; - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid test date") -} - -fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8) -> i64 { - let epoch_day = day(y, m, d); - let secs = i64::from(epoch_day) * 86_400 - + i64::from(hour) * 3_600 - + i64::from(minute) * 60 - + i64::from(second); - secs * 1_000_000 -} - -fn filing(key: &str, timefiled: &str, form_type: &str) -> QmFiling { - QmFiling { - key: key.to_string(), - timefiled: timefiled.to_string(), - form_type: form_type.to_string(), - filing_id: None, - url: None, - } -} - -fn obs( - key: &str, - period_end: i32, - fiscal_period: FiscalPeriod, - currency: &str, - report_date: Option, - fields: FundamentalsFields, -) -> FinancialObservation { - FinancialObservation { - key: key.to_string(), - period_end, - fiscal_period, - currency: currency.to_string(), - report_date, - fields, - } -} - -fn fields_rev(rev: f64) -> FundamentalsFields { - FundamentalsFields { - revenue: Some(rev), - net_income: Some(rev * 0.1), - operating_cash_flow: Some(rev * 0.15), - total_assets: Some(rev * 5.0), - total_equity: Some(rev * 2.0), - shares_outstanding: Some(1_000.0), - } -} - -fn venues_map(entries: &[(&str, StatutoryLagVenue)]) -> BTreeMap { - entries - .iter() - .map(|&(k, v)| (k.to_string(), v)) - .collect() -} - -fn assert_reconciliation(build: &FundamentalsBuild) { - let s = &build.stats; - assert_eq!(s.rows_out, build.rows.len()); - assert_eq!( - s.rows_out, - s.rows_linked_to_filing + s.rows_statutory_lag_estimate, - "output provenance mismatch: {s:?}" - ); - assert_eq!( - s.observations_in, - s.rows_out - + s.observations_dropped_unknown_key - + s.observations_dropped_non_finite - + s.observations_dropped_date_out_of_range - + s.observations_dropped_report_date_not_after_period_end - + s.observations_dropped_unanchored_vintage - + s.observations_dropped_stale_estimate - + s.duplicate_collapsed - + s.duplicate_conflict_dropped, - "observation reconciliation failed: {s:?}" - ); - assert_eq!( - s.filings_in, - s.filings_eligible - + s.filings_dropped_unknown_key - + s.filings_ignored_non_periodic - + s.filings_dropped_invalid_timestamp - + s.filings_dropped_date_out_of_range - + s.filings_dropped_before_period_end, - "filing reconciliation failed: {s:?}" - ); - for pair in build.rows.windows(2) { - assert!( - (&pair[0].key, pair[0].period_end, pair[0].known_at_utc_micros) - < (&pair[1].key, pair[1].period_end, pair[1].known_at_utc_micros), - "rows must be strictly sorted and unique by (key, period_end, known_at_utc_micros)" - ); - } -} - -#[test] -fn restatement_of_q1_after_q2_updates_q1_and_ttm_without_overwriting_q2() { - let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); - - let p_2023_q3 = day(2023, 9, 30); - let p_2023_q4 = day(2023, 12, 31); - let p_2024_q1 = day(2024, 3, 31); - let p_2024_q2 = day(2024, 6, 30); - - let initial_filings = vec![ - filing("ACME", "2023-11-01T16:15:00 EDT", "10-Q"), - filing("ACME", "2024-02-01T16:15:00 EST", "10-Q"), - filing("ACME", "2024-05-01T16:15:00 EDT", "10-Q"), - filing("ACME", "2024-08-01T16:15:00 EDT", "10-Q"), - ]; - let amendment_filing = filing("ACME", "2024-09-15T17:00:00 EDT", "10-Q/A"); - - let initial_obs = vec![ - obs( - "ACME", - p_2023_q3, - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 11, 1)), - FundamentalsFields { - revenue: Some(70.0), - net_income: Some(7.0), - operating_cash_flow: Some(10.0), - total_assets: Some(500.0), - total_equity: Some(200.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - "ACME", - p_2023_q4, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 2, 1)), - FundamentalsFields { - revenue: Some(80.0), - net_income: Some(8.0), - operating_cash_flow: Some(12.0), - total_assets: Some(520.0), - total_equity: Some(210.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - "ACME", - p_2024_q1, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - FundamentalsFields { - revenue: Some(100.0), - net_income: Some(10.0), - operating_cash_flow: Some(15.0), - total_assets: Some(540.0), - total_equity: Some(220.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - "ACME", - p_2024_q2, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 8, 1)), - FundamentalsFields { - revenue: Some(120.0), - net_income: Some(12.0), - operating_cash_flow: Some(18.0), - total_assets: Some(560.0), - total_equity: Some(230.0), - shares_outstanding: Some(100.0), - }, - ), - ]; - - // Q1 amendment filed on 2024-09-15 (168 days after Q1 period end, beyond 75d window) - // Restates revenue from 100 -> 110 and omits operating_cash_flow & total_assets (None). - let q1_amendment = obs( - "ACME", - p_2024_q1, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 9, 15)), - FundamentalsFields { - revenue: Some(110.0), - net_income: Some(11.0), - operating_cash_flow: None, - total_assets: None, - total_equity: Some(225.0), - shares_outstanding: None, - }, - ); - - let mut full_obs = initial_obs.clone(); - full_obs.push(q1_amendment); - let mut full_filings = initial_filings.clone(); - full_filings.push(amendment_filing); - - let full_build = build_fundamentals_rows(full_obs, full_filings, &venues); - assert_reconciliation(&full_build); - assert_eq!(full_build.stats.rows_out, 5); - assert_eq!(full_build.stats.rows_linked_to_filing, 5); - assert_eq!(full_build.stats.rows_statutory_lag_estimate, 0); - - let full_snaps = build_fundamentals_snapshots(&full_build.rows, 4).unwrap(); - assert_eq!(full_snaps.len(), 5); - - let ts_q2 = utc_micros(2024, 8, 1, 20, 15, 0); - let ts_amend = utc_micros(2024, 9, 15, 21, 0, 0); - - // As-of strictly between Q2 filing and Q1 restatement (also check exact Q2 timestamp). - for probe in [ts_q2, ts_amend - 1] { - let snap = as_of(&full_snaps, "ACME", probe).expect("snapshot visible after Q2"); - assert_eq!(snap.effective_known_at_utc_micros, ts_q2); - assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!snap.has_estimated_lag); - assert_eq!(snap.periods[0].period_end, p_2024_q2); - assert_eq!(snap.periods[0].fields.revenue, Some(120.0)); - assert_eq!(snap.periods[1].period_end, p_2024_q1); - assert_eq!(snap.periods[1].fields.revenue, Some(100.0)); - assert_eq!(snap.periods[1].fields.operating_cash_flow, Some(15.0)); - let ttm = snap.ttm.as_ref().expect("4 consecutive quarters"); - assert_eq!(ttm.ending_period_end, p_2024_q2); - assert_eq!(ttm.flows.revenue, Some(370.0)); - assert_eq!(ttm.flows.net_income, Some(37.0)); - assert_eq!(ttm.flows.operating_cash_flow, Some(55.0)); - } - - // As-of at and after the Q1 restatement: Q2 stays latest and unchanged, Q1 updated + inherited, TTM updated. - for probe in [ts_amend, ts_amend + 1_000_000] { - let snap = as_of(&full_snaps, "ACME", probe).expect("snapshot visible at/after amendment"); - assert_eq!(snap.effective_known_at_utc_micros, ts_amend); - assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!snap.has_estimated_lag); - assert_eq!(snap.periods[0].period_end, p_2024_q2); - assert_eq!(snap.periods[0].fields.revenue, Some(120.0)); - assert_eq!(snap.periods[0].fields.total_assets, Some(560.0)); - assert_eq!(snap.periods[1].period_end, p_2024_q1); - assert_eq!(snap.periods[1].known_at_utc_micros, ts_amend); - assert_eq!(snap.periods[1].fields.revenue, Some(110.0)); - assert_eq!(snap.periods[1].fields.net_income, Some(11.0)); - // Omitted fields inherited from original Q1 - assert_eq!(snap.periods[1].fields.operating_cash_flow, Some(15.0)); - assert_eq!(snap.periods[1].fields.total_assets, Some(540.0)); - assert_eq!(snap.periods[1].fields.shares_outstanding, Some(100.0)); - assert_eq!(snap.periods[1].fields.total_equity, Some(225.0)); - let ttm = snap.ttm.as_ref().expect("4 consecutive quarters"); - assert_eq!(ttm.ending_period_end, p_2024_q2); - assert_eq!(ttm.flows.revenue, Some(380.0)); - assert_eq!(ttm.flows.net_income, Some(38.0)); - assert_eq!(ttm.flows.operating_cash_flow, Some(55.0)); - } - - // Truncation test: rebuild without future amendment and its filing; all earlier snapshots identical. - let trunc_build = build_fundamentals_rows(initial_obs, initial_filings, &venues); - assert_reconciliation(&trunc_build); - let trunc_snaps = build_fundamentals_snapshots(&trunc_build.rows, 4).unwrap(); - assert_eq!(trunc_snaps.len(), 4); - assert_eq!(&full_snaps[..4], &trunc_snaps[..]); -} - -#[test] -fn known_at_filing_linking_covers_all_periodic_forms_zones_windows_and_exclusions() { - let venues = venues_map(&[ - ("US_Q", StatutoryLagVenue::UsTsx), - ("US_A", StatutoryLagVenue::UsTsx), - ("CA_40F", StatutoryLagVenue::UsTsx), - ("SEDAR_Q", StatutoryLagVenue::TsxvCse), - ("SEDAR_A", StatutoryLagVenue::TsxvCse), - ("WIN_Q", StatutoryLagVenue::UsTsx), - ("WIN_A", StatutoryLagVenue::UsTsx), - ("NOISE", StatutoryLagVenue::UsTsx), - ]); - - let filings = vec![ - // Late-evening EDT filing whose UTC date is the next day (2024-05-11T01:30:00Z) - filing("US_Q", "2024-05-10T21:30:00 EDT", "10-Q"), - // EST annual 10-K - filing("US_A", "2024-03-01T08:15:30 EST", "10-K"), - // 40-F annual - filing("CA_40F", "2024-03-15T14:00:00 EDT", "40-F"), - // SEDAR interim & annual - filing("SEDAR_Q", "2024-05-20T18:00:00 EDT", "Interim financial statements/report - English"), - filing("SEDAR_A", "2024-04-20T12:30:00 EDT", "Annual financial statements - English"), - // Window boundary filings for undated quarterly (period_end = 2024-03-31 -> +75d = 2024-06-14, +76d = 2024-06-15) - // Also add an earlier 10-Q/A on 2024-05-01 which undated observation must ignore! - filing("WIN_Q", "2024-05-01T10:00:00 EDT", "10-Q/A"), - filing("WIN_Q", "2024-06-14T11:00:00 EDT", "10-Q"), - // Window boundary for undated annual (period_end = 2023-12-31 -> +150d = 2024-05-29, +151d = 2024-05-30) - filing("WIN_A", "2024-05-29T15:00:00 EDT", "10-K"), - // Non-periodic 8-K, wrong kind (10-K for quarterly), and wrong listing - filing("NOISE", "2024-05-05T09:00:00 EDT", "8-K"), - filing("NOISE", "2024-05-05T09:30:00 EDT", "News release"), - filing("NOISE", "2024-05-05T10:00:00 EDT", "10-K"), - ]; - - let observations = vec![ - // Same-day match across UTC midnight rollover (ET date = 2024-05-10) - obs("US_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", Some(day(2024, 5, 10)), fields_rev(10.0)), - obs("US_A", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(20.0)), - obs("CA_40F", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(30.0)), - obs("SEDAR_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(40.0)), - obs("SEDAR_A", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(50.0)), - // Exact +75d inclusive boundary -> links to 2024-06-14 10-Q (skipping 2024-05-01 10-Q/A) - obs("WIN_Q", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(60.0)), - // Exact +76d (period_end = 2024-03-30 -> 2024-06-14 is +76d) -> outside window, falls back! - obs("WIN_Q", day(2024, 3, 30), FiscalPeriod::Quarterly, "USD", None, fields_rev(61.0)), - // Exact +150d inclusive boundary -> links to 2024-05-29 10-K - obs("WIN_A", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(70.0)), - // Exact +151d (period_end = 2023-12-30 -> 2024-05-29 is +151d) -> outside window, falls back! - obs("WIN_A", day(2023, 12, 30), FiscalPeriod::Annual, "USD", None, fields_rev(71.0)), - // NOISE quarterly: 8-K, News release, and 10-K must NOT link -> statutory lag fallback - obs("NOISE", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(80.0)), - ]; - - let built = build_fundamentals_rows(observations, filings, &venues); - assert_reconciliation(&built); - assert_eq!(built.stats.filings_ignored_non_periodic, 2); - assert_eq!(built.stats.rows_linked_to_filing, 7); - assert_eq!(built.stats.rows_statutory_lag_estimate, 3); - - let find = |k: &str, pe: i32| { - built - .rows - .iter() - .find(|r| r.key == k && r.period_end == pe) - .expect("row present") - }; - - assert_eq!(find("US_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 11, 1, 30, 0)); - assert_eq!(find("US_Q", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert_eq!(find("US_A", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 1, 13, 15, 30)); - assert_eq!(find("CA_40F", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 15, 18, 0, 0)); - assert_eq!(find("SEDAR_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 20, 22, 0, 0)); - assert_eq!(find("SEDAR_A", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 4, 20, 16, 30, 0)); - - // Window boundaries - assert_eq!(find("WIN_Q", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert_eq!(find("WIN_Q", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 6, 14, 15, 0, 0)); - assert_eq!(find("WIN_Q", day(2024, 3, 30)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert_eq!(find("WIN_A", day(2023, 12, 31)).known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert_eq!(find("WIN_A", day(2023, 12, 30)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - - // 8-K and wrong-kind 10-K did not link - assert_eq!(find("NOISE", day(2024, 3, 31)).known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); -} - -#[test] -fn statutory_lag_fallback_exact_offsets_dst_boundary_and_unanchored_vintage() { - let venues = venues_map(&[ - ("US", StatutoryLagVenue::UsTsx), - ("VN", StatutoryLagVenue::TsxvCse), - ]); - - // Spring DST 2024 is Sunday 2024-03-10: - // - 2024-01-24 + 45d = 2024-03-09 (EST, UTC-5) -> 16:05 ET == 21:05 UTC - // - 2024-01-25 + 45d = 2024-03-10 (EDT, UTC-4) -> 16:05 ET == 20:05 UTC - let observations = vec![ - // US/TSX Quarterly (+45d) before DST - obs("US", day(2024, 1, 24), FiscalPeriod::Quarterly, "USD", None, fields_rev(10.0)), - // US/TSX Quarterly (+45d) on spring DST Sunday - obs("US", day(2024, 1, 25), FiscalPeriod::Quarterly, "USD", None, fields_rev(11.0)), - // US/TSX Annual (+90d): 2023-12-31 + 90d = 2024-03-30 (EDT, 2024 is leap year) - obs("US", day(2023, 12, 31), FiscalPeriod::Annual, "USD", None, fields_rev(20.0)), - // TSXV/CSE Quarterly (+60d): 2024-03-31 + 60d = 2024-05-30 (EDT) - obs("VN", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(30.0)), - // TSXV/CSE Annual (+120d): 2023-12-31 + 120d = 2024-04-29 (EDT) - obs("VN", day(2023, 12, 31), FiscalPeriod::Annual, "CAD", None, fields_rev(40.0)), - // Dated record with no same-day filing and report_date == lag_date -> allowed fallback - obs( - "US", - day(2024, 6, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 6, 30) + 45), - fields_rev(50.0), - ), - // Dated record with no same-day filing and report_date > lag_date -> dropped as unanchored vintage! - obs( - "US", - day(2024, 9, 30), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 9, 30) + 46), - fields_rev(60.0), - ), - ]; - - let built = build_fundamentals_rows(observations, Vec::>::new(), &venues); - assert_reconciliation(&built); - assert_eq!(built.stats.rows_out, 6); - assert_eq!(built.stats.rows_statutory_lag_estimate, 6); - assert_eq!(built.stats.observations_dropped_unanchored_vintage, 1); - - let find = |k: &str, pe: i32| { - built - .rows - .iter() - .find(|r| r.key == k && r.period_end == pe) - .expect("row present") - }; - - assert_eq!(find("US", day(2024, 1, 24)).known_at_utc_micros, utc_micros(2024, 3, 9, 21, 5, 0)); - assert_eq!(find("US", day(2024, 1, 25)).known_at_utc_micros, utc_micros(2024, 3, 10, 20, 5, 0)); - assert_eq!(find("US", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 3, 30, 20, 5, 0)); - assert_eq!(find("VN", day(2024, 3, 31)).known_at_utc_micros, utc_micros(2024, 5, 30, 20, 5, 0)); - assert_eq!(find("VN", day(2023, 12, 31)).known_at_utc_micros, utc_micros(2024, 4, 29, 20, 5, 0)); - assert_eq!( - find("US", day(2024, 6, 30)).known_at_utc_micros, - et_to_utc_micros(day(2024, 6, 30) + 45, 16, 5, 0).unwrap() - ); -} - -#[test] -fn ttm_handles_gaps_fy_rows_currency_missing_overflow_carry_forward_and_provenance() { - // 1. Quarter spacing boundaries (76 rejected, 77 accepted, 105 accepted, 106 rejected) - let make_row = |key: &str, pe: i32, kind: FiscalPeriod, curr: &str, ts: i64, src: &'static str, fields: FundamentalsFields| { - FundamentalsRow { - key: key.to_string(), - period_end: pe, - fiscal_period: kind, - currency: curr.to_string(), - known_at_utc_micros: ts, - known_at_source: src, - fields, - } - }; - - let base = day(2023, 1, 1); - // Exact 77-day spacing -> TTM computed - let rows_77 = vec![ - make_row("G77", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row("G77", base + 77, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row("G77", base + 154, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row("G77", base + 231, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), - ]; - let snaps_77 = build_fundamentals_snapshots(&rows_77, 2).unwrap(); - assert!(snaps_77[2].ttm.is_none()); // only 3 quarters - let ttm_77 = snaps_77[3].ttm.as_ref().expect("77d spacing is consecutive"); - assert_eq!(ttm_77.flows.revenue, Some(100.0)); - assert_eq!(ttm_77.ending_period_end, base + 231); - // Stock fields remain period values (not summed) - assert_eq!(snaps_77[3].periods[0].fields.total_assets, Some(200.0)); - assert_eq!(snaps_77[3].periods[0].fields.shares_outstanding, Some(1_000.0)); - - // 76-day gap -> None - let mut rows_76 = rows_77.clone(); - rows_76[3].period_end = base + 154 + 76; - assert!(build_fundamentals_snapshots(&rows_76, 4).unwrap()[3].ttm.is_none()); - - // 105-day spacing -> Some, 106-day gap -> None - let rows_105 = vec![ - make_row("G105", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row("G105", base + 105, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row("G105", base + 210, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row("G105", base + 315, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), - ]; - assert!(build_fundamentals_snapshots(&rows_105, 4).unwrap()[3].ttm.is_some()); - let mut rows_106 = rows_105.clone(); - rows_106[3].period_end = base + 210 + 106; - assert!(build_fundamentals_snapshots(&rows_106, 4).unwrap()[3].ttm.is_none()); - - // 2. Intervening FY row occupies a snapshot slot while TTM still uses the 4 standalone quarters - let rows_fy = vec![ - make_row("FY", day(2023, 3, 31), FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row("FY", day(2023, 6, 30), FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row("FY", day(2023, 9, 30), FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row("FY", day(2023, 12, 31), FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), - make_row("FY", day(2024, 1, 1), FiscalPeriod::Annual, "USD", 5, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)), - ]; - let snaps_fy = build_fundamentals_snapshots(&rows_fy, 2).unwrap(); - let last_fy = snaps_fy.last().unwrap(); - assert_eq!(last_fy.periods[0].fiscal_period, FiscalPeriod::Annual); - assert_eq!(last_fy.ttm.as_ref().unwrap().flows.revenue, Some(100.0)); - - // 3. Currency mismatch across 4 quarters -> TTM is None - let mut rows_curr = rows_77.clone(); - rows_curr[2].currency = "CAD".to_string(); - assert!(build_fundamentals_snapshots(&rows_curr, 4).unwrap()[3].ttm.is_none()); - - // 4. Missing flow input & overflow -> per-field None while other flow fields still sum - let mut rows_edge = rows_77.clone(); - rows_edge[1].fields.net_income = None; - rows_edge[0].fields.operating_cash_flow = Some(f64::MAX); - rows_edge[1].fields.operating_cash_flow = Some(f64::MAX); - let ttm_edge = build_fundamentals_snapshots(&rows_edge, 4).unwrap()[3] - .ttm - .clone() - .expect("ttm present"); - assert_eq!(ttm_edge.flows.revenue, Some(100.0)); - assert_eq!(ttm_edge.flows.net_income, None); - assert_eq!(ttm_edge.flows.operating_cash_flow, None); - - // 5. Carry-forward stays within same (period_end, kind, currency) and retains estimated provenance - let rows_cf = vec![ - // Initial Q1 with statutory_lag_estimate - make_row( - "CF", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - 10, - KNOWN_AT_SOURCE_STATUTORY_LAG, - FundamentalsFields { - revenue: Some(100.0), - net_income: Some(10.0), - operating_cash_flow: None, - total_assets: Some(500.0), - total_equity: None, - shares_outstanding: None, - }, - ), - // Filing restatement leaves net_income=None -> inherits net_income from estimated version -> still estimated! - make_row( - "CF", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - 20, - KNOWN_AT_SOURCE_FILING_TIMESTAMP, - FundamentalsFields { - revenue: Some(105.0), - net_income: None, - operating_cash_flow: Some(15.0), - total_assets: Some(505.0), - total_equity: None, - shares_outstanding: None, - }, - ), - // Currency change to CAD at t=30 -> does NOT carry forward USD fields; now purely filing_timestamp! - make_row( - "CF", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "CAD", - 30, - KNOWN_AT_SOURCE_FILING_TIMESTAMP, - FundamentalsFields { - revenue: Some(140.0), - net_income: None, - operating_cash_flow: None, - total_assets: None, - total_equity: None, - shares_outstanding: None, - }, - ), - ]; - let snaps_cf = build_fundamentals_snapshots(&rows_cf, 2).unwrap(); - assert!(snaps_cf[0].has_estimated_lag); - assert_eq!(snaps_cf[1].periods[0].fields.net_income, Some(10.0)); - assert!(snaps_cf[1].periods[0].has_estimated_lag); - assert!(snaps_cf[1].has_estimated_lag); - assert_eq!(snaps_cf[1].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - // After currency change, no carry-forward from USD estimated row - assert_eq!(snaps_cf[2].periods[0].fields.net_income, None); - assert!(!snaps_cf[2].periods[0].has_estimated_lag); - assert!(!snaps_cf[2].has_estimated_lag); - assert_eq!(snaps_cf[2].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - - // 6. Estimated TTM contributor outside displayed k=2 slots flags the snapshot as estimated - let rows_ttm_est = vec![ - make_row("EST", base, FiscalPeriod::Quarterly, "USD", 1, KNOWN_AT_SOURCE_STATUTORY_LAG, fields_rev(10.0)), - make_row("EST", base + 90, FiscalPeriod::Quarterly, "USD", 2, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row("EST", base + 180, FiscalPeriod::Quarterly, "USD", 3, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row("EST", base + 270, FiscalPeriod::Quarterly, "USD", 4, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), - ]; - let snaps_est = build_fundamentals_snapshots(&rows_ttm_est, 2).unwrap(); - let s4 = &snaps_est[3]; - assert_eq!(s4.periods.len(), 2); - assert!(s4.periods.iter().all(|p| !p.has_estimated_lag)); - assert!(s4.ttm.as_ref().unwrap().has_estimated_lag); - assert!(s4.has_estimated_lag); - assert_eq!(s4.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - - // 7. Multiple updates at the same timestamp produce one combined snapshot + as_of edge cases - let rows_same_ts = vec![ - make_row("M", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row("M", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - ]; - let snaps_same = build_fundamentals_snapshots(&rows_same_ts, 4).unwrap(); - assert_eq!(snaps_same.len(), 1); - assert_eq!(snaps_same[0].periods.len(), 2); - assert!(as_of(&snaps_same, "M", 99).is_none()); - assert_eq!(as_of(&snaps_same, "M", 100), Some(&snaps_same[0])); - assert!(as_of(&snaps_same, "UNKNOWN", 100).is_none()); - - // 8. k == 0 rejected with typed error - assert_eq!( - build_fundamentals_snapshots(&rows_same_ts, 0), - Err(FundamentalsError::InvalidPeriodLimit { k: 0 }) - ); -} - -#[test] -fn robustness_bad_rows_dedup_conflicts_and_input_order_determinism() { - let venues = venues_map(&[ - ("A", StatutoryLagVenue::UsTsx), - ("B", StatutoryLagVenue::TsxvCse), - ]); - - let observations = vec![ - // Valid linked observation (with -0.0 normalized to 0.0) + exact duplicate - obs( - "A", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - FundamentalsFields { - revenue: Some(-0.0), - net_income: Some(5.0), - operating_cash_flow: Some(6.0), - total_assets: Some(100.0), - total_equity: Some(50.0), - shares_outstanding: Some(10.0), - }, - ), - obs( - "A", - day(2024, 3, 31), - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - FundamentalsFields { - revenue: Some(0.0), - net_income: Some(5.0), - operating_cash_flow: Some(6.0), - total_assets: Some(100.0), - total_equity: Some(50.0), - shares_outstanding: Some(10.0), - }, - ), - // Conflicting duplicate pair on B (same period_end & known_at, differing revenue) - obs("B", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(10.0)), - obs("B", day(2024, 3, 31), FiscalPeriod::Quarterly, "CAD", None, fields_rev(11.0)), - // Unknown key - obs("UNKNOWN", day(2024, 3, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)), - // Non-finite values (NaN, +inf, -inf) - obs( - "A", - day(2024, 6, 30), - FiscalPeriod::Quarterly, - "USD", - None, - FundamentalsFields { - revenue: Some(f64::NAN), - ..Default::default() - }, - ), - obs( - "A", - day(2024, 6, 30), - FiscalPeriod::Quarterly, - "USD", - None, - FundamentalsFields { - total_assets: Some(f64::INFINITY), - ..Default::default() - }, - ), - // Out-of-range period_end, report_date, and lag_date - obs("A", day(2007, 12, 31), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)), - obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2031, 1, 1)), fields_rev(1.0)), - obs("A", day(2030, 12, 1), FiscalPeriod::Quarterly, "USD", None, fields_rev(1.0)), - // Explicit report_date <= period_end - obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2024, 6, 30)), fields_rev(1.0)), - // Valid second period for A to verify early filing anchored earlier period, not dropped - obs("A", day(2024, 6, 30), FiscalPeriod::Quarterly, "USD", Some(day(2024, 8, 1)), fields_rev(25.0)), - ]; - - let filings = vec![ - // Legitimate filings for A Q1 and Q2 (Q1 filing predates Q2 period_end, must NOT be dropped!) - filing("A", "2024-05-01T16:10:00 EDT", "10-Q"), - filing("A", "2024-08-01T16:10:00 EDT", "10-Q"), - // Early filing on or before A's earliest quarterly period_end (2024-03-31) -> dropped - filing("A", "2024-03-31T16:00:00 EDT", "10-Q"), - // Unknown key - filing("UNKNOWN", "2024-05-01T16:10:00 EDT", "10-Q"), - // Non-periodic - filing("A", "2024-05-02T16:10:00 EDT", "8-K"), - // Invalid timestamps (malformed, unknown zone, invalid date) - filing("A", "not-a-date", "10-Q"), - filing("A", "2024-05-01T16:10:00 UTC", "10-Q"), - filing("A", "2024-02-30T16:10:00 EST", "10-Q"), - // Out-of-range Eastern filing date - filing("A", "2007-12-31T16:10:00 EST", "10-Q"), - ]; - - let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); - assert_reconciliation(&built); - - assert_eq!(built.stats.observations_in, 12); - assert_eq!(built.stats.rows_out, 2); - assert_eq!(built.stats.keys_out, 1); - assert_eq!(built.stats.rows_linked_to_filing, 2); - assert_eq!(built.stats.rows_statutory_lag_estimate, 0); - assert_eq!(built.stats.observations_dropped_unknown_key, 1); - assert_eq!(built.stats.observations_dropped_non_finite, 2); - assert_eq!(built.stats.observations_dropped_date_out_of_range, 3); - assert_eq!(built.stats.observations_dropped_report_date_not_after_period_end, 1); - assert_eq!(built.stats.duplicate_collapsed, 1); - assert_eq!(built.stats.duplicate_conflict_dropped, 2); - - assert_eq!(built.stats.filings_in, 9); - assert_eq!(built.stats.filings_eligible, 2); - assert_eq!(built.stats.filings_dropped_unknown_key, 1); - assert_eq!(built.stats.filings_ignored_non_periodic, 1); - assert_eq!(built.stats.filings_dropped_invalid_timestamp, 3); - assert_eq!(built.stats.filings_dropped_date_out_of_range, 1); - assert_eq!(built.stats.filings_dropped_before_period_end, 1); - - // -0.0 normalized to +0.0 - assert_eq!(built.rows[0].fields.revenue.unwrap().to_bits(), 0.0_f64.to_bits()); - - // Input-order determinism: reversed and rotated inputs yield identical rows, snapshots, and stats - let mut obs_rev = observations.clone(); - obs_rev.reverse(); - let mut fil_rev = filings.clone(); - fil_rev.reverse(); - let built_rev = build_fundamentals_rows(obs_rev, fil_rev, &venues); - assert_eq!(built, built_rev); - - let mut obs_rot = observations; - obs_rot.rotate_left(5); - let mut fil_rot = filings; - fil_rot.rotate_left(4); - let built_rot = build_fundamentals_rows(obs_rot, fil_rot, &venues); - assert_eq!(built, built_rot); - - let snaps_a = build_fundamentals_snapshots(&built.rows, 4).unwrap(); - let snaps_b = build_fundamentals_snapshots(&built_rev.rows, 4).unwrap(); - assert_eq!(snaps_a, snaps_b); -} - -#[test] -fn stale_statutory_lag_estimate_does_not_overwrite_newer_filed_version() { - let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); - let q1_end = day(2024, 3, 31); - - // Apr 30 observation has no same-day periodic filing -> would fall back to May 15 16:05 ET. - // May 10 observation links to a 10-Q -> visible May 10 16:15 ET. - // Because Apr 30 is an older report vintage than May 10, the stale estimate must be dropped - // so revenue stays 110 at and after May 15 instead of reverting to 100. - let filings = vec![filing("ACME", "2024-05-10T16:15:00 EDT", "10-Q")]; - let observations = vec![ - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 4, 30)), - fields_rev(100.0), - ), - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 10)), - fields_rev(110.0), - ), - ]; - - let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); - assert_reconciliation(&built); - assert_eq!(built.stats.rows_out, 1); - assert_eq!(built.stats.rows_linked_to_filing, 1); - assert_eq!(built.stats.rows_statutory_lag_estimate, 0); - assert_eq!(built.stats.observations_dropped_stale_estimate, 1); - - // Input-order determinism with stale estimate present - let mut obs_rev = observations; - obs_rev.reverse(); - assert_eq!(built, build_fundamentals_rows(obs_rev, filings, &venues)); - - let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); - assert_eq!(snaps.len(), 1); - - let ts_may_10 = utc_micros(2024, 5, 10, 20, 15, 0); - let ts_may_15_fallback = et_to_utc_micros(day(2024, 5, 15), 16, 5, 0).unwrap(); - - for probe in [ts_may_10, ts_may_15_fallback, ts_may_15_fallback + 1_000_000] { - let snap = as_of(&snaps, "ACME", probe).expect("snapshot visible"); - assert_eq!(snap.effective_known_at_utc_micros, ts_may_10); - assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!snap.has_estimated_lag); - assert_eq!(snap.periods[0].period_end, q1_end); - assert_eq!(snap.periods[0].fields.revenue, Some(110.0)); - } - - // Edge cases: - // (a) An earlier estimate (Apr 30 -> May 15) followed by a LATER filing (Jun 1) is NOT stale. - // (b) A linked FY filing sharing Dec 31 does NOT suppress a standalone Q4 estimate. - let edge_filings = vec![ - filing("ACME", "2024-06-01T17:00:00 EDT", "10-Q/A"), - filing("ACME", "2024-02-12T16:15:00 EST", "10-K"), - ]; - let dec_31 = day(2023, 12, 31); - let edge_obs = vec![ - obs("ACME", q1_end, FiscalPeriod::Quarterly, "USD", Some(day(2024, 4, 30)), fields_rev(100.0)), - obs("ACME", q1_end, FiscalPeriod::Quarterly, "USD", Some(day(2024, 6, 1)), fields_rev(115.0)), - obs("ACME", dec_31, FiscalPeriod::Quarterly, "USD", Some(day(2024, 2, 10)), fields_rev(40.0)), - obs("ACME", dec_31, FiscalPeriod::Annual, "USD", Some(day(2024, 2, 12)), fields_rev(160.0)), - ]; - let edge_built = build_fundamentals_rows(edge_obs, edge_filings, &venues); - assert_reconciliation(&edge_built); - assert_eq!(edge_built.stats.observations_dropped_stale_estimate, 0); - assert_eq!(edge_built.stats.rows_out, 4); -} - -#[test] -fn conflicting_newer_filing_does_not_suppress_eligible_statutory_lag_estimate() { - let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); - let q1_end = day(2024, 3, 31); - - // Apr 30 observation (rev 100) has no same-day filing -> May 15 16:05 ET fallback. - // Two May 10 observations link to the same 10-Q with conflicting revenues (110 vs 112). - // Because the May 10 group is rejected as a duplicate conflict, it must NOT suppress the - // eligible Apr 30 statutory-lag estimate. - let filings = vec![filing("ACME", "2024-05-10T16:15:00 EDT", "10-Q")]; - let observations = vec![ - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 4, 30)), - fields_rev(100.0), - ), - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 10)), - fields_rev(110.0), - ), - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 10)), - fields_rev(112.0), - ), - ]; - - let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); - assert_reconciliation(&built); - assert_eq!(built.stats.duplicate_conflict_dropped, 2); - assert_eq!(built.stats.observations_dropped_stale_estimate, 0); - assert_eq!(built.stats.rows_out, 1); - assert_eq!(built.stats.rows_linked_to_filing, 0); - assert_eq!(built.stats.rows_statutory_lag_estimate, 1); - - // Input-order determinism - let mut obs_rev = observations; - obs_rev.reverse(); - assert_eq!(built, build_fundamentals_rows(obs_rev, filings, &venues)); - - let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); - let ts_may_10 = utc_micros(2024, 5, 10, 20, 15, 0); - let ts_may_15_fallback = et_to_utc_micros(day(2024, 5, 15), 16, 5, 0).unwrap(); - - assert!(as_of(&snaps, "ACME", ts_may_10).is_none()); - assert!(as_of(&snaps, "ACME", ts_may_15_fallback - 1).is_none()); - - let snap = as_of(&snaps, "ACME", ts_may_15_fallback).expect("fallback estimate must be visible"); - assert_eq!(snap.effective_known_at_utc_micros, ts_may_15_fallback); - assert_eq!(snap.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert!(snap.has_estimated_lag); - assert_eq!(snap.periods[0].period_end, q1_end); - assert_eq!(snap.periods[0].fields.revenue, Some(100.0)); -} - -#[test] -fn stale_estimate_at_same_fallback_timestamp_does_not_conflict_with_eligible_estimate() { - let venues = venues_map(&[("ACME", StatutoryLagVenue::UsTsx)]); - let q1_end = day(2024, 3, 31); - - // Apr 30 (rev 100) and May 12 (rev 115) have no same-day periodic filing -> both get the - // May 15 16:05 ET fallback timestamp. The accepted May 10 10-Q (rev 110) supersedes Apr 30, - // so Apr 30 must be dropped as a stale estimate before duplicate/conflict checks and must - // not cause the eligible May 12 estimate to be discarded as a conflict. - let filings = vec![filing("ACME", "2024-05-10T16:15:00 EDT", "10-Q")]; - let observations = vec![ - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 4, 30)), - fields_rev(100.0), - ), - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 10)), - fields_rev(110.0), - ), - obs( - "ACME", - q1_end, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 12)), - fields_rev(115.0), - ), - ]; - - let built = build_fundamentals_rows(observations.clone(), filings.clone(), &venues); - assert_reconciliation(&built); - assert_eq!(built.stats.observations_dropped_stale_estimate, 1); - assert_eq!(built.stats.duplicate_conflict_dropped, 0); - assert_eq!(built.stats.rows_out, 2); - assert_eq!(built.stats.rows_linked_to_filing, 1); - assert_eq!(built.stats.rows_statutory_lag_estimate, 1); - - // Input-order determinism - let mut obs_rev = observations; - obs_rev.reverse(); - assert_eq!(built, build_fundamentals_rows(obs_rev, filings, &venues)); - - let snaps = build_fundamentals_snapshots(&built.rows, 4).unwrap(); - let ts_may_15_fallback = et_to_utc_micros(day(2024, 5, 15), 16, 5, 0).unwrap(); - - let before_fallback = as_of(&snaps, "ACME", ts_may_15_fallback - 1) - .expect("May 10 10-Q must be visible before fallback"); - assert_eq!(before_fallback.periods[0].period_end, q1_end); - assert_eq!(before_fallback.periods[0].fields.revenue, Some(110.0)); - assert_eq!(before_fallback.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!before_fallback.has_estimated_lag); - - let at_fallback = as_of(&snaps, "ACME", ts_may_15_fallback) - .expect("May 12 estimate must be visible at fallback cutoff"); - assert_eq!(at_fallback.effective_known_at_utc_micros, ts_may_15_fallback); - assert_eq!(at_fallback.periods[0].period_end, q1_end); - assert_eq!(at_fallback.periods[0].fields.revenue, Some(115.0)); - assert_eq!(at_fallback.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert!(at_fallback.has_estimated_lag); -} - -#[test] -fn annual_fy_sharing_q4_period_end_preserves_standalone_q4_for_ttm() { - let make_row = |pe: i32, kind: FiscalPeriod, ts: i64, src: &'static str, fields: FundamentalsFields| { - FundamentalsRow { - key: "CAL".to_string(), - period_end: pe, - fiscal_period: kind, - currency: "USD".to_string(), - known_at_utc_micros: ts, - known_at_source: src, - fields, - } - }; - - let q1 = day(2023, 3, 31); - let q2 = day(2023, 6, 30); - let q3 = day(2023, 9, 30); - let q4_fy = day(2023, 12, 31); - - let rows = vec![ - make_row(q1, FiscalPeriod::Quarterly, 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row(q2, FiscalPeriod::Quarterly, 200, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row(q3, FiscalPeriod::Quarterly, 300, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row(q4_fy, FiscalPeriod::Quarterly, 400, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(40.0)), - // Later FY report sharing December 31 period_end - make_row(q4_fy, FiscalPeriod::Annual, 500, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)), - // Even later Q4 restatement omitting operating_cash_flow -> should inherit original Q4's OCF - make_row( - q4_fy, - FiscalPeriod::Quarterly, - 600, - KNOWN_AT_SOURCE_FILING_TIMESTAMP, - FundamentalsFields { - revenue: Some(45.0), - net_income: Some(4.5), - operating_cash_flow: None, - total_assets: Some(210.0), - total_equity: Some(85.0), - shares_outstanding: Some(1_000.0), - }, - ), - // Partial FY amendment after the Q4 amendment -> should inherit original FY's OCF (15.0) - make_row( - q4_fy, - FiscalPeriod::Annual, - 700, - KNOWN_AT_SOURCE_FILING_TIMESTAMP, - FundamentalsFields { - revenue: Some(102.0), - net_income: Some(10.2), - operating_cash_flow: None, - total_assets: Some(220.0), - total_equity: Some(90.0), - shares_outstanding: Some(1_000.0), - }, - ), - ]; - - let snaps = build_fundamentals_snapshots(&rows, 4).unwrap(); - assert_eq!(snaps.len(), 7); - - // At t=400 (Q4 visible): TTM ends 2023-12-31 with revenue 100 - let s4 = as_of(&snaps, "CAL", 400).unwrap(); - assert_eq!(s4.periods[0].period_end, q4_fy); - assert_eq!(s4.periods[0].fiscal_period, FiscalPeriod::Quarterly); - assert_eq!(s4.ttm.as_ref().unwrap().ending_period_end, q4_fy); - assert_eq!(s4.ttm.as_ref().unwrap().flows.revenue, Some(100.0)); - - // At t=500 (FY shares 2023-12-31): latest slot is FY, while TTM still uses all 4 standalone quarters - let s5 = as_of(&snaps, "CAL", 500).unwrap(); - assert_eq!(s5.periods[0].period_end, q4_fy); - assert_eq!(s5.periods[0].fiscal_period, FiscalPeriod::Annual); - assert_eq!(s5.periods[0].fields.revenue, Some(100.0)); - let ttm5 = s5.ttm.as_ref().expect("TTM must survive FY sharing Dec 31"); - assert_eq!(ttm5.ending_period_end, q4_fy); - assert_eq!(ttm5.flows.revenue, Some(100.0)); - assert_eq!(ttm5.flows.net_income, Some(10.0)); - assert_eq!(ttm5.flows.operating_cash_flow, Some(15.0)); - - // At t=600 (Q4 restatement after FY): inherits original Q4's operating_cash_flow (6.0), TTM updates to 105 - let s6 = as_of(&snaps, "CAL", 600).unwrap(); - assert_eq!(s6.periods[0].period_end, q4_fy); - assert_eq!(s6.periods[0].fiscal_period, FiscalPeriod::Quarterly); - assert_eq!(s6.periods[0].fields.revenue, Some(45.0)); - assert_eq!(s6.periods[0].fields.operating_cash_flow, Some(6.0)); - let ttm6 = s6.ttm.as_ref().expect("TTM after Q4 restatement"); - assert_eq!(ttm6.ending_period_end, q4_fy); - assert_eq!(ttm6.flows.revenue, Some(105.0)); - assert_eq!(ttm6.flows.operating_cash_flow, Some(15.0)); - - // At t=700 (partial FY amendment after Q4 amendment): inherits original FY's OCF (15.0) while - // TTM remains backed by the 4 standalone quarters (rev 105, OCF 15). - let s7 = as_of(&snaps, "CAL", 700).unwrap(); - assert_eq!(s7.periods[0].period_end, q4_fy); - assert_eq!(s7.periods[0].fiscal_period, FiscalPeriod::Annual); - assert_eq!(s7.periods[0].fields.revenue, Some(102.0)); - assert_eq!(s7.periods[0].fields.operating_cash_flow, Some(15.0)); - let ttm7 = s7.ttm.as_ref().expect("TTM after partial FY amendment"); - assert_eq!(ttm7.ending_period_end, q4_fy); - assert_eq!(ttm7.flows.revenue, Some(105.0)); - assert_eq!(ttm7.flows.operating_cash_flow, Some(15.0)); - - // Provenance check: if Q4 was statutory_lag_estimate and later FY (filing_timestamp) occupies - // periods[0] on Dec 31, TTM still uses estimated Q4 so snapshot stays flagged estimated. - let rows_est_q4 = vec![ - make_row(q1, FiscalPeriod::Quarterly, 100, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(10.0)), - make_row(q2, FiscalPeriod::Quarterly, 200, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(20.0)), - make_row(q3, FiscalPeriod::Quarterly, 300, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(30.0)), - make_row(q4_fy, FiscalPeriod::Quarterly, 400, KNOWN_AT_SOURCE_STATUTORY_LAG, fields_rev(40.0)), - make_row(q4_fy, FiscalPeriod::Annual, 500, KNOWN_AT_SOURCE_FILING_TIMESTAMP, fields_rev(100.0)), - ]; - let snaps_est = build_fundamentals_snapshots(&rows_est_q4, 4).unwrap(); - let fy_snap = as_of(&snaps_est, "CAL", 500).unwrap(); - assert!(!fy_snap.periods[0].has_estimated_lag); - assert!(fy_snap.ttm.as_ref().unwrap().has_estimated_lag); - assert!(fy_snap.has_estimated_lag); - assert_eq!(fy_snap.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); -} diff --git a/tools/curate-etl/src/ilp.rs b/tools/curate-etl/src/ilp.rs deleted file mode 100644 index 54a5691e..00000000 --- a/tools/curate-etl/src/ilp.rs +++ /dev/null @@ -1,567 +0,0 @@ -//! Pure, socket-free QuestDB ILP v2 line encoder and sharded batch writer for -//! `bars_1m` and `fx_1m`. -//! -//! # Wire format (QuestDB ILP Protocol Version 2) -//! -//! Verified against the official `questdb-rs` client source in -//! `questdb/c-questdb-client` (`main` branch, `questdb-rs`): -//! - Binary `DOUBLE` type tag (`DOUBLE_TYPE = 16` / `0x10`): -//! `questdb-rs/src/ingress.rs` lines 157–159. -//! - Tag/field separators and binary `f64` field encoding (`==\x10<8 LE IEEE-754 bytes>`): -//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 569–713. -//! - ILP escaping for `SYMBOL` values (space, `,`, `=`, `\n`, `\r`, and `\` prefixed with `\`): -//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 36–84. -//! - Timestamp column microsecond suffix (`=t`): -//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1026–1047. -//! - Designated timestamp microsecond suffix (` t\n`, non-negative): -//! `questdb-rs/src/ingress/buffer/ilp.rs` lines 1087–1116. -//! -//! # Table contracts -//! -//! Column names and types match `M2_INTRADAY_SCHEMAS` in `libs/data/questdb/src/schema.ts` -//! and `design/DATA-CONTRACTS.md` §3.B: -//! - `bars_1m`: symbols `listing_id`, `session`, `source`; binary doubles `open`, `high`, `low`, -//! `close`, `volume` (`vwap` is omitted / NULL); timestamp column `known_at`; designated -//! timestamp `ts` (UTC microseconds). -//! - `fx_1m`: symbols `pair`, `source`; binary doubles `open`, `high`, `low`, `close`; -//! designated timestamp `ts` (UTC microseconds). -//! -//! # Deterministic sharding -//! -//! [`IlpShardedWriter`] routes rows deterministically using 64-bit FNV-1a modulo shard count -//! (`fnv1a_64(key_bytes) % shard_count`): -//! - `bars_1m` hashes `listing_id` as its 4-byte little-endian representation -//! (`listing_id.to_le_bytes()`). -//! - `fx_1m` hashes `pair` as its raw UTF-8 bytes (`pair.as_bytes()`). -//! -//! All rows for a given key always land on the same shard in their exact input order, preserving -//! the per-key ordering required by `DEDUP UPSERT KEYS(ts, listing_id)` / `KEYS(ts, pair)`. - -use std::error::Error; -use std::fmt; -use std::io::{self, Write}; - -use crate::bars_1m::Bar1mRow; - -/// QuestDB ILP v2 binary `DOUBLE` type byte (`16` / `0x10`). -pub const ILP_V2_DOUBLE_TYPE: u8 = 0x10; - -/// Canonical QuestDB table name for 1-minute equity bars. -pub const TABLE_BARS_1M: &str = "bars_1m"; - -/// Canonical QuestDB table name for 1-minute FX bars. -pub const TABLE_FX_1M: &str = "fx_1m"; - -/// 64-bit FNV-1a offset basis used for deterministic shard routing. -pub const FNV1A_64_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; - -/// 64-bit FNV-1a prime used for deterministic shard routing. -pub const FNV1A_64_PRIME: u64 = 0x0000_0100_0000_01b3; - -/// Default maximum buffered bytes per shard before flushing a batch (1 MiB). -pub const DEFAULT_ILP_MAX_BATCH_BYTES: usize = 1_048_576; - -/// Default maximum buffered rows per shard before flushing a batch. -pub const DEFAULT_ILP_MAX_BATCH_ROWS: usize = 10_000; - -/// A single `fx_1m` 1-minute FX bar input for QuestDB ILP v2 encoding. -/// -/// Matches `M2_INTRADAY_SCHEMAS.fx_1m` in `libs/data/questdb/src/schema.ts`: -/// `pair` (SYMBOL), `open`/`high`/`low`/`close` (DOUBLE), `source` (SYMBOL), `ts` (TIMESTAMP). -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Fx1mRow<'a> { - pub pair: &'a str, - /// Bar start timestamp in UTC microseconds since the Unix epoch (must be `>= 0`). - pub ts: i64, - pub open: f64, - pub high: f64, - pub low: f64, - pub close: f64, - pub source: &'a str, -} - -/// Typed validation errors returned by [`encode_bar_1m`] and [`encode_fx_1m`]. -/// -/// Encoding is atomic: when an error is returned, the caller's destination buffer is left -/// completely unmodified. -#[derive(Debug, Clone, PartialEq)] -pub enum IlpEncodeError { - /// A `DOUBLE` field was non-finite (`NaN`, `+inf`, or `-inf`). - NonFiniteDouble { field: &'static str, value: f64 }, - /// The designated timestamp `ts` was negative (QuestDB ILP requires `ts >= 0`). - NegativeTimestamp { field: &'static str, value: i64 }, - /// A required `SYMBOL` column value was empty. - EmptySymbol { field: &'static str }, -} - -impl fmt::Display for IlpEncodeError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - Self::NonFiniteDouble { field, value } => { - write!(f, "non-finite ILP double field '{field}': {value}") - } - Self::NegativeTimestamp { field, value } => { - write!( - f, - "negative ILP designated timestamp '{field}': {value} (must be >= 0)" - ) - } - Self::EmptySymbol { field } => { - write!(f, "empty ILP symbol field '{field}'") - } - } - } -} - -impl Error for IlpEncodeError {} - -/// Batching limits for [`IlpShardedWriter`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct IlpWriterOptions { - /// Maximum buffered bytes per shard before flushing (must be `>= 1`). - pub max_batch_bytes: usize, - /// Maximum buffered rows per shard before flushing (must be `>= 1`). - pub max_batch_rows: usize, -} - -impl Default for IlpWriterOptions { - fn default() -> Self { - Self { - max_batch_bytes: DEFAULT_ILP_MAX_BATCH_BYTES, - max_batch_rows: DEFAULT_ILP_MAX_BATCH_ROWS, - } - } -} - -/// Summary statistics returned by [`IlpShardedWriter::finish`]. -/// -/// Conservation invariants: -/// - `per_shard_rows.iter().sum::() == rows` -/// - `bytes` equals the exact sum of bytes written across all successful shard `write_all` calls. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct IlpWriteStats { - pub rows: usize, - pub bytes: usize, - pub flushes: usize, - pub per_shard_rows: Vec, -} - -/// Typed errors returned by [`IlpShardedWriter`]. -#[derive(Debug)] -pub enum IlpWriterError { - /// No sinks were provided to [`IlpShardedWriter::new`]. - EmptySinks, - /// [`IlpWriterOptions::max_batch_bytes`] was `0`. - ZeroMaxBatchBytes, - /// [`IlpWriterOptions::max_batch_rows`] was `0`. - ZeroMaxBatchRows, - /// Row encoding failed before mutating any shard buffer. - Encode(IlpEncodeError), - /// A sink `write_all` or `flush` call failed on `shard`. - Io { shard: usize, source: io::Error }, - /// A previous I/O failure on `failed_shard` poisoned the writer; no further writes are allowed. - Poisoned { failed_shard: usize }, -} - -impl fmt::Display for IlpWriterError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::EmptySinks => write!(f, "ILP sharded writer requires at least one sink"), - Self::ZeroMaxBatchBytes => { - write!(f, "ILP writer max_batch_bytes must be >= 1") - } - Self::ZeroMaxBatchRows => { - write!(f, "ILP writer max_batch_rows must be >= 1") - } - Self::Encode(err) => write!(f, "ILP encode error: {err}"), - Self::Io { shard, source } => { - write!(f, "ILP writer I/O error on shard {shard}: {source}") - } - Self::Poisoned { failed_shard } => write!( - f, - "ILP writer is poisoned after prior I/O error on shard {failed_shard}" - ), - } - } -} - -impl Error for IlpWriterError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::Encode(err) => Some(err), - Self::Io { source, .. } => Some(source), - Self::EmptySinks - | Self::ZeroMaxBatchBytes - | Self::ZeroMaxBatchRows - | Self::Poisoned { .. } => None, - } - } -} - -impl From for IlpWriterError { - fn from(err: IlpEncodeError) -> Self { - Self::Encode(err) - } -} - -/// Computes the 64-bit FNV-1a hash of `bytes`. -#[inline] -pub fn fnv1a_64(bytes: &[u8]) -> u64 { - let mut hash = FNV1A_64_OFFSET_BASIS; - for &b in bytes { - hash ^= u64::from(b); - hash = hash.wrapping_mul(FNV1A_64_PRIME); - } - hash -} - -/// Deterministic shard index for an equity `listing_id` (`i32` hashed as 4 little-endian bytes). -#[inline] -pub fn shard_for_listing_id(listing_id: i32, shard_count: usize) -> usize { - debug_assert!(shard_count > 0); - (fnv1a_64(&listing_id.to_le_bytes()) % (shard_count as u64)) as usize -} - -/// Deterministic shard index for an FX `pair` (hashed as raw UTF-8 bytes). -#[inline] -pub fn shard_for_fx_pair(pair: &str, shard_count: usize) -> usize { - debug_assert!(shard_count > 0); - (fnv1a_64(pair.as_bytes()) % (shard_count as u64)) as usize -} - -#[inline] -fn validate_finite(field: &'static str, value: f64) -> Result<(), IlpEncodeError> { - if value.is_finite() { - Ok(()) - } else { - Err(IlpEncodeError::NonFiniteDouble { field, value }) - } -} - -#[inline] -fn validate_non_negative_ts(field: &'static str, value: i64) -> Result<(), IlpEncodeError> { - if value >= 0 { - Ok(()) - } else { - Err(IlpEncodeError::NegativeTimestamp { field, value }) - } -} - -/// Escapes an ILP tag/symbol value by prefixing space, `,`, `=`, `\n`, `\r`, and `\` with `\`. -#[inline] -fn write_escaped_symbol(buf: &mut Vec, value: &str) { - let bytes = value.as_bytes(); - let mut last = 0usize; - for (i, &b) in bytes.iter().enumerate() { - if matches!(b, b' ' | b',' | b'=' | b'\n' | b'\r' | b'\\') { - if last < i { - buf.extend_from_slice(&bytes[last..i]); - } - buf.push(b'\\'); - buf.push(b); - last = i + 1; - } - } - if last < bytes.len() { - buf.extend_from_slice(&bytes[last..]); - } -} - -#[inline] -fn write_i64_decimal(buf: &mut Vec, value: i64) { - let mut tmp = [0u8; 20]; - let negative = value < 0; - let mut mag = value.unsigned_abs(); - let mut pos = tmp.len(); - if mag == 0 { - pos -= 1; - tmp[pos] = b'0'; - } else { - while mag > 0 { - pos -= 1; - tmp[pos] = b'0' + (mag % 10) as u8; - mag /= 10; - } - } - if negative { - pos -= 1; - tmp[pos] = b'-'; - } - buf.extend_from_slice(&tmp[pos..]); -} - -#[inline] -fn write_binary_f64(buf: &mut Vec, name: &str, value: f64) { - buf.extend_from_slice(name.as_bytes()); - buf.extend_from_slice(&[b'=', b'=', ILP_V2_DOUBLE_TYPE]); - buf.extend_from_slice(&value.to_le_bytes()); -} - -/// Encodes one curated `bars_1m` row in QuestDB ILP v2 format into `buf`. -/// -/// Emits: -/// - Table `bars_1m` -/// - Symbols `listing_id` (decimal `row.key`), `session` (`PRE`/`RTH`/`POST`), `source` -/// - Binary `f64` columns `open`, `high`, `low`, `close`, `volume` (`vwap` omitted / NULL) -/// - Timestamp column `known_at=t` -/// - Designated timestamp ` t\n` -/// -/// Validates all doubles, `source`, and non-negative `row.ts` before appending any bytes so -/// `buf` is left untouched on error. -pub fn encode_bar_1m( - buf: &mut Vec, - row: &Bar1mRow, - known_at_micros: i64, -) -> Result<(), IlpEncodeError> { - if row.source.is_empty() { - return Err(IlpEncodeError::EmptySymbol { field: "source" }); - } - validate_finite("open", row.open)?; - validate_finite("high", row.high)?; - validate_finite("low", row.low)?; - validate_finite("close", row.close)?; - validate_finite("volume", row.volume)?; - validate_non_negative_ts("ts", row.ts)?; - - buf.extend_from_slice(TABLE_BARS_1M.as_bytes()); - buf.extend_from_slice(b",listing_id="); - write_i64_decimal(buf, i64::from(row.key)); - buf.extend_from_slice(b",session="); - buf.extend_from_slice(row.session.as_str().as_bytes()); - buf.extend_from_slice(b",source="); - write_escaped_symbol(buf, row.source); - - buf.push(b' '); - write_binary_f64(buf, "open", row.open); - buf.push(b','); - write_binary_f64(buf, "high", row.high); - buf.push(b','); - write_binary_f64(buf, "low", row.low); - buf.push(b','); - write_binary_f64(buf, "close", row.close); - buf.push(b','); - write_binary_f64(buf, "volume", row.volume); - buf.extend_from_slice(b",known_at="); - write_i64_decimal(buf, known_at_micros); - buf.extend_from_slice(b"t "); - - write_i64_decimal(buf, row.ts); - buf.extend_from_slice(b"t\n"); - Ok(()) -} - -/// Encodes one `fx_1m` row in QuestDB ILP v2 format into `buf`. -/// -/// Emits: -/// - Table `fx_1m` -/// - Symbols `pair`, `source` -/// - Binary `f64` columns `open`, `high`, `low`, `close` -/// - Designated timestamp ` t\n` -/// -/// Validates `pair`, `source`, all doubles, and non-negative `row.ts` before appending any bytes -/// so `buf` is left untouched on error. -pub fn encode_fx_1m(buf: &mut Vec, row: &Fx1mRow<'_>) -> Result<(), IlpEncodeError> { - if row.pair.is_empty() { - return Err(IlpEncodeError::EmptySymbol { field: "pair" }); - } - if row.source.is_empty() { - return Err(IlpEncodeError::EmptySymbol { field: "source" }); - } - validate_finite("open", row.open)?; - validate_finite("high", row.high)?; - validate_finite("low", row.low)?; - validate_finite("close", row.close)?; - validate_non_negative_ts("ts", row.ts)?; - - buf.extend_from_slice(TABLE_FX_1M.as_bytes()); - buf.extend_from_slice(b",pair="); - write_escaped_symbol(buf, row.pair); - buf.extend_from_slice(b",source="); - write_escaped_symbol(buf, row.source); - - buf.push(b' '); - write_binary_f64(buf, "open", row.open); - buf.push(b','); - write_binary_f64(buf, "high", row.high); - buf.push(b','); - write_binary_f64(buf, "low", row.low); - buf.push(b','); - write_binary_f64(buf, "close", row.close); - - buf.push(b' '); - write_i64_decimal(buf, row.ts); - buf.extend_from_slice(b"t\n"); - Ok(()) -} - -struct ShardState { - sink: W, - buf: Vec, - pending_rows: usize, - written_rows: usize, -} - -/// Deterministic, sink-agnostic sharded QuestDB ILP v2 batch writer. -/// -/// Buffers complete ILP lines per shard and flushes whole-line batches to injected [`Write`] -/// sinks when either `max_batch_rows` or `max_batch_bytes` is reached, or on [`Self::finish`]. -pub struct IlpShardedWriter { - shards: Vec>, - options: IlpWriterOptions, - scratch: Vec, - rows_written: usize, - bytes_written: usize, - flushes: usize, - poisoned_shard: Option, -} - -impl IlpShardedWriter { - /// Creates a new sharded writer over `sinks` with the given batching `options`. - /// - /// Returns an error if `sinks` is empty or either batch limit is zero. - pub fn new(sinks: Vec, options: IlpWriterOptions) -> Result { - if sinks.is_empty() { - return Err(IlpWriterError::EmptySinks); - } - if options.max_batch_bytes == 0 { - return Err(IlpWriterError::ZeroMaxBatchBytes); - } - if options.max_batch_rows == 0 { - return Err(IlpWriterError::ZeroMaxBatchRows); - } - - let initial_buf_cap = options.max_batch_bytes.min(DEFAULT_ILP_MAX_BATCH_BYTES); - let shards = sinks - .into_iter() - .map(|sink| ShardState { - sink, - buf: Vec::with_capacity(initial_buf_cap), - pending_rows: 0, - written_rows: 0, - }) - .collect(); - - Ok(Self { - shards, - options, - scratch: Vec::with_capacity(256), - rows_written: 0, - bytes_written: 0, - flushes: 0, - poisoned_shard: None, - }) - } - - /// Returns the number of configured shards. - #[inline] - pub fn shard_count(&self) -> usize { - self.shards.len() - } - - /// Encodes and buffers one `bars_1m` row on the shard determined by `row.key`. - pub fn write_bar_1m( - &mut self, - row: &Bar1mRow, - known_at_micros: i64, - ) -> Result<(), IlpWriterError> { - if let Some(failed_shard) = self.poisoned_shard { - return Err(IlpWriterError::Poisoned { failed_shard }); - } - self.scratch.clear(); - encode_bar_1m(&mut self.scratch, row, known_at_micros)?; - let shard_idx = shard_for_listing_id(row.key, self.shards.len()); - self.enqueue_scratch_row(shard_idx) - } - - /// Encodes and buffers one `fx_1m` row on the shard determined by `row.pair`. - pub fn write_fx_1m(&mut self, row: &Fx1mRow<'_>) -> Result<(), IlpWriterError> { - if let Some(failed_shard) = self.poisoned_shard { - return Err(IlpWriterError::Poisoned { failed_shard }); - } - self.scratch.clear(); - encode_fx_1m(&mut self.scratch, row)?; - let shard_idx = shard_for_fx_pair(row.pair, self.shards.len()); - self.enqueue_scratch_row(shard_idx) - } - - /// Flushes all remaining buffered batches and underlying sinks, returning write statistics. - pub fn finish(mut self) -> Result { - if let Some(failed_shard) = self.poisoned_shard { - return Err(IlpWriterError::Poisoned { failed_shard }); - } - - for shard_idx in 0..self.shards.len() { - if !self.shards[shard_idx].buf.is_empty() { - self.flush_shard(shard_idx)?; - } - if let Err(source) = self.shards[shard_idx].sink.flush() { - self.poisoned_shard = Some(shard_idx); - return Err(IlpWriterError::Io { - shard: shard_idx, - source, - }); - } - } - - let per_shard_rows = self.shards.iter().map(|s| s.written_rows).collect(); - Ok(IlpWriteStats { - rows: self.rows_written, - bytes: self.bytes_written, - flushes: self.flushes, - per_shard_rows, - }) - } - - fn enqueue_scratch_row(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> { - let row_len = self.scratch.len(); - let needs_preflush = { - let shard = &self.shards[shard_idx]; - !shard.buf.is_empty() - && shard.buf.len().saturating_add(row_len) > self.options.max_batch_bytes - }; - if needs_preflush { - self.flush_shard(shard_idx)?; - } - - let needs_postflush = { - let shard = &mut self.shards[shard_idx]; - shard.buf.extend_from_slice(&self.scratch); - shard.pending_rows += 1; - shard.pending_rows >= self.options.max_batch_rows - || shard.buf.len() >= self.options.max_batch_bytes - }; - if needs_postflush { - self.flush_shard(shard_idx)?; - } - - Ok(()) - } - - fn flush_shard(&mut self, shard_idx: usize) -> Result<(), IlpWriterError> { - let shard = &mut self.shards[shard_idx]; - if shard.buf.is_empty() { - return Ok(()); - } - if let Err(source) = shard.sink.write_all(&shard.buf) { - self.poisoned_shard = Some(shard_idx); - return Err(IlpWriterError::Io { - shard: shard_idx, - source, - }); - } - - let bytes = shard.buf.len(); - let rows = shard.pending_rows; - shard.buf.clear(); - shard.pending_rows = 0; - shard.written_rows += rows; - self.rows_written += rows; - self.bytes_written += bytes; - self.flushes += 1; - Ok(()) - } -} - -#[cfg(test)] -#[path = "ilp_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/ilp_tests.rs b/tools/curate-etl/src/ilp_tests.rs deleted file mode 100644 index 775d1686..00000000 --- a/tools/curate-etl/src/ilp_tests.rs +++ /dev/null @@ -1,903 +0,0 @@ -use std::collections::HashMap; -use std::io::{self, Write}; -use std::sync::{Arc, Mutex}; - -use crate::bars_1m::{Bar1mRow, IntradaySession, BARS_1M_SOURCE_EOD}; - -use super::{ - encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Fx1mRow, - IlpEncodeError, IlpShardedWriter, IlpWriterError, IlpWriterOptions, ILP_V2_DOUBLE_TYPE, -}; - -fn sample_bar(listing_id: i32, ts: i64) -> Bar1mRow { - Bar1mRow { - key: listing_id, - ts, - session_date: 20_100, - open: 123.45, - high: 125.75, - low: 122.125, - close: 124.5, - volume: 98_765.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_EOD, - } -} - -fn sample_fx(pair: &'static str, ts: i64) -> Fx1mRow<'static> { - Fx1mRow { - pair, - ts, - open: 1.3625, - high: 1.3650, - low: 1.3610, - close: 1.3642, - source: "eod", - } -} - -/// Minimal ILP v2 frame splitter that respects escaped symbols and fixed-width 8-byte binary -/// `DOUBLE` payloads (`==\x10<8 bytes>`), so embedded `0x0a` bytes inside binary doubles or -/// escaped `\n` in symbols never falsely split a row. -fn split_ilp_v2_rows(data: &[u8]) -> Vec<&[u8]> { - let mut rows = Vec::new(); - let mut i = 0usize; - let len = data.len(); - - while i < len { - let start = i; - // 1. Tag set (table + symbols) ends at unescaped ASCII space. - while i < len { - match data[i] { - b'\\' => { - assert!(i + 1 < len, "dangling backslash in ILP tag set"); - i += 2; - } - b' ' => { - i += 1; - break; - } - _ => i += 1, - } - } - assert!(i < len, "unexpected EOF after ILP tag set"); - - // 2. Field set ends at ASCII space; skip fixed 8-byte binary double payloads after `==\x10`. - while i < len { - if data[i] == b' ' { - i += 1; - break; - } - if data[i] == b'=' && i + 2 < len && data[i + 1] == b'=' && data[i + 2] == ILP_V2_DOUBLE_TYPE - { - assert!( - i + 3 + 8 <= len, - "truncated binary DOUBLE payload in ILP field set" - ); - i += 3 + 8; - } else { - i += 1; - } - } - assert!(i < len, "unexpected EOF after ILP field set"); - - // 3. Designated timestamp runs to unescaped LF. - while i < len && data[i] != b'\n' { - i += 1; - } - assert!(i < len && data[i] == b'\n', "ILP row missing trailing LF"); - i += 1; - rows.push(&data[start..i]); - } - - rows -} - -fn extract_tag_value<'a>(row: &'a [u8], tag_prefix: &[u8]) -> &'a [u8] { - let mut i = 0usize; - let tag_end = loop { - assert!(i < row.len(), "missing space after tag set"); - match row[i] { - b'\\' => i += 2, - b' ' => break i, - _ => i += 1, - } - }; - let tag_section = &row[..tag_end]; - let pos = tag_section - .windows(tag_prefix.len()) - .position(|w| w == tag_prefix) - .expect("expected tag prefix in row"); - let val_start = pos + tag_prefix.len(); - let mut j = val_start; - while j < tag_end { - match tag_section[j] { - b'\\' => j += 2, - b',' => break, - _ => j += 1, - } - } - &tag_section[val_start..j] -} - -#[derive(Clone, Default)] -struct RecordingSink { - writes: Arc>>>, - flush_calls: Arc>, - fail_on_write_call: Option, - /// `(call_index, prefix_bytes)`: on `call_index`, accept only `prefix_bytes` and then fail - /// on the subsequent `write()` call inside `write_all()`. - partial_then_fail_on_write_call: Option<(usize, usize)>, - fail_on_flush: bool, -} - -impl RecordingSink { - fn new() -> Self { - Self::default() - } - - fn failing_on_write(call_index: usize) -> Self { - Self { - fail_on_write_call: Some(call_index), - ..Self::default() - } - } - - fn failing_after_partial_write(call_index: usize, prefix_bytes: usize) -> Self { - Self { - partial_then_fail_on_write_call: Some((call_index, prefix_bytes)), - ..Self::default() - } - } - - fn failing_on_flush() -> Self { - Self { - fail_on_flush: true, - ..Self::default() - } - } - - fn captured_writes(&self) -> Vec> { - self.writes.lock().unwrap().clone() - } - - fn captured_bytes(&self) -> Vec { - self.writes - .lock() - .unwrap() - .iter() - .flat_map(|w| w.iter().copied()) - .collect() - } - - fn captured_flushes(&self) -> usize { - *self.flush_calls.lock().unwrap() - } -} - -impl Write for RecordingSink { - fn write(&mut self, buf: &[u8]) -> io::Result { - let mut writes = self.writes.lock().unwrap(); - let call_idx = writes.len(); - if self.fail_on_write_call == Some(call_idx) { - return Err(io::Error::new( - io::ErrorKind::BrokenPipe, - format!("injected write failure on call {call_idx}"), - )); - } - if let Some((partial_call, prefix_bytes)) = self.partial_then_fail_on_write_call { - if call_idx == partial_call { - let n = prefix_bytes.min(buf.len()); - writes.push(buf[..n].to_vec()); - return Ok(n); - } - if call_idx > partial_call { - return Err(io::Error::new( - io::ErrorKind::BrokenPipe, - format!("injected write failure after partial write on call {call_idx}"), - )); - } - } - writes.push(buf.to_vec()); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - let mut flushes = self.flush_calls.lock().unwrap(); - *flushes += 1; - if self.fail_on_flush { - return Err(io::Error::new( - io::ErrorKind::ConnectionReset, - "injected flush failure", - )); - } - Ok(()) - } -} - -#[test] -fn golden_bytes_encode_bar_1m_matches_ilp_v2_wire_contract() { - let row = Bar1mRow { - key: 42, - ts: 1_736_951_400_000_000, - session_date: 20_103, - open: 150.25, - high: 151.75, - low: 149.5, - close: 151.125, - volume: 12_345.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_EOD, - }; - let known_at_micros = 1_736_951_460_123_456_i64; - - let mut actual = Vec::new(); - encode_bar_1m(&mut actual, &row, known_at_micros).expect("encode bar_1m"); - - let mut expected = Vec::new(); - expected.extend_from_slice(b"bars_1m,listing_id=42,session=RTH,source=eod_unadj "); - expected.extend_from_slice(b"open==\x10"); - expected.extend_from_slice(&150.25_f64.to_le_bytes()); - expected.extend_from_slice(b",high==\x10"); - expected.extend_from_slice(&151.75_f64.to_le_bytes()); - expected.extend_from_slice(b",low==\x10"); - expected.extend_from_slice(&149.5_f64.to_le_bytes()); - expected.extend_from_slice(b",close==\x10"); - expected.extend_from_slice(&151.125_f64.to_le_bytes()); - expected.extend_from_slice(b",volume==\x10"); - expected.extend_from_slice(&12_345.0_f64.to_le_bytes()); - expected.extend_from_slice(b",known_at=1736951460123456t 1736951400000000t\n"); - - assert_eq!(actual, expected); - assert!( - !actual.windows(4).any(|w| w == b"vwap"), - "vwap must be omitted for bars_1m" - ); - - // Round-trip every binary DOUBLE payload bit-exactly via f64::from_le_bytes. - for (prefix, expected_val) in [ - (&b"open==\x10"[..], row.open), - (&b",high==\x10"[..], row.high), - (&b",low==\x10"[..], row.low), - (&b",close==\x10"[..], row.close), - (&b",volume==\x10"[..], row.volume), - ] { - let pos = actual - .windows(prefix.len()) - .position(|w| w == prefix) - .expect("binary double column present"); - let raw: [u8; 8] = actual[pos + prefix.len()..pos + prefix.len() + 8] - .try_into() - .unwrap(); - let decoded = f64::from_le_bytes(raw); - assert_eq!(decoded.to_bits(), expected_val.to_bits()); - } - - // Verify PRE and POST session tags as well. - let mut pre_buf = Vec::new(); - let mut pre_row = row.clone(); - pre_row.session = IntradaySession::Pre; - encode_bar_1m(&mut pre_buf, &pre_row, known_at_micros).unwrap(); - assert!(pre_buf.starts_with(b"bars_1m,listing_id=42,session=PRE,source=eod_unadj ")); - - let mut post_buf = Vec::new(); - let mut post_row = row; - post_row.session = IntradaySession::Post; - encode_bar_1m(&mut post_buf, &post_row, known_at_micros).unwrap(); - assert!(post_buf.starts_with(b"bars_1m,listing_id=42,session=POST,source=eod_unadj ")); -} - -#[test] -fn golden_bytes_encode_fx_1m_matches_ilp_v2_wire_contract() { - let row = Fx1mRow { - pair: "USD.CAD", - ts: 1_736_951_400_000_000, - open: 1.3625, - high: 1.365, - low: 1.36125, - close: 1.364375, - source: "eod", - }; - - let mut actual = Vec::new(); - encode_fx_1m(&mut actual, &row).expect("encode fx_1m"); - - let mut expected = Vec::new(); - expected.extend_from_slice(b"fx_1m,pair=USD.CAD,source=eod "); - expected.extend_from_slice(b"open==\x10"); - expected.extend_from_slice(&1.3625_f64.to_le_bytes()); - expected.extend_from_slice(b",high==\x10"); - expected.extend_from_slice(&1.365_f64.to_le_bytes()); - expected.extend_from_slice(b",low==\x10"); - expected.extend_from_slice(&1.36125_f64.to_le_bytes()); - expected.extend_from_slice(b",close==\x10"); - expected.extend_from_slice(&1.364375_f64.to_le_bytes()); - expected.extend_from_slice(b" 1736951400000000t\n"); - - assert_eq!(actual, expected); - assert!(!actual.windows(8).any(|w| w == b"known_at")); - assert!(!actual.windows(6).any(|w| w == b"volume")); - - for (prefix, expected_val) in [ - (&b"open==\x10"[..], row.open), - (&b",high==\x10"[..], row.high), - (&b",low==\x10"[..], row.low), - (&b",close==\x10"[..], row.close), - ] { - let pos = actual - .windows(prefix.len()) - .position(|w| w == prefix) - .expect("binary double column present"); - let raw: [u8; 8] = actual[pos + prefix.len()..pos + prefix.len() + 8] - .try_into() - .unwrap(); - assert_eq!(f64::from_le_bytes(raw).to_bits(), expected_val.to_bits()); - } -} - -#[test] -fn symbol_escaping_and_non_finite_or_negative_ts_atomic_rejection() { - // Escaping: space, comma, '=', backslash, LF, CR, and UTF-8. - let raw_sym = "a b,c=d\\e\nf\rg caf\u{00e9}"; - let expected_escaped = b"a\\ b\\,c\\=d\\\\e\\\nf\\\rg\\ caf\xc3\xa9"; - - let mut bar = sample_bar(7, 0); - bar.source = raw_sym; - let mut bar_buf = Vec::new(); - encode_bar_1m(&mut bar_buf, &bar, -500).expect("encode escaped bar_1m"); - let mut expected_prefix = b"bars_1m,listing_id=7,session=RTH,source=".to_vec(); - expected_prefix.extend_from_slice(expected_escaped); - expected_prefix.push(b' '); - assert!(bar_buf.starts_with(&expected_prefix)); - assert!(bar_buf.ends_with(b",known_at=-500t 0t\n")); - - let fx = Fx1mRow { - pair: raw_sym, - source: "src=1,2 3\\4\n\r", - ..sample_fx("USD.CAD", 123) - }; - let mut fx_buf = Vec::new(); - encode_fx_1m(&mut fx_buf, &fx).expect("encode escaped fx_1m"); - let mut expected_fx_prefix = b"fx_1m,pair=".to_vec(); - expected_fx_prefix.extend_from_slice(expected_escaped); - expected_fx_prefix.extend_from_slice(b",source=src\\=1\\,2\\ 3\\\\4\\\n\\\r "); - assert!(fx_buf.starts_with(&expected_fx_prefix)); - assert!(fx_buf.ends_with(b" 123t\n")); - - // Non-finite doubles in a late field must fail atomically and preserve existing buffer bytes. - let sentinel = b"EXISTING_PREFIX_BYTES".to_vec(); - for bad_val in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - let mut buf = sentinel.clone(); - let mut bad_bar = sample_bar(1, 100); - bad_bar.volume = bad_val; - let err = encode_bar_1m(&mut buf, &bad_bar, 200).unwrap_err(); - assert!(matches!( - err, - IlpEncodeError::NonFiniteDouble { - field: "volume", - .. - } - )); - assert_eq!(buf, sentinel, "buffer must be untouched on bars_1m error"); - - let mut fx_buf = sentinel.clone(); - let mut bad_fx = sample_fx("USD.CAD", 100); - bad_fx.close = bad_val; - let err = encode_fx_1m(&mut fx_buf, &bad_fx).unwrap_err(); - assert!(matches!( - err, - IlpEncodeError::NonFiniteDouble { field: "close", .. } - )); - assert_eq!(fx_buf, sentinel, "buffer must be untouched on fx_1m error"); - } - - // Negative designated timestamp fails atomically. - let mut buf = sentinel.clone(); - let bad_ts_bar = sample_bar(1, -1); - assert_eq!( - encode_bar_1m(&mut buf, &bad_ts_bar, 500), - Err(IlpEncodeError::NegativeTimestamp { - field: "ts", - value: -1 - }) - ); - assert_eq!(buf, sentinel); - - let mut fx_buf = sentinel.clone(); - let bad_ts_fx = sample_fx("USD.CAD", -42); - assert_eq!( - encode_fx_1m(&mut fx_buf, &bad_ts_fx), - Err(IlpEncodeError::NegativeTimestamp { - field: "ts", - value: -42 - }) - ); - assert_eq!(fx_buf, sentinel); - - // Empty symbol fails atomically. - let mut buf = sentinel.clone(); - let mut empty_src = sample_bar(1, 100); - empty_src.source = ""; - assert_eq!( - encode_bar_1m(&mut buf, &empty_src, 100), - Err(IlpEncodeError::EmptySymbol { field: "source" }) - ); - assert_eq!(buf, sentinel); - - let mut fx_buf = sentinel.clone(); - let empty_pair = sample_fx("", 100); - assert_eq!( - encode_fx_1m(&mut fx_buf, &empty_pair), - Err(IlpEncodeError::EmptySymbol { field: "pair" }) - ); - assert_eq!(fx_buf, sentinel); -} - -#[test] -fn sharded_writer_routes_deterministically_preserves_per_key_order_and_handles_embedded_lf() { - // Build a finite double whose IEEE-754 little-endian representation contains 0x0a (LF). - let double_with_lf = f64::from_le_bytes([0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x24, 0x40]); - assert!(double_with_lf.is_finite()); - - let num_shards = 4usize; - let num_listings = 64i32; - let rows_per_listing = 20usize; // 64 * 20 = 1,280 interleaved rows >= 1,000 - - let mut input_rows: Vec<(Bar1mRow, i64)> = - Vec::with_capacity(num_listings as usize * rows_per_listing + 2); - for step in 0..rows_per_listing { - for listing_id in 1..=num_listings { - let ts = 1_700_000_000_000_000 + (step as i64) * 60_000_000 + i64::from(listing_id); - let known_at = ts + 60_000_000; - let mut row = sample_bar(listing_id, ts); - row.open = double_with_lf; - row.close = 100.0 + (step as f64) * 0.25 + f64::from(listing_id) * 0.01; - row.volume = (step as f64 + 1.0) * 100.0; - if step == 5 && listing_id == 10 { - row.source = "eod\nwith_lf"; - } - input_rows.push((row, known_at)); - } - } - // Append a second version of an existing (ts, listing_id) to verify DEDUP UPSERT ordering. - let (mut revision, rev_known_at) = input_rows[0].clone(); - revision.close += 0.5; - input_rows.push((revision, rev_known_at + 120_000_000)); - - // Expected per-listing byte sequences in input order. - let mut expected_by_listing: HashMap>> = HashMap::new(); - for (row, known_at) in &input_rows { - let mut line = Vec::new(); - encode_bar_1m(&mut line, row, *known_at).unwrap(); - expected_by_listing.entry(row.key).or_default().push(line); - } - - let opts = IlpWriterOptions { - max_batch_bytes: 2048, - max_batch_rows: 17, - }; - - let run_once = || { - let mut sinks: Vec> = (0..num_shards).map(|_| Vec::new()).collect(); - let stats = { - let sink_refs: Vec<&mut Vec> = sinks.iter_mut().collect(); - let mut writer = IlpShardedWriter::new(sink_refs, opts).unwrap(); - for (row, known_at) in &input_rows { - writer.write_bar_1m(row, *known_at).unwrap(); - } - writer.finish().unwrap() - }; - (sinks, stats) - }; - - let (sinks_a, stats_a) = run_once(); - let (sinks_b, stats_b) = run_once(); - - // Byte-for-byte determinism across runs. - assert_eq!(sinks_a, sinks_b); - assert_eq!(stats_a, stats_b); - - // Conservation invariants. - assert_eq!(stats_a.rows, input_rows.len()); - assert_eq!( - stats_a.per_shard_rows.iter().sum::(), - stats_a.rows - ); - let total_sink_bytes: usize = sinks_a.iter().map(Vec::len).sum(); - assert_eq!(stats_a.bytes, total_sink_bytes); - - // Parse every shard with the binary-aware ILP v2 splitter and verify routing + order. - let mut seen_shard_for_listing: HashMap = HashMap::new(); - let mut observed_by_listing: HashMap>> = HashMap::new(); - let mut total_parsed_rows = 0usize; - - for (shard_idx, shard_bytes) in sinks_a.iter().enumerate() { - let parsed = split_ilp_v2_rows(shard_bytes); - assert_eq!(parsed.len(), stats_a.per_shard_rows[shard_idx]); - total_parsed_rows += parsed.len(); - - for row_bytes in parsed { - let id_bytes = extract_tag_value(row_bytes, b",listing_id="); - let listing_id: i32 = std::str::from_utf8(id_bytes).unwrap().parse().unwrap(); - assert_eq!( - shard_idx, - shard_for_listing_id(listing_id, num_shards), - "listing_id {listing_id} routed to unexpected shard" - ); - if let Some(&prev_shard) = seen_shard_for_listing.get(&listing_id) { - assert_eq!(prev_shard, shard_idx); - } else { - seen_shard_for_listing.insert(listing_id, shard_idx); - } - observed_by_listing - .entry(listing_id) - .or_default() - .push(row_bytes.to_vec()); - } - } - - assert_eq!(total_parsed_rows, input_rows.len()); - assert_eq!(seen_shard_for_listing.len(), num_listings as usize); - assert_eq!(observed_by_listing, expected_by_listing); - - // Repeated FX pairs across batches route by `pair` and preserve order. - let pairs = ["USD.CAD", "EUR.USD", "GBP.USD", "USD.JPY", "AUD.USD", "USD.CHF"]; - let mut fx_sinks: Vec> = (0..num_shards).map(|_| Vec::new()).collect(); - let mut expected_by_pair: HashMap<&str, Vec>> = HashMap::new(); - let fx_stats = { - let refs: Vec<&mut Vec> = fx_sinks.iter_mut().collect(); - let mut writer = IlpShardedWriter::new( - refs, - IlpWriterOptions { - max_batch_bytes: 512, - max_batch_rows: 3, - }, - ) - .unwrap(); - for step in 0..10 { - for &pair in &pairs { - let mut row = sample_fx(pair, 1_700_000_000_000_000 + step * 60_000_000); - row.close += (step as f64) * 0.0001; - let mut line = Vec::new(); - encode_fx_1m(&mut line, &row).unwrap(); - expected_by_pair.entry(pair).or_default().push(line); - writer.write_fx_1m(&row).unwrap(); - } - } - writer.finish().unwrap() - }; - assert_eq!(fx_stats.rows, pairs.len() * 10); - assert_eq!(fx_stats.per_shard_rows.iter().sum::(), fx_stats.rows); - assert_eq!(fx_stats.bytes, fx_sinks.iter().map(Vec::len).sum::()); - - let mut observed_by_pair: HashMap>> = HashMap::new(); - for (shard_idx, shard_bytes) in fx_sinks.iter().enumerate() { - for row_bytes in split_ilp_v2_rows(shard_bytes) { - let pair_str = - std::str::from_utf8(extract_tag_value(row_bytes, b",pair=")).unwrap(); - assert_eq!(shard_idx, shard_for_fx_pair(pair_str, num_shards)); - observed_by_pair - .entry(pair_str.to_string()) - .or_default() - .push(row_bytes.to_vec()); - } - } - for (pair, expected) in expected_by_pair { - assert_eq!(observed_by_pair.get(pair).unwrap(), &expected); - } -} - -#[test] -fn batching_limits_oversized_lines_remainder_and_whole_line_boundaries() { - let row = sample_bar(42, 1_736_951_400_000_000); - let known_at = 1_736_951_460_000_000; - let mut one_line = Vec::new(); - encode_bar_1m(&mut one_line, &row, known_at).unwrap(); - let row_len = one_line.len(); - - // 1. Exact row limit (max_batch_rows = 3) + 1 remainder row. - let sink = RecordingSink::new(); - let mut writer = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { - max_batch_bytes: 100_000, - max_batch_rows: 3, - }, - ) - .unwrap(); - for _ in 0..7 { - writer.write_bar_1m(&row, known_at).unwrap(); - } - let stats = writer.finish().unwrap(); - let writes = sink.captured_writes(); - assert_eq!(writes.len(), 3); - assert_eq!(stats.flushes, 3); - assert_eq!(stats.rows, 7); - assert_eq!(stats.bytes, 7 * row_len); - assert_eq!(sink.captured_flushes(), 1); - assert_eq!(split_ilp_v2_rows(&writes[0]).len(), 3); - assert_eq!(split_ilp_v2_rows(&writes[1]).len(), 3); - assert_eq!(split_ilp_v2_rows(&writes[2]).len(), 1); - assert!(writes.iter().all(|w| w.ends_with(b"\n"))); - - // 2. Exact byte limit (2 * row_len): flushes after every 2 rows. - let sink = RecordingSink::new(); - let mut writer = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { - max_batch_bytes: 2 * row_len, - max_batch_rows: 100, - }, - ) - .unwrap(); - for _ in 0..5 { - writer.write_bar_1m(&row, known_at).unwrap(); - } - let stats = writer.finish().unwrap(); - let writes = sink.captured_writes(); - assert_eq!(writes.len(), 3); - assert_eq!(stats.flushes, 3); - assert_eq!(split_ilp_v2_rows(&writes[0]).len(), 2); - assert_eq!(split_ilp_v2_rows(&writes[1]).len(), 2); - assert_eq!(split_ilp_v2_rows(&writes[2]).len(), 1); - - // 3. Next line would exceed remaining capacity (2 * row_len - 1): flushes before appending. - let sink = RecordingSink::new(); - let mut writer = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { - max_batch_bytes: 2 * row_len - 1, - max_batch_rows: 100, - }, - ) - .unwrap(); - for _ in 0..3 { - writer.write_bar_1m(&row, known_at).unwrap(); - } - let stats = writer.finish().unwrap(); - let writes = sink.captured_writes(); - assert_eq!(writes.len(), 3); - assert_eq!(stats.flushes, 3); - for w in &writes { - assert_eq!(w.len(), row_len); - assert_eq!(split_ilp_v2_rows(w).len(), 1); - } - - // 4. Individually oversized line (max_batch_bytes = 16 < row_len) sent alone, never split. - let sink = RecordingSink::new(); - let mut writer = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { - max_batch_bytes: 16, - max_batch_rows: 100, - }, - ) - .unwrap(); - writer.write_bar_1m(&row, known_at).unwrap(); - writer.write_bar_1m(&row, known_at).unwrap(); - let stats = writer.finish().unwrap(); - let writes = sink.captured_writes(); - assert_eq!(writes.len(), 2); - assert_eq!(stats.flushes, 2); - assert_eq!(writes[0], one_line); - assert_eq!(writes[1], one_line); -} - -#[test] -fn writer_validates_options_handles_zero_rows_and_poisons_on_io_error() { - assert!(matches!( - IlpShardedWriter::>::new(Vec::new(), IlpWriterOptions::default()), - Err(IlpWriterError::EmptySinks) - )); - assert!(matches!( - IlpShardedWriter::new( - vec![Vec::new()], - IlpWriterOptions { - max_batch_bytes: 0, - max_batch_rows: 10, - } - ), - Err(IlpWriterError::ZeroMaxBatchBytes) - )); - assert!(matches!( - IlpShardedWriter::new( - vec![Vec::new()], - IlpWriterOptions { - max_batch_bytes: 1024, - max_batch_rows: 0, - } - ), - Err(IlpWriterError::ZeroMaxBatchRows) - )); - - // Zero rows written -> clean stats and sink flush still called. - let s0 = RecordingSink::new(); - let s1 = RecordingSink::new(); - let writer = IlpShardedWriter::new(vec![s0.clone(), s1.clone()], IlpWriterOptions::default()) - .unwrap(); - let stats = writer.finish().unwrap(); - assert_eq!(stats.rows, 0); - assert_eq!(stats.bytes, 0); - assert_eq!(stats.flushes, 0); - assert_eq!(stats.per_shard_rows, vec![0, 0]); - assert_eq!(s0.captured_flushes(), 1); - assert_eq!(s1.captured_flushes(), 1); - - // Find a listing_id that routes to shard 2 out of 4. - let target_listing = (1..1000) - .find(|&id| shard_for_listing_id(id, 4) == 2) - .expect("listing for shard 2"); - - // Failing write_all on shard 2 after 1 successful batch: returns Io { shard: 2 } and poisons. - let failing_sink = RecordingSink::failing_on_write(1); - let mut writer = IlpShardedWriter::new( - vec![ - RecordingSink::new(), - RecordingSink::new(), - failing_sink.clone(), - RecordingSink::new(), - ], - IlpWriterOptions { - max_batch_bytes: 100_000, - max_batch_rows: 1, - }, - ) - .unwrap(); - let row = sample_bar(target_listing, 1_700_000_000_000_000); - writer.write_bar_1m(&row, 1_700_000_060_000_000).unwrap(); - let err = writer - .write_bar_1m(&row, 1_700_000_120_000_000) - .unwrap_err(); - assert!(matches!(err, IlpWriterError::Io { shard: 2, .. })); - - // Subsequent writes and finish fail with Poisoned { failed_shard: 2 }. - let err2 = writer - .write_bar_1m(&row, 1_700_000_180_000_000) - .unwrap_err(); - assert!(matches!(err2, IlpWriterError::Poisoned { failed_shard: 2 })); - let err3 = writer.write_fx_1m(&sample_fx("USD.CAD", 100)).unwrap_err(); - assert!(matches!(err3, IlpWriterError::Poisoned { failed_shard: 2 })); - let err4 = writer.finish().unwrap_err(); - assert!(matches!(err4, IlpWriterError::Poisoned { failed_shard: 2 })); - assert_eq!(failing_sink.captured_writes().len(), 1); - - // Failing flush() during finish() reports shard index. - let mut writer = IlpShardedWriter::new( - vec![RecordingSink::new(), RecordingSink::failing_on_flush()], - IlpWriterOptions::default(), - ) - .unwrap(); - writer.write_bar_1m(&row, 1_700_000_060_000_000).unwrap(); - let flush_err = writer.finish().unwrap_err(); - assert!(matches!(flush_err, IlpWriterError::Io { shard: 1, .. })); - - // Encode error does not poison the writer. - let mut sinks = [Vec::new(), Vec::new()]; - let stats = { - let refs: Vec<&mut Vec> = sinks.iter_mut().collect(); - let mut writer = IlpShardedWriter::new(refs, IlpWriterOptions::default()).unwrap(); - let mut bad = sample_bar(42, 100); - bad.close = f64::NAN; - assert!(matches!( - writer.write_bar_1m(&bad, 200), - Err(IlpWriterError::Encode(IlpEncodeError::NonFiniteDouble { - field: "close", - .. - })) - )); - writer - .write_bar_1m(&sample_bar(42, 100), 200) - .expect("writer still healthy after encode error"); - writer.finish().unwrap() - }; - assert_eq!(stats.rows, 1); - - // Sanity check FNV-1a 64-bit known test vector ("foobar" -> 0x85944171f73967e8). - assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8); -} - -#[test] -fn partial_write_failure_poisons_writer_and_freezes_sink_bytes() { - let target_listing = (1..1000) - .find(|&id| shard_for_listing_id(id, 4) == 2) - .expect("listing for shard 2"); - let other_listing = (1..1000) - .find(|&id| shard_for_listing_id(id, 4) == 0) - .expect("listing for shard 0"); - - let row1 = sample_bar(target_listing, 1_700_000_000_000_000); - let row2 = sample_bar(target_listing, 1_700_000_060_000_000); - let other_row = sample_bar(other_listing, 1_700_000_000_000_000); - let known_at = 1_700_000_120_000_000; - - let mut expected_row1 = Vec::new(); - encode_bar_1m(&mut expected_row1, &row1, known_at).unwrap(); - let mut expected_row2 = Vec::new(); - encode_bar_1m(&mut expected_row2, &row2, known_at).unwrap(); - let partial_prefix_len = 32; - assert!(partial_prefix_len < expected_row2.len()); - - let healthy_sink = RecordingSink::new(); - let failing_sink = RecordingSink::failing_after_partial_write(1, partial_prefix_len); - let mut writer = IlpShardedWriter::new( - vec![ - healthy_sink.clone(), - RecordingSink::new(), - failing_sink.clone(), - RecordingSink::new(), - ], - IlpWriterOptions { - max_batch_bytes: 100_000, - max_batch_rows: 1, - }, - ) - .unwrap(); - - // First batch on shard 2 succeeds completely. - writer.write_bar_1m(&row1, known_at).unwrap(); - - // Second batch on shard 2 writes a partial prefix, then hits BrokenPipe. - let err = writer.write_bar_1m(&row2, known_at).unwrap_err(); - assert!(matches!(err, IlpWriterError::Io { shard: 2, .. })); - - let mut expected_captured = expected_row1.clone(); - expected_captured.extend_from_slice(&expected_row2[..partial_prefix_len]); - assert_eq!(failing_sink.captured_bytes(), expected_captured); - - // Subsequent writes (both on the failed shard and on another shard) and finish() are rejected, - // leaving all sink bytes frozen without replaying or appending anything. - assert!(matches!( - writer.write_bar_1m(&row2, known_at), - Err(IlpWriterError::Poisoned { failed_shard: 2 }) - )); - assert!(matches!( - writer.write_bar_1m(&other_row, known_at), - Err(IlpWriterError::Poisoned { failed_shard: 2 }) - )); - assert!(matches!( - writer.write_fx_1m(&sample_fx("USD.CAD", 100)), - Err(IlpWriterError::Poisoned { failed_shard: 2 }) - )); - assert!(matches!( - writer.finish(), - Err(IlpWriterError::Poisoned { failed_shard: 2 }) - )); - - assert_eq!(failing_sink.captured_bytes(), expected_captured); - assert!(healthy_sink.captured_bytes().is_empty()); -} - -#[test] -fn golden_bytes_literal_ieee754_little_endian_without_to_le_bytes() { - let row = Bar1mRow { - key: 7, - ts: 1_700_000_000_000_000, - session_date: 20_000, - open: 1.0, - high: 2.0, - low: 0.5, - close: 1.5, - volume: 0.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_EOD, - }; - let mut actual = Vec::new(); - encode_bar_1m(&mut actual, &row, 1_700_000_060_000_000).unwrap(); - - // Hand-written little-endian IEEE-754 bytes (no f64::to_le_bytes): - // 1.0 -> 00 00 00 00 00 00 f0 3f - // 2.0 -> 00 00 00 00 00 00 00 40 - // 0.5 -> 00 00 00 00 00 00 e0 3f - // 1.5 -> 00 00 00 00 00 00 f8 3f - // 0.0 -> 00 00 00 00 00 00 00 00 - let mut expected: Vec = Vec::new(); - expected.extend_from_slice(b"bars_1m,listing_id=7,session=RTH,source=eod_unadj "); - expected.extend_from_slice(b"open==\x10\x00\x00\x00\x00\x00\x00\xf0\x3f"); - expected.extend_from_slice(b",high==\x10\x00\x00\x00\x00\x00\x00\x00\x40"); - expected.extend_from_slice(b",low==\x10\x00\x00\x00\x00\x00\x00\xe0\x3f"); - expected.extend_from_slice(b",close==\x10\x00\x00\x00\x00\x00\x00\xf8\x3f"); - expected.extend_from_slice(b",volume==\x10\x00\x00\x00\x00\x00\x00\x00\x00"); - expected.extend_from_slice(b",known_at=1700000060000000t 1700000000000000t\n"); - - assert_eq!(actual, expected); -} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index 1a8ff478..023e1f16 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -2,34 +2,27 @@ pub mod adj; pub mod bars; -pub mod bars_1m; pub mod bench; pub mod bson_ceo_shorts; -pub mod bson_eod_intraday; pub mod bson_eod_prices; pub mod bson_qm_actions; pub mod bson_qm_events; -pub mod bson_qm_intraday; pub mod bson_qm_prices; pub mod bson_stream; pub mod bson_te_market_data; pub mod cli; pub mod corporate_actions; pub mod events; -pub mod fundamentals; pub mod fx; -pub mod ilp; pub mod mongo_safety; pub mod mongo_stream; pub mod parquet_adj; pub mod parquet_bars; pub mod parquet_corporate_actions; pub mod parquet_events; -pub mod parquet_fundamentals; pub mod parquet_fx; mod parquet_publish; pub mod parquet_shorts; -pub mod posts; pub mod provider_mapping; pub mod session_close; pub mod shorts; @@ -43,21 +36,11 @@ 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, BARS_1M_SOURCE_QM, 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, DEFAULT_REPORT_DATE_FIELD, }; -pub use bson_eod_intraday::{ - decode_eod_intraday_buffer, decode_eod_intraday_bytes, decode_eod_intraday_doc, - BsonEodIntradayDecodeStats, BsonEodIntradayError, RawEodIntradayBar, -}; pub use bson_eod_prices::{ decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs, BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar, @@ -81,14 +64,13 @@ pub use bson_qm_prices::{ BsonQmPriceError, RawQmPrice, FIELD_SHARE_VOLUME, }; pub use bson_stream::{ - decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_intraday_chunks, - decode_eod_intraday_stream, decode_eod_price_chunks, decode_eod_price_stream, - decode_qm_dividend_chunks, decode_qm_dividend_stream, decode_qm_earnings_chunks, - decode_qm_earnings_stream, decode_qm_filings_chunks, decode_qm_filings_stream, - decode_qm_intraday_chunks, decode_qm_intraday_stream, decode_qm_price_chunks, - decode_qm_price_stream, decode_qm_split_chunks, decode_qm_split_stream, - decode_te_market_data_chunks, decode_te_market_data_stream, BsonCeoShortsStreamError, - BsonQmEventsStreamError, BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, + decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_price_chunks, + decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream, + decode_qm_earnings_chunks, decode_qm_earnings_stream, decode_qm_filings_chunks, + decode_qm_filings_stream, decode_qm_price_chunks, decode_qm_price_stream, + decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks, + decode_te_market_data_stream, BsonCeoShortsStreamError, BsonQmEventsStreamError, + BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader, DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES, }; pub use bson_te_market_data::{ @@ -111,27 +93,10 @@ 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, }; -pub use ilp::{ - encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Fx1mRow, - IlpEncodeError, IlpShardedWriter, IlpWriteStats, IlpWriterError, IlpWriterOptions, - DEFAULT_ILP_MAX_BATCH_BYTES, DEFAULT_ILP_MAX_BATCH_ROWS, FNV1A_64_OFFSET_BASIS, - FNV1A_64_PRIME, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M, -}; pub use mongo_safety::{ assert_read_only_mongo_uri, is_qa_mongo_target, parse_mongo_target, LocalHosts, MongoSafetyError, MongoScheme, MongoTarget, MongoTargetHost, ReadOnlyPolicy, @@ -163,11 +128,6 @@ pub use parquet_events::{ events_parquet_schema, write_events_dataset, EventsParquetRow, EventsWriteOptions, EventsWriteStats, ParquetEventsError, }; -pub use parquet_fundamentals::{ - fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitLatestPeriod, - FundamentalsPitParquetRow, FundamentalsPitWriteOptions, FundamentalsPitWriteStats, - ParquetFundamentalsError, -}; pub use parquet_fx::{ fx_1d_parquet_schema, write_fx_1d_dataset, Fx1dParquetRow, Fx1dWriteOptions, Fx1dWriteStats, ParquetFxError, @@ -176,18 +136,14 @@ pub use parquet_shorts::{ shorts_parquet_schema, write_shorts_dataset, ParquetShortsError, ShortsParquetRow, ShortsWriteOptions, ShortsWriteStats, }; -pub use posts::{ - build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats, POSTS_SOURCE_CEO, -}; pub use provider_mapping::{ MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow, ProviderMappingTable, }; pub use session_close::{ - 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, + 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, }; pub use shorts::{ add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, @@ -243,26 +199,6 @@ pub use curate_corporate_actions::{ CurateCorporateActionsWriteReport, CurateDelistingInput, }; -pub mod curate_bars_1m; -pub use curate_bars_1m::{ - check_curated_session_closes, curate_and_write_bars_1m, curate_and_write_bars_1m_from_bson, - curate_bars_1m, CurateBars1mBsonError, CurateBars1mBsonReport, CurateBars1mError, - CurateBars1mOutput, CurateBars1mStats, CurateBars1mWriteError, CurateBars1mWriteReport, -}; - -pub mod curate_qm_bars_1m; -pub use curate_qm_bars_1m::{ - curate_and_write_qm_bars_1m, curate_and_write_qm_bars_1m_from_bson, curate_qm_bars_1m, - CurateQmBars1mBsonError, CurateQmBars1mBsonReport, -}; - -pub mod curate_fx_1m; -pub use curate_fx_1m::{ - build_fx_1m, curate_and_write_fx_1m, curate_and_write_fx_1m_from_bson, CurateFx1mBsonError, - CurateFx1mBsonReport, CurateFx1mOutput, CurateFx1mStats, CurateFx1mWriteReport, - FX_1M_SOURCE_EOD, -}; - pub mod run_curate_bars; pub use run_curate_bars::{ default_curate_bars_threads, format_curate_bars_report, load_listing_currencies_tsv, @@ -312,7 +248,5 @@ pub use run_mongo::{ CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError, }; -#[cfg(test)] -mod posts_tests; #[cfg(test)] mod tsv_fixture_tests; diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 6f3be0c3..e54fba0a 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -4,15 +4,14 @@ use std::env; use std::process::ExitCode; use curate_etl::bench::{ - run_adj_benchmark, run_bars_1m_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark, + run_adj_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_fundamentals_benchmark, run_fx_benchmark, run_ilp_bars_1m_benchmark, - run_mongo_stream_benchmark, run_parquet_adj_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, @@ -334,78 +333,6 @@ 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::BenchIlpBars1m(rows)) => { - let report = match run_ilp_bars_1m_benchmark(rows) { - Ok(report) => report, - Err(err) => { - eprintln!("error: ilp bars_1m benchmark failed: {err}"); - return ExitCode::FAILURE; - } - }; - println!("curate-etl bench-ilp-bars-1m"); - println!( - " input: rows={} keys={} shards={}", - report.rows, report.key_count, report.shards - ); - println!( - " output: rows_encoded={} bytes={} flushes={} per_shard_rows={:?}", - report.rows_encoded, report.bytes, report.flushes, report.per_shard_rows - ); - println!( - " perf: elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row size={:.2} bytes/row write={:.2} MB/s", - report.elapsed_ms, - report.rows_per_sec, - report.ns_per_row, - report.bytes_per_row, - report.mb_per_sec - ); - ExitCode::SUCCESS - } Ok(CliAction::BenchFx(rows)) => { let report = run_fx_benchmark(rows); println!("curate-etl bench-fx"); @@ -510,51 +437,6 @@ 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, diff --git a/tools/curate-etl/src/parquet_fundamentals.rs b/tools/curate-etl/src/parquet_fundamentals.rs deleted file mode 100644 index 0bc2a9b4..00000000 --- a/tools/curate-etl/src/parquet_fundamentals.rs +++ /dev/null @@ -1,1354 +0,0 @@ -//! Streaming, atomic, year-partitioned Zstd Parquet writer for `fundamentals_pit`. -//! -//! Writes `/fundamentals_pit/year=YYYY/part.parquet` files matching the 20-column -//! contract schema in `design/DATA-CONTRACTS.md` (§3A): -//! -//! 1. `listing_id` (`INT32`, `REQUIRED`) -//! 2. `effective_known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) -//! 3. `known_at_source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) -//! 4. `has_estimated_lag` (`BOOLEAN`, `REQUIRED`) -//! 5. `period_end` (`INT32`, `REQUIRED`, `DATE`) -//! 6. `fiscal_period` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) -//! 7. `currency` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) -//! 8. `period_known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) -//! 9. `revenue` (`DOUBLE`, `OPTIONAL`) -//! 10. `net_income` (`DOUBLE`, `OPTIONAL`) -//! 11. `operating_cash_flow` (`DOUBLE`, `OPTIONAL`) -//! 12. `total_assets` (`DOUBLE`, `OPTIONAL`) -//! 13. `total_equity` (`DOUBLE`, `OPTIONAL`) -//! 14. `shares_outstanding` (`DOUBLE`, `OPTIONAL`) -//! 15. `ttm_period_end` (`INT32`, `OPTIONAL`, `DATE`) -//! 16. `ttm_currency` (`BYTE_ARRAY`, `OPTIONAL`, `STRING`) -//! 17. `ttm_revenue` (`DOUBLE`, `OPTIONAL`) -//! 18. `ttm_net_income` (`DOUBLE`, `OPTIONAL`) -//! 19. `ttm_operating_cash_flow` (`DOUBLE`, `OPTIONAL`) -//! 20. `ttm_has_estimated_lag` (`BOOLEAN`, `OPTIONAL`) -//! -//! Each physical row flattens `periods[0]` (the latest visible resolved period) and the -//! builder-provided 4-quarter `ttm` summary from a [`FundamentalsSnapshot`]. Lagged period slots -//! (`periods[1..]`) are intentionally omitted from the flat Parquet representation; TTM values -//! computed by [`crate::fundamentals::build_fundamentals_snapshots`] are preserved as-is. - -use std::borrow::{Borrow, Cow}; -use std::cmp::Ordering; -use std::collections::BTreeMap; -use std::error::Error; -use std::fmt; -use std::fs::{self, File}; -use std::io::{self, BufWriter, Write}; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::time::Duration; - -use parquet::basic::{ - Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel, -}; -use parquet::data_type::ByteArray; -use parquet::errors::ParquetError; -use parquet::file::properties::{WriterProperties, WriterPropertiesPtr}; -use parquet::file::writer::SerializedFileWriter; -use parquet::schema::types::{ColumnPath, Type, TypePtr}; - -use crate::events::{ - partition_year_utc, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, -}; -use crate::fundamentals::{FundamentalsFields, FundamentalsSnapshot, FundamentalsTtm}; -pub use crate::parquet_bars::{MAX_PARQUET_YEAR, MIN_PARQUET_YEAR}; -use crate::parquet_publish::{ - create_backup_preserving_live, create_exclusive_tmp_file, dataset_mutex, next_run_id, - rollback_published, write_bool_col, write_i32_col, write_i64_col, write_interned_str_col, - write_optional_f64_col, write_optional_i32_col, write_optional_interned_str_col, - DatasetFileLock, PublishIoError, PublishedPartition, StagingFileGuard, StringInterner, - DEFAULT_LOCK_TIMEOUT, FILE_BUF_CAPACITY_BYTES, STRING_WRITE_BATCH_ROWS, -}; -pub use crate::parquet_publish::{RollbackFailure, DEFAULT_ROW_GROUP_ROWS, DEFAULT_ZSTD_LEVEL}; - -/// Latest visible period projection flattened into a [`FundamentalsPitParquetRow`]. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsPitLatestPeriod { - pub period_end: i32, - pub fiscal_period: Cow<'static, str>, - pub currency: String, - pub period_known_at_micros: i64, - pub fields: FundamentalsFields, -} - -/// Single `fundamentals_pit` row matching the `design/DATA-CONTRACTS.md` (§3A) Parquet schema. -/// -/// Only `periods[0]` (the latest visible period) and `ttm` are stored; lagged slots -/// (`periods[1..]`) are intentionally omitted. -#[derive(Debug, Clone, PartialEq)] -pub struct FundamentalsPitParquetRow { - pub listing_id: i32, - pub effective_known_at_micros: i64, - pub known_at_source: Cow<'static, str>, - pub has_estimated_lag: bool, - latest_period: Option, - pub ttm: Option, -} - -impl FundamentalsPitParquetRow { - /// Constructs a valid `fundamentals_pit` Parquet row with an explicit latest visible period. - pub fn new( - listing_id: i32, - effective_known_at_micros: i64, - known_at_source: Cow<'static, str>, - has_estimated_lag: bool, - latest_period: FundamentalsPitLatestPeriod, - ttm: Option, - ) -> Self { - Self { - listing_id, - effective_known_at_micros, - known_at_source, - has_estimated_lag, - latest_period: Some(latest_period), - ttm, - } - } - - /// Returns the flattened latest visible period (`periods[0]`), or `None` if converted from a - /// malformed snapshot with an empty `periods` vector. - #[inline] - pub fn latest_period(&self) -> Option<&FundamentalsPitLatestPeriod> { - self.latest_period.as_ref() - } -} - -impl From<&FundamentalsSnapshot> for FundamentalsPitParquetRow { - fn from(snapshot: &FundamentalsSnapshot) -> Self { - let latest_period = snapshot.periods.first().map(|slot| FundamentalsPitLatestPeriod { - period_end: slot.period_end, - fiscal_period: Cow::Borrowed(slot.fiscal_period.as_str()), - currency: slot.currency.clone(), - period_known_at_micros: slot.known_at_utc_micros, - fields: slot.fields, - }); - Self { - listing_id: snapshot.key, - effective_known_at_micros: snapshot.effective_known_at_utc_micros, - known_at_source: Cow::Borrowed(snapshot.known_at_source), - has_estimated_lag: snapshot.has_estimated_lag, - latest_period, - ttm: snapshot.ttm.clone(), - } - } -} - -impl From> for FundamentalsPitParquetRow { - fn from(snapshot: FundamentalsSnapshot) -> Self { - let latest_period = snapshot - .periods - .into_iter() - .next() - .map(|slot| FundamentalsPitLatestPeriod { - period_end: slot.period_end, - fiscal_period: Cow::Borrowed(slot.fiscal_period.as_str()), - currency: slot.currency, - period_known_at_micros: slot.known_at_utc_micros, - fields: slot.fields, - }); - Self { - listing_id: snapshot.key, - effective_known_at_micros: snapshot.effective_known_at_utc_micros, - known_at_source: Cow::Borrowed(snapshot.known_at_source), - has_estimated_lag: snapshot.has_estimated_lag, - latest_period, - ttm: snapshot.ttm, - } - } -} - -/// Configuration for [`write_fundamentals_pit_dataset`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct FundamentalsPitWriteOptions { - pub row_group_rows: usize, - pub zstd_level: i32, -} - -impl Default for FundamentalsPitWriteOptions { - fn default() -> Self { - Self { - row_group_rows: DEFAULT_ROW_GROUP_ROWS, - zstd_level: DEFAULT_ZSTD_LEVEL, - } - } -} - -/// Accounting summary returned by [`write_fundamentals_pit_dataset`]. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct FundamentalsPitWriteStats { - pub rows_written: usize, - pub files_written: usize, - pub row_groups_written: usize, - pub bytes_written: u64, - pub rows_by_year: BTreeMap, -} - -/// Typed error returned by [`write_fundamentals_pit_dataset`]. -#[derive(Debug)] -pub enum ParquetFundamentalsError { - InvalidRowGroupRows, - InvalidZstdLevel { - level: i32, - }, - EmptyPeriods { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - UnsortedInput { - row_index: usize, - prev_listing_id: i32, - prev_effective_known_at_micros: i64, - listing_id: i32, - effective_known_at_micros: i64, - }, - DuplicateRow { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - PartitionYearOutOfRange { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - year: i32, - min_year: i32, - max_year: i32, - }, - EmptyKnownAtSource { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - InvalidKnownAtSource { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - value: String, - }, - EmptyFiscalPeriod { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - EmptyCurrency { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - EmptyTtmCurrency { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - }, - NonFiniteValue { - row_index: usize, - listing_id: i32, - effective_known_at_micros: i64, - field: &'static str, - value: f64, - }, - LockTimeout { - path: PathBuf, - waited: Duration, - }, - RollbackFailed { - cause: Box, - failures: Vec, - }, - Io { - path: PathBuf, - source: io::Error, - }, - Parquet { - path: PathBuf, - source: ParquetError, - }, -} - -impl fmt::Display for ParquetFundamentalsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::InvalidRowGroupRows => { - write!(f, "invalid row_group_rows: must be greater than 0") - } - Self::InvalidZstdLevel { level } => { - write!(f, "invalid Zstd compression level: {level}") - } - Self::EmptyPeriods { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "snapshot has empty periods at row {row_index} for (listing_id={listing_id}, effective_known_at={effective_known_at_micros})" - ), - Self::UnsortedInput { - row_index, - prev_listing_id, - prev_effective_known_at_micros, - listing_id, - effective_known_at_micros, - } => write!( - f, - "unsorted input at row {row_index}: ({listing_id}, {effective_known_at_micros}) follows ({prev_listing_id}, {prev_effective_known_at_micros})" - ), - Self::DuplicateRow { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "duplicate fundamentals_pit row at row {row_index}: (listing_id={listing_id}, effective_known_at={effective_known_at_micros})" - ), - Self::PartitionYearOutOfRange { - row_index, - listing_id, - effective_known_at_micros, - year, - min_year, - max_year, - } => write!( - f, - "partition year {year} (effective_known_at {effective_known_at_micros}) at row {row_index} for listing_id {listing_id} is outside allowed range {min_year}..={max_year}" - ), - Self::EmptyKnownAtSource { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "empty known_at_source at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" - ), - Self::InvalidKnownAtSource { - row_index, - listing_id, - effective_known_at_micros, - value, - } => write!( - f, - "invalid known_at_source {value:?} at row {row_index} for ({listing_id}, {effective_known_at_micros}): expected {KNOWN_AT_SOURCE_FILING_TIMESTAMP:?} or {KNOWN_AT_SOURCE_STATUTORY_LAG:?}" - ), - Self::EmptyFiscalPeriod { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "empty fiscal_period at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" - ), - Self::EmptyCurrency { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "empty currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" - ), - Self::EmptyTtmCurrency { - row_index, - listing_id, - effective_known_at_micros, - } => write!( - f, - "empty ttm_currency at row {row_index} for ({listing_id}, {effective_known_at_micros}): must be non-empty" - ), - Self::NonFiniteValue { - row_index, - listing_id, - effective_known_at_micros, - field, - value, - } => write!( - f, - "non-finite {field} value {value} at row {row_index} for ({listing_id}, {effective_known_at_micros})" - ), - Self::LockTimeout { path, waited } => write!( - f, - "timed out after {}ms waiting for dataset write lock '{}' (if no writer is active, remove the stale lock file and retry)", - waited.as_millis(), - path.display() - ), - Self::RollbackFailed { cause, failures } => { - write!( - f, - "publication failed ({cause}) and rollback encountered {} error(s) requiring manual recovery:", - failures.len() - )?; - for failure in failures { - write!(f, " [{failure}]")?; - } - Ok(()) - } - Self::Io { path, source } => { - write!(f, "I/O error at '{}': {source}", path.display()) - } - Self::Parquet { path, source } => { - write!(f, "Parquet error at '{}': {source}", path.display()) - } - } - } -} - -impl Error for ParquetFundamentalsError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - Self::RollbackFailed { cause, .. } => Some(cause.as_ref()), - Self::Io { source, .. } => Some(source), - Self::Parquet { source, .. } => Some(source), - _ => None, - } - } -} - -impl From for ParquetFundamentalsError { - fn from(err: PublishIoError) -> Self { - match err { - PublishIoError::LockTimeout { path, waited } => Self::LockTimeout { path, waited }, - PublishIoError::Io { path, source } => Self::Io { path, source }, - } - } -} - -/// Builds the exact 20-column Parquet schema for `fundamentals_pit` per `design/DATA-CONTRACTS.md` (§3A). -pub fn fundamentals_pit_parquet_schema() -> Result { - let fields: Vec = vec![ - // 1. listing_id INT32 REQUIRED - Arc::new( - Type::primitive_type_builder("listing_id", PhysicalType::INT32) - .with_repetition(Repetition::REQUIRED) - .build()?, - ), - // 2. effective_known_at INT64 REQUIRED TIMESTAMP(MICROS, UTC) - Arc::new( - Type::primitive_type_builder("effective_known_at", PhysicalType::INT64) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) - .build()?, - ), - // 3. known_at_source STRING REQUIRED - Arc::new( - Type::primitive_type_builder("known_at_source", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - // 4. has_estimated_lag BOOLEAN REQUIRED - Arc::new( - Type::primitive_type_builder("has_estimated_lag", PhysicalType::BOOLEAN) - .with_repetition(Repetition::REQUIRED) - .build()?, - ), - // 5. period_end INT32 DATE REQUIRED - Arc::new( - Type::primitive_type_builder("period_end", PhysicalType::INT32) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::Date)) - .build()?, - ), - // 6. fiscal_period STRING REQUIRED - Arc::new( - Type::primitive_type_builder("fiscal_period", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - // 7. currency STRING REQUIRED - Arc::new( - Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - // 8. period_known_at INT64 REQUIRED TIMESTAMP(MICROS, UTC) - Arc::new( - Type::primitive_type_builder("period_known_at", PhysicalType::INT64) - .with_repetition(Repetition::REQUIRED) - .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) - .build()?, - ), - // 9-14. latest-period financial metrics DOUBLE OPTIONAL - Arc::new( - Type::primitive_type_builder("revenue", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("net_income", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("operating_cash_flow", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("total_assets", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("total_equity", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("shares_outstanding", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - // 15. ttm_period_end INT32 DATE OPTIONAL - Arc::new( - Type::primitive_type_builder("ttm_period_end", PhysicalType::INT32) - .with_repetition(Repetition::OPTIONAL) - .with_logical_type(Some(LogicalType::Date)) - .build()?, - ), - // 16. ttm_currency STRING OPTIONAL - Arc::new( - Type::primitive_type_builder("ttm_currency", PhysicalType::BYTE_ARRAY) - .with_repetition(Repetition::OPTIONAL) - .with_logical_type(Some(LogicalType::String)) - .build()?, - ), - // 17-19. TTM flow sums DOUBLE OPTIONAL - Arc::new( - Type::primitive_type_builder("ttm_revenue", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("ttm_net_income", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - Arc::new( - Type::primitive_type_builder("ttm_operating_cash_flow", PhysicalType::DOUBLE) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - // 20. ttm_has_estimated_lag BOOLEAN OPTIONAL - Arc::new( - Type::primitive_type_builder("ttm_has_estimated_lag", PhysicalType::BOOLEAN) - .with_repetition(Repetition::OPTIONAL) - .build()?, - ), - ]; - - Ok(Arc::new( - Type::group_type_builder("fundamentals_pit") - .with_fields(fields) - .build()?, - )) -} - -fn build_writer_properties(zstd_level: ZstdLevel) -> WriterPropertiesPtr { - Arc::new( - WriterProperties::builder() - .set_compression(Compression::ZSTD(zstd_level)) - .set_column_dictionary_enabled(ColumnPath::from("known_at_source"), true) - .set_column_dictionary_enabled(ColumnPath::from("fiscal_period"), true) - .set_column_dictionary_enabled(ColumnPath::from("currency"), true) - .set_column_dictionary_enabled(ColumnPath::from("ttm_currency"), true) - .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) - .build(), - ) -} - -#[inline] -fn check_opt_finite( - row: &FundamentalsPitParquetRow, - row_index: usize, - field: &'static str, - val: Option, -) -> Result<(), ParquetFundamentalsError> { - if let Some(value) = val { - if !value.is_finite() { - return Err(ParquetFundamentalsError::NonFiniteValue { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - field, - value, - }); - } - } - Ok(()) -} - -#[inline] -fn validate_row( - row: &FundamentalsPitParquetRow, - row_index: usize, -) -> Result<(i32, &FundamentalsPitLatestPeriod), ParquetFundamentalsError> { - let Some(latest) = row.latest_period.as_ref() else { - return Err(ParquetFundamentalsError::EmptyPeriods { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - }; - - let year = partition_year_utc(row.effective_known_at_micros); - if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { - return Err(ParquetFundamentalsError::PartitionYearOutOfRange { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - year, - min_year: MIN_PARQUET_YEAR, - max_year: MAX_PARQUET_YEAR, - }); - } - - if row.known_at_source.trim().is_empty() { - return Err(ParquetFundamentalsError::EmptyKnownAtSource { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - if row.known_at_source.as_ref() != KNOWN_AT_SOURCE_FILING_TIMESTAMP - && row.known_at_source.as_ref() != KNOWN_AT_SOURCE_STATUTORY_LAG - { - return Err(ParquetFundamentalsError::InvalidKnownAtSource { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - value: row.known_at_source.to_string(), - }); - } - if latest.fiscal_period.trim().is_empty() { - return Err(ParquetFundamentalsError::EmptyFiscalPeriod { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - if latest.currency.trim().is_empty() { - return Err(ParquetFundamentalsError::EmptyCurrency { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - - check_opt_finite(row, row_index, "revenue", latest.fields.revenue)?; - check_opt_finite(row, row_index, "net_income", latest.fields.net_income)?; - check_opt_finite( - row, - row_index, - "operating_cash_flow", - latest.fields.operating_cash_flow, - )?; - check_opt_finite(row, row_index, "total_assets", latest.fields.total_assets)?; - check_opt_finite(row, row_index, "total_equity", latest.fields.total_equity)?; - check_opt_finite( - row, - row_index, - "shares_outstanding", - latest.fields.shares_outstanding, - )?; - - if let Some(ttm) = row.ttm.as_ref() { - if ttm.currency.trim().is_empty() { - return Err(ParquetFundamentalsError::EmptyTtmCurrency { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - check_opt_finite(row, row_index, "ttm_revenue", ttm.flows.revenue)?; - check_opt_finite(row, row_index, "ttm_net_income", ttm.flows.net_income)?; - check_opt_finite( - row, - row_index, - "ttm_operating_cash_flow", - ttm.flows.operating_cash_flow, - )?; - } - - Ok((year, latest)) -} - -#[inline] -fn push_opt_f64(values: &mut Vec, defs: &mut Vec, val: Option) { - match val { - Some(v) => { - values.push(v); - defs.push(1); - } - None => { - defs.push(0); - } - } -} - -#[derive(Default)] -struct RowGroupBuffer { - listing_id: Vec, - effective_known_at_micros: Vec, - known_at_source_ids: Vec, - known_at_source_interner: StringInterner, - has_estimated_lag: Vec, - period_end: Vec, - fiscal_period_ids: Vec, - fiscal_period_interner: StringInterner, - currency_ids: Vec, - currency_interner: StringInterner, - period_known_at_micros: Vec, - revenue_values: Vec, - revenue_def: Vec, - net_income_values: Vec, - net_income_def: Vec, - operating_cash_flow_values: Vec, - operating_cash_flow_def: Vec, - total_assets_values: Vec, - total_assets_def: Vec, - total_equity_values: Vec, - total_equity_def: Vec, - shares_outstanding_values: Vec, - shares_outstanding_def: Vec, - ttm_period_end_values: Vec, - ttm_period_end_def: Vec, - ttm_currency_ids: Vec, - ttm_currency_def: Vec, - ttm_currency_interner: StringInterner, - ttm_revenue_values: Vec, - ttm_revenue_def: Vec, - ttm_net_income_values: Vec, - ttm_net_income_def: Vec, - ttm_operating_cash_flow_values: Vec, - ttm_operating_cash_flow_def: Vec, - ttm_has_estimated_lag_values: Vec, - ttm_has_estimated_lag_def: Vec, -} - -impl RowGroupBuffer { - #[inline] - fn len(&self) -> usize { - self.listing_id.len() - } - - fn push(&mut self, row: &FundamentalsPitParquetRow, latest: &FundamentalsPitLatestPeriod) { - self.listing_id.push(row.listing_id); - self.effective_known_at_micros - .push(row.effective_known_at_micros); - let kas_id = self - .known_at_source_interner - .intern(row.known_at_source.as_ref()); - self.known_at_source_ids.push(kas_id); - self.has_estimated_lag.push(row.has_estimated_lag); - self.period_end.push(latest.period_end); - let fp_id = self - .fiscal_period_interner - .intern(latest.fiscal_period.as_ref()); - self.fiscal_period_ids.push(fp_id); - let cur_id = self.currency_interner.intern(latest.currency.as_str()); - self.currency_ids.push(cur_id); - self.period_known_at_micros - .push(latest.period_known_at_micros); - - push_opt_f64( - &mut self.revenue_values, - &mut self.revenue_def, - latest.fields.revenue, - ); - push_opt_f64( - &mut self.net_income_values, - &mut self.net_income_def, - latest.fields.net_income, - ); - push_opt_f64( - &mut self.operating_cash_flow_values, - &mut self.operating_cash_flow_def, - latest.fields.operating_cash_flow, - ); - push_opt_f64( - &mut self.total_assets_values, - &mut self.total_assets_def, - latest.fields.total_assets, - ); - push_opt_f64( - &mut self.total_equity_values, - &mut self.total_equity_def, - latest.fields.total_equity, - ); - push_opt_f64( - &mut self.shares_outstanding_values, - &mut self.shares_outstanding_def, - latest.fields.shares_outstanding, - ); - - match row.ttm.as_ref() { - Some(ttm) => { - self.ttm_period_end_values.push(ttm.ending_period_end); - self.ttm_period_end_def.push(1); - let ttm_cur_id = self.ttm_currency_interner.intern(ttm.currency.as_str()); - self.ttm_currency_ids.push(ttm_cur_id); - self.ttm_currency_def.push(1); - push_opt_f64( - &mut self.ttm_revenue_values, - &mut self.ttm_revenue_def, - ttm.flows.revenue, - ); - push_opt_f64( - &mut self.ttm_net_income_values, - &mut self.ttm_net_income_def, - ttm.flows.net_income, - ); - push_opt_f64( - &mut self.ttm_operating_cash_flow_values, - &mut self.ttm_operating_cash_flow_def, - ttm.flows.operating_cash_flow, - ); - self.ttm_has_estimated_lag_values - .push(ttm.has_estimated_lag); - self.ttm_has_estimated_lag_def.push(1); - } - None => { - self.ttm_period_end_def.push(0); - self.ttm_currency_def.push(0); - self.ttm_revenue_def.push(0); - self.ttm_net_income_def.push(0); - self.ttm_operating_cash_flow_def.push(0); - self.ttm_has_estimated_lag_def.push(0); - } - } - } - - fn clear(&mut self) { - self.listing_id.clear(); - self.effective_known_at_micros.clear(); - self.known_at_source_ids.clear(); - self.known_at_source_interner.clear(); - self.has_estimated_lag.clear(); - self.period_end.clear(); - self.fiscal_period_ids.clear(); - self.fiscal_period_interner.clear(); - self.currency_ids.clear(); - self.currency_interner.clear(); - self.period_known_at_micros.clear(); - self.revenue_values.clear(); - self.revenue_def.clear(); - self.net_income_values.clear(); - self.net_income_def.clear(); - self.operating_cash_flow_values.clear(); - self.operating_cash_flow_def.clear(); - self.total_assets_values.clear(); - self.total_assets_def.clear(); - self.total_equity_values.clear(); - self.total_equity_def.clear(); - self.shares_outstanding_values.clear(); - self.shares_outstanding_def.clear(); - self.ttm_period_end_values.clear(); - self.ttm_period_end_def.clear(); - self.ttm_currency_ids.clear(); - self.ttm_currency_def.clear(); - self.ttm_currency_interner.clear(); - self.ttm_revenue_values.clear(); - self.ttm_revenue_def.clear(); - self.ttm_net_income_values.clear(); - self.ttm_net_income_def.clear(); - self.ttm_operating_cash_flow_values.clear(); - self.ttm_operating_cash_flow_def.clear(); - self.ttm_has_estimated_lag_values.clear(); - self.ttm_has_estimated_lag_def.clear(); - } -} - -struct YearWriter { - tmp_path: PathBuf, - final_path: PathBuf, - writer: SerializedFileWriter>, - buf: RowGroupBuffer, - rows_written: usize, - row_groups_written: usize, -} - -impl YearWriter { - fn open( - dataset_dir: &Path, - year: i32, - run_id: &str, - schema: &TypePtr, - props: &WriterPropertiesPtr, - staging_guards: &mut BTreeMap, - ) -> Result { - let year_dir = dataset_dir.join(format!("year={year:04}")); - fs::create_dir_all(&year_dir).map_err(|source| ParquetFundamentalsError::Io { - path: year_dir.clone(), - source, - })?; - - let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; - staging_guards.insert(year, StagingFileGuard::new(tmp_path.clone())); - let final_path = year_dir.join("part.parquet"); - - let buf_writer = BufWriter::with_capacity(FILE_BUF_CAPACITY_BYTES, file); - let writer = SerializedFileWriter::new(buf_writer, schema.clone(), props.clone()).map_err( - |source| ParquetFundamentalsError::Parquet { - path: tmp_path.clone(), - source, - }, - )?; - - Ok(Self { - tmp_path, - final_path, - writer, - buf: RowGroupBuffer::default(), - rows_written: 0, - row_groups_written: 0, - }) - } - - fn flush_row_group( - &mut self, - scratch: &mut Vec, - ) -> Result<(), ParquetFundamentalsError> { - let row_count = self.buf.len(); - if row_count == 0 { - return Ok(()); - } - - let map_pq = |source: ParquetError| ParquetFundamentalsError::Parquet { - path: self.tmp_path.clone(), - source, - }; - - let mut rg_writer = self.writer.next_row_group().map_err(map_pq)?; - - // 1. listing_id (INT32, REQUIRED) - write_i32_col(&mut rg_writer, &self.buf.listing_id).map_err(map_pq)?; - // 2. effective_known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) - write_i64_col(&mut rg_writer, &self.buf.effective_known_at_micros).map_err(map_pq)?; - // 3. known_at_source (BYTE_ARRAY, REQUIRED, STRING) - write_interned_str_col( - &mut rg_writer, - &self.buf.known_at_source_ids, - &self.buf.known_at_source_interner, - scratch, - ) - .map_err(map_pq)?; - // 4. has_estimated_lag (BOOLEAN, REQUIRED) - write_bool_col(&mut rg_writer, &self.buf.has_estimated_lag, None).map_err(map_pq)?; - // 5. period_end (INT32, REQUIRED, DATE) - write_i32_col(&mut rg_writer, &self.buf.period_end).map_err(map_pq)?; - // 6. fiscal_period (BYTE_ARRAY, REQUIRED, STRING) - write_interned_str_col( - &mut rg_writer, - &self.buf.fiscal_period_ids, - &self.buf.fiscal_period_interner, - scratch, - ) - .map_err(map_pq)?; - // 7. currency (BYTE_ARRAY, REQUIRED, STRING) - write_interned_str_col( - &mut rg_writer, - &self.buf.currency_ids, - &self.buf.currency_interner, - scratch, - ) - .map_err(map_pq)?; - // 8. period_known_at (INT64, REQUIRED, TIMESTAMP MICROS UTC) - write_i64_col(&mut rg_writer, &self.buf.period_known_at_micros).map_err(map_pq)?; - // 9. revenue (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.revenue_values, - &self.buf.revenue_def, - ) - .map_err(map_pq)?; - // 10. net_income (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.net_income_values, - &self.buf.net_income_def, - ) - .map_err(map_pq)?; - // 11. operating_cash_flow (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.operating_cash_flow_values, - &self.buf.operating_cash_flow_def, - ) - .map_err(map_pq)?; - // 12. total_assets (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.total_assets_values, - &self.buf.total_assets_def, - ) - .map_err(map_pq)?; - // 13. total_equity (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.total_equity_values, - &self.buf.total_equity_def, - ) - .map_err(map_pq)?; - // 14. shares_outstanding (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.shares_outstanding_values, - &self.buf.shares_outstanding_def, - ) - .map_err(map_pq)?; - // 15. ttm_period_end (INT32, OPTIONAL, DATE) - write_optional_i32_col( - &mut rg_writer, - &self.buf.ttm_period_end_values, - &self.buf.ttm_period_end_def, - ) - .map_err(map_pq)?; - // 16. ttm_currency (BYTE_ARRAY, OPTIONAL, STRING) - write_optional_interned_str_col( - &mut rg_writer, - &self.buf.ttm_currency_ids, - &self.buf.ttm_currency_def, - &self.buf.ttm_currency_interner, - scratch, - ) - .map_err(map_pq)?; - // 17. ttm_revenue (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.ttm_revenue_values, - &self.buf.ttm_revenue_def, - ) - .map_err(map_pq)?; - // 18. ttm_net_income (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.ttm_net_income_values, - &self.buf.ttm_net_income_def, - ) - .map_err(map_pq)?; - // 19. ttm_operating_cash_flow (DOUBLE, OPTIONAL) - write_optional_f64_col( - &mut rg_writer, - &self.buf.ttm_operating_cash_flow_values, - &self.buf.ttm_operating_cash_flow_def, - ) - .map_err(map_pq)?; - // 20. ttm_has_estimated_lag (BOOLEAN, OPTIONAL) - write_bool_col( - &mut rg_writer, - &self.buf.ttm_has_estimated_lag_values, - Some(&self.buf.ttm_has_estimated_lag_def), - ) - .map_err(map_pq)?; - - rg_writer.close().map_err(map_pq)?; - - self.rows_written += row_count; - self.row_groups_written += 1; - self.buf.clear(); - Ok(()) - } - - fn finish_and_sync( - mut self, - scratch: &mut Vec, - ) -> Result { - self.flush_row_group(scratch)?; - - let mut buf_writer = - self.writer - .into_inner() - .map_err(|source| ParquetFundamentalsError::Parquet { - path: self.tmp_path.clone(), - source, - })?; - buf_writer - .flush() - .map_err(|source| ParquetFundamentalsError::Io { - path: self.tmp_path.clone(), - source, - })?; - let file = buf_writer - .into_inner() - .map_err(|err| ParquetFundamentalsError::Io { - path: self.tmp_path.clone(), - source: err.into_error(), - })?; - file.sync_all() - .map_err(|source| ParquetFundamentalsError::Io { - path: self.tmp_path.clone(), - source, - })?; - let bytes = file - .metadata() - .map_err(|source| ParquetFundamentalsError::Io { - path: self.tmp_path.clone(), - source, - })? - .len(); - drop(file); - - Ok(SyncedYearFile { - tmp_path: self.tmp_path, - final_path: self.final_path, - rows_written: self.rows_written, - row_groups_written: self.row_groups_written, - bytes, - }) - } -} - -struct SyncedYearFile { - tmp_path: PathBuf, - final_path: PathBuf, - rows_written: usize, - row_groups_written: usize, - bytes: u64, -} - -fn finish_with_rollback( - cause: ParquetFundamentalsError, - published: &[PublishedPartition], - extra_failure: Option, -) -> ParquetFundamentalsError { - let mut failures = Vec::new(); - if let Some(failure) = extra_failure { - failures.push(failure); - } - failures.extend(rollback_published(published)); - if failures.is_empty() { - cause - } else { - ParquetFundamentalsError::RollbackFailed { - cause: Box::new(cause), - failures, - } - } -} - -/// Streams strictly ascending `(listing_id, effective_known_at)` snapshot rows into -/// year-partitioned Zstd Parquet files at `/fundamentals_pit/year=YYYY/part.parquet`, -/// partitioned by the UTC year of `effective_known_at`. -/// -/// # Sort Order & Validation -/// Input rows must be strictly ascending and unique by `(listing_id, effective_known_at)`. -/// Out-of-order rows, duplicate keys, snapshots with empty `periods`, partition years outside -/// `MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR`, empty string metadata fields, and non-finite numeric -/// values return typed [`ParquetFundamentalsError`] variants with nothing published. Empty input -/// returns `Ok(FundamentalsPitWriteStats::default())` without creating -/// `/fundamentals_pit` or touching pre-existing partitions. -/// -/// # Concurrency & Atomicity -/// Concurrent writers targeting the same `/fundamentals_pit` directory are serialized via -/// an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file. Every year -/// partition is written to an exclusively created per-run staging file (`part.parquet..tmp`), -/// flushed, and `sync_all`'d before publication. Pre-existing `part.parquet` files are backed up -/// in place (hard link with exclusive copy fallback) so the live path remains readable until -/// replaced by a single atomic `rename`; on any error or unwind, all open writers close before -/// owned staging files are unlinked, replaced partitions are restored from backup, and newly -/// published partitions are removed (reporting rollback errors via -/// [`ParquetFundamentalsError::RollbackFailed`]). -pub fn write_fundamentals_pit_dataset( - out_dir: P, - rows: I, - options: FundamentalsPitWriteOptions, -) -> Result -where - P: AsRef, - I: IntoIterator, - R: Borrow, -{ - write_fundamentals_pit_dataset_with_hooks( - out_dir, - rows, - options, - DEFAULT_LOCK_TIMEOUT, - |_, _, _| {}, - ) -} - -fn write_fundamentals_pit_dataset_with_hooks( - out_dir: P, - rows: I, - options: FundamentalsPitWriteOptions, - lock_timeout: Duration, - mut on_after_backup: F, -) -> Result -where - P: AsRef, - I: IntoIterator, - R: Borrow, - F: FnMut(i32, &Path, Option<&Path>), -{ - if options.row_group_rows == 0 { - return Err(ParquetFundamentalsError::InvalidRowGroupRows); - } - let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { - ParquetFundamentalsError::InvalidZstdLevel { - level: options.zstd_level, - } - })?; - - let mut row_iter = rows.into_iter(); - let Some(first_item) = row_iter.next() else { - return Ok(FundamentalsPitWriteStats::default()); - }; - validate_row(first_item.borrow(), 0)?; - - let out_dir = out_dir.as_ref(); - let dataset_dir = out_dir.join("fundamentals_pit"); - let schema = - fundamentals_pit_parquet_schema().map_err(|source| ParquetFundamentalsError::Parquet { - path: dataset_dir.clone(), - source, - })?; - let props = build_writer_properties(zstd_level); - - fs::create_dir_all(&dataset_dir).map_err(|source| ParquetFundamentalsError::Io { - path: dataset_dir.clone(), - source, - })?; - - let dataset_mu = dataset_mutex(&dataset_dir); - let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); - let _file_lock = DatasetFileLock::acquire_with_timeout(&dataset_dir, lock_timeout)?; - - let run_id = next_run_id(); - // Declared before `writers` so Rust's reverse drop order closes all Parquet file handles - // before unlinking owned `.tmp` staging files on error or panic unwind. - let mut staging_guards: BTreeMap = BTreeMap::new(); - let mut writers: BTreeMap = BTreeMap::new(); - let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); - - let synced_files: Vec<(i32, SyncedYearFile)> = { - let mut prev_key: Option<(i32, i64)> = None; - - for (row_index, item) in std::iter::once(first_item).chain(row_iter).enumerate() { - let row = item.borrow(); - let key = (row.listing_id, row.effective_known_at_micros); - if let Some((prev_listing_id, prev_effective_known_at_micros)) = prev_key { - match key.cmp(&(prev_listing_id, prev_effective_known_at_micros)) { - Ordering::Equal => { - return Err(ParquetFundamentalsError::DuplicateRow { - row_index, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - Ordering::Less => { - return Err(ParquetFundamentalsError::UnsortedInput { - row_index, - prev_listing_id, - prev_effective_known_at_micros, - listing_id: row.listing_id, - effective_known_at_micros: row.effective_known_at_micros, - }); - } - Ordering::Greater => {} - } - } - - let (year, latest) = validate_row(row, row_index)?; - - let yw = match writers.entry(year) { - std::collections::btree_map::Entry::Occupied(entry) => entry.into_mut(), - std::collections::btree_map::Entry::Vacant(entry) => { - let opened = YearWriter::open( - &dataset_dir, - year, - &run_id, - &schema, - &props, - &mut staging_guards, - )?; - entry.insert(opened) - } - }; - - yw.buf.push(row, latest); - if yw.buf.len() == options.row_group_rows { - yw.flush_row_group(&mut scratch)?; - } - prev_key = Some(key); - } - - let mut synced = Vec::with_capacity(writers.len()); - let drained: Vec<(i32, YearWriter)> = std::mem::take(&mut writers).into_iter().collect(); - for (year, yw) in drained { - let file = yw.finish_and_sync(&mut scratch)?; - synced.push((year, file)); - } - synced - }; - - let mut stats = FundamentalsPitWriteStats::default(); - let mut published: Vec = Vec::with_capacity(synced_files.len()); - for (year, file) in synced_files { - let backup_path = match fs::symlink_metadata(&file.final_path) { - Ok(meta) if !meta.is_dir() => { - match create_backup_preserving_live(&file.final_path, &run_id) { - Ok(bak) => Some(bak), - Err(err) => { - return Err(finish_with_rollback(err.into(), &published, None)); - } - } - } - // Directory occupying final_path: leave it in place so the rename below fails - // cleanly and triggers rollback of all earlier partitions. - Ok(_) => None, - Err(err) if err.kind() == io::ErrorKind::NotFound => None, - Err(source) => { - let err = ParquetFundamentalsError::Io { - path: file.final_path, - source, - }; - return Err(finish_with_rollback(err, &published, None)); - } - }; - - on_after_backup(year, &file.final_path, backup_path.as_deref()); - - if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) { - let extra_failure = backup_path.and_then(|bak| { - fs::remove_file(&bak).err().map(|remove_err| RollbackFailure { - final_path: file.final_path.clone(), - backup_path: Some(bak), - source: remove_err, - }) - }); - let err = ParquetFundamentalsError::Io { - path: file.final_path, - source, - }; - return Err(finish_with_rollback(err, &published, extra_failure)); - } - - if let Some(guard) = staging_guards.get_mut(&year) { - guard.disarm(); - } - - published.push(PublishedPartition { - final_path: file.final_path, - backup_path, - }); - stats.rows_written += file.rows_written; - stats.files_written += 1; - stats.row_groups_written += file.row_groups_written; - stats.bytes_written += file.bytes; - stats.rows_by_year.insert(year, file.rows_written); - } - - for part in &published { - if let Some(bak) = &part.backup_path { - let _ = fs::remove_file(bak); - } - } - - Ok(stats) -} - -#[cfg(test)] -#[path = "parquet_fundamentals_tests.rs"] -mod tests; diff --git a/tools/curate-etl/src/parquet_fundamentals_tests.rs b/tools/curate-etl/src/parquet_fundamentals_tests.rs deleted file mode 100644 index de8b46e2..00000000 --- a/tools/curate-etl/src/parquet_fundamentals_tests.rs +++ /dev/null @@ -1,1907 +0,0 @@ -//! Round-trip, schema, partitioning, validation, and atomic rollback tests for -//! `parquet_fundamentals`. - -use std::borrow::Cow; -use std::collections::BTreeMap; -use std::fs::{self, File}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; - -use parquet::basic::{ - Compression, ConvertedType, LogicalType, Repetition, TimeUnit, Type as PhysicalType, -}; -use parquet::column::reader::ColumnReader; -use parquet::file::reader::{FileReader, SerializedFileReader}; - -use super::{ - fundamentals_pit_parquet_schema, write_fundamentals_pit_dataset, FundamentalsPitLatestPeriod, - FundamentalsPitParquetRow, FundamentalsPitWriteOptions, FundamentalsPitWriteStats, - ParquetFundamentalsError, DEFAULT_ZSTD_LEVEL, -}; -use crate::events::{ - partition_year_utc, QmFiling, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, -}; -use crate::fundamentals::{ - build_fundamentals_rows, build_fundamentals_snapshots, FinancialObservation, FiscalPeriod, - FundamentalsFields, FundamentalsSnapshot, FundamentalsTtm, StatutoryLagVenue, TtmFlowFields, -}; -use crate::split::ymd_to_epoch_days; - -static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); - -struct TempDirGuard { - path: PathBuf, -} - -impl TempDirGuard { - fn new(label: &str) -> Self { - let seq = TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); - let pid = std::process::id(); - let path = std::env::temp_dir().join(format!( - "curate-etl-pq-fundamentals-test-{label}-{pid}-{seq}" - )); - let _ = fs::remove_dir_all(&path); - fs::create_dir_all(&path).expect("create test temp dir"); - Self { path } - } - - fn path(&self) -> &Path { - &self.path - } -} - -impl Drop for TempDirGuard { - fn drop(&mut self) { - let _ = fs::remove_dir_all(&self.path); - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid test date") -} - -fn utc_micros(y: i32, m: u32, d: u32, hour: u8, minute: u8, second: u8, micro: i64) -> i64 { - let epoch_day = day(y, m, d); - let secs = i64::from(epoch_day) * 86_400 - + i64::from(hour) * 3_600 - + i64::from(minute) * 60 - + i64::from(second); - secs * 1_000_000 + micro -} - -fn filing(key: i32, timefiled: &str, form_type: &str) -> QmFiling { - QmFiling { - key, - timefiled: timefiled.to_string(), - form_type: form_type.to_string(), - filing_id: None, - url: None, - } -} - -fn obs( - key: i32, - period_end: i32, - fiscal_period: FiscalPeriod, - currency: &str, - report_date: Option, - fields: FundamentalsFields, -) -> FinancialObservation { - FinancialObservation { - key, - period_end, - fiscal_period, - currency: currency.to_string(), - report_date, - fields, - } -} - -#[derive(Debug, Clone, PartialEq)] -struct DecodedFundamentalsPitRow { - listing_id: i32, - effective_known_at: i64, - known_at_source: String, - has_estimated_lag: bool, - period_end: i32, - fiscal_period: String, - currency: String, - period_known_at: i64, - revenue: Option, - net_income: Option, - operating_cash_flow: Option, - total_assets: Option, - total_equity: Option, - shares_outstanding: Option, - ttm_period_end: Option, - ttm_currency: Option, - ttm_revenue: Option, - ttm_net_income: Option, - ttm_operating_cash_flow: Option, - ttm_has_estimated_lag: Option, -} - -fn read_parquet_rows(path: &Path) -> Vec { - let file = File::open(path).expect("open parquet file"); - let reader = SerializedFileReader::new(file).expect("open parquet reader"); - let meta = reader.metadata(); - let mut out = Vec::new(); - - for rg_idx in 0..meta.num_row_groups() { - let rg_rows = meta.row_group(rg_idx).num_rows() as usize; - let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); - - let read_req_i32 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read req i32"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT32 at col {col_idx}"), - } - vals - }; - - let read_opt_i32 = |col_idx: usize| -> Vec> { - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int32ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read opt i32"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT32 at col {col_idx}"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_req_i64 = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::Int64ColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read req i64"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected INT64 at col {col_idx}"), - } - vals - }; - - let read_req_bool = |col_idx: usize| -> Vec { - let mut vals = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::BoolColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut vals) - .expect("read req bool"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BOOLEAN at col {col_idx}"), - } - vals - }; - - let read_opt_bool = |col_idx: usize| -> Vec> { - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::BoolColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read opt bool"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BOOLEAN at col {col_idx}"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_opt_f64 = |col_idx: usize| -> Vec> { - let mut vals = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::DoubleColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut vals) - .expect("read opt f64"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected DOUBLE at col {col_idx}"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let v = vals[vi]; - vi += 1; - Some(v) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let read_req_str = |col_idx: usize| -> Vec { - let mut raw = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, None, None, &mut raw) - .expect("read req str"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BYTE_ARRAY at col {col_idx}"), - } - raw.iter() - .map(|b| std::str::from_utf8(b.data()).expect("valid utf8").to_string()) - .collect() - }; - - let read_opt_str = |col_idx: usize| -> Vec> { - let mut raw = Vec::with_capacity(rg_rows); - let mut defs = Vec::with_capacity(rg_rows); - match rg_reader.get_column_reader(col_idx).expect("col reader") { - ColumnReader::ByteArrayColumnReader(mut typed) => { - let mut read = 0usize; - while read < rg_rows { - let (n, _, _) = typed - .read_records(rg_rows - read, Some(&mut defs), None, &mut raw) - .expect("read opt str"); - assert!(n > 0); - read += n; - } - } - _ => panic!("expected BYTE_ARRAY at col {col_idx}"), - } - let mut vi = 0usize; - defs.into_iter() - .map(|d| { - if d == 1 { - let s = std::str::from_utf8(raw[vi].data()) - .expect("valid utf8") - .to_string(); - vi += 1; - Some(s) - } else { - assert_eq!(d, 0); - None - } - }) - .collect() - }; - - let listing_id = read_req_i32(0); - let effective_known_at = read_req_i64(1); - let known_at_source = read_req_str(2); - let has_estimated_lag = read_req_bool(3); - let period_end = read_req_i32(4); - let fiscal_period = read_req_str(5); - let currency = read_req_str(6); - let period_known_at = read_req_i64(7); - let revenue = read_opt_f64(8); - let net_income = read_opt_f64(9); - let operating_cash_flow = read_opt_f64(10); - let total_assets = read_opt_f64(11); - let total_equity = read_opt_f64(12); - let shares_outstanding = read_opt_f64(13); - let ttm_period_end = read_opt_i32(14); - let ttm_currency = read_opt_str(15); - let ttm_revenue = read_opt_f64(16); - let ttm_net_income = read_opt_f64(17); - let ttm_operating_cash_flow = read_opt_f64(18); - let ttm_has_estimated_lag = read_opt_bool(19); - - for i in 0..rg_rows { - out.push(DecodedFundamentalsPitRow { - listing_id: listing_id[i], - effective_known_at: effective_known_at[i], - known_at_source: known_at_source[i].clone(), - has_estimated_lag: has_estimated_lag[i], - period_end: period_end[i], - fiscal_period: fiscal_period[i].clone(), - currency: currency[i].clone(), - period_known_at: period_known_at[i], - revenue: revenue[i], - net_income: net_income[i], - operating_cash_flow: operating_cash_flow[i], - total_assets: total_assets[i], - total_equity: total_equity[i], - shares_outstanding: shares_outstanding[i], - ttm_period_end: ttm_period_end[i], - ttm_currency: ttm_currency[i].clone(), - ttm_revenue: ttm_revenue[i], - ttm_net_income: ttm_net_income[i], - ttm_operating_cash_flow: ttm_operating_cash_flow[i], - ttm_has_estimated_lag: ttm_has_estimated_lag[i], - }); - } - } - - out -} - -fn assert_no_transient_files(dir: &Path) { - if !dir.exists() { - return; - } - fn walk(dir: &Path) { - for entry in fs::read_dir(dir).expect("read_dir") { - let path = entry.expect("dir entry").path(); - if path.is_dir() { - walk(&path); - } else { - let name = path - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or_default(); - assert!( - !name.ends_with(".tmp") && !name.ends_with(".bak") && name != ".write.lock", - "unexpected transient file left behind: {}", - path.display() - ); - } - } - } - walk(dir); -} - -fn make_row( - listing_id: i32, - effective_known_at_micros: i64, - period_end: i32, - revenue: Option, - ttm: Option, -) -> FundamentalsPitParquetRow { - FundamentalsPitParquetRow::new( - listing_id, - effective_known_at_micros, - Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), - false, - FundamentalsPitLatestPeriod { - period_end, - fiscal_period: Cow::Borrowed("Q"), - currency: "USD".to_string(), - period_known_at_micros: effective_known_at_micros, - fields: FundamentalsFields { - revenue, - net_income: revenue.map(|r| r * 0.1), - operating_cash_flow: revenue.map(|r| r * 0.15), - total_assets: Some(500.0), - total_equity: Some(200.0), - shares_outstanding: Some(100.0), - }, - }, - ttm, - ) -} - -#[test] -fn schema_matches_contract_zstd_null_ttm_and_nullable_booleans() { - let tmp = TempDirGuard::new("schema"); - - // 1) Row with no TTM (all 6 ttm_* columns must be null) and some null latest-period fields. - let row_no_ttm = FundamentalsPitParquetRow::new( - 10, - utc_micros(2024, 5, 1, 20, 15, 0, 0), - Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), - false, - FundamentalsPitLatestPeriod { - period_end: day(2024, 3, 31), - fiscal_period: Cow::Borrowed("Q"), - currency: "USD".to_string(), - period_known_at_micros: utc_micros(2024, 5, 1, 20, 15, 0, 0), - fields: FundamentalsFields { - revenue: Some(100.0), - net_income: None, - operating_cash_flow: Some(15.0), - total_assets: None, - total_equity: Some(220.0), - shares_outstanding: None, - }, - }, - None, - ); - - // 2) Row with TTM where ttm_has_estimated_lag = Some(false) and all flows present. - let row_ttm_false = FundamentalsPitParquetRow::new( - 10, - utc_micros(2024, 8, 1, 20, 15, 0, 0), - Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), - false, - FundamentalsPitLatestPeriod { - period_end: day(2024, 6, 30), - fiscal_period: Cow::Borrowed("Q"), - currency: "USD".to_string(), - period_known_at_micros: utc_micros(2024, 8, 1, 20, 15, 0, 0), - fields: FundamentalsFields { - revenue: Some(120.0), - net_income: Some(12.0), - operating_cash_flow: Some(18.0), - total_assets: Some(560.0), - total_equity: Some(230.0), - shares_outstanding: Some(100.0), - }, - }, - Some(FundamentalsTtm { - ending_period_end: day(2024, 6, 30), - currency: "USD".to_string(), - flows: TtmFlowFields { - revenue: Some(370.0), - net_income: Some(37.0), - operating_cash_flow: Some(55.0), - }, - has_estimated_lag: false, - }), - ); - - // 3) Row with TTM where ttm_has_estimated_lag = Some(true), FY latest period, and partial null TTM flow. - let row_ttm_true = FundamentalsPitParquetRow::new( - 10, - utc_micros(2024, 11, 15, 21, 5, 0, 0), - Cow::Borrowed(KNOWN_AT_SOURCE_STATUTORY_LAG), - true, - FundamentalsPitLatestPeriod { - period_end: day(2024, 9, 30), - fiscal_period: Cow::Borrowed("FY"), - currency: "CAD".to_string(), - period_known_at_micros: utc_micros(2024, 11, 15, 21, 5, 0, 0), - fields: FundamentalsFields { - revenue: Some(450.0), - net_income: Some(45.0), - operating_cash_flow: None, - total_assets: Some(600.0), - total_equity: Some(250.0), - shares_outstanding: Some(105.0), - }, - }, - Some(FundamentalsTtm { - ending_period_end: day(2024, 9, 30), - currency: "CAD".to_string(), - flows: TtmFlowFields { - revenue: Some(450.0), - net_income: None, - operating_cash_flow: Some(60.0), - }, - has_estimated_lag: true, - }), - ); - - let rows = vec![row_no_ttm, row_ttm_false, row_ttm_true]; - let stats = write_fundamentals_pit_dataset( - tmp.path(), - &rows, - FundamentalsPitWriteOptions::default(), - ) - .expect("write schema test dataset"); - assert_eq!(stats.rows_written, 3); - assert_eq!(stats.files_written, 1); - assert_eq!(stats.rows_by_year, BTreeMap::from([(2024, 3)])); - - let path = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); - let reader = SerializedFileReader::new(File::open(&path).expect("open parquet")) - .expect("open parquet reader"); - let meta = reader.metadata(); - let expected_schema = fundamentals_pit_parquet_schema().expect("schema"); - assert_eq!(meta.file_metadata().schema(), expected_schema.as_ref()); - assert_eq!(expected_schema.name(), "fundamentals_pit"); - - let fields = meta.file_metadata().schema().get_fields(); - assert_eq!(fields.len(), 20); - - let expected_cols: [( - &str, - PhysicalType, - Repetition, - Option, - ConvertedType, - ); 20] = [ - ( - "listing_id", - PhysicalType::INT32, - Repetition::REQUIRED, - None, - ConvertedType::NONE, - ), - ( - "effective_known_at", - PhysicalType::INT64, - Repetition::REQUIRED, - Some(LogicalType::timestamp(true, TimeUnit::MICROS)), - ConvertedType::TIMESTAMP_MICROS, - ), - ( - "known_at_source", - PhysicalType::BYTE_ARRAY, - Repetition::REQUIRED, - Some(LogicalType::String), - ConvertedType::UTF8, - ), - ( - "has_estimated_lag", - PhysicalType::BOOLEAN, - Repetition::REQUIRED, - None, - ConvertedType::NONE, - ), - ( - "period_end", - PhysicalType::INT32, - Repetition::REQUIRED, - Some(LogicalType::Date), - ConvertedType::DATE, - ), - ( - "fiscal_period", - PhysicalType::BYTE_ARRAY, - Repetition::REQUIRED, - Some(LogicalType::String), - ConvertedType::UTF8, - ), - ( - "currency", - PhysicalType::BYTE_ARRAY, - Repetition::REQUIRED, - Some(LogicalType::String), - ConvertedType::UTF8, - ), - ( - "period_known_at", - PhysicalType::INT64, - Repetition::REQUIRED, - Some(LogicalType::timestamp(true, TimeUnit::MICROS)), - ConvertedType::TIMESTAMP_MICROS, - ), - ( - "revenue", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "net_income", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "operating_cash_flow", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "total_assets", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "total_equity", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "shares_outstanding", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "ttm_period_end", - PhysicalType::INT32, - Repetition::OPTIONAL, - Some(LogicalType::Date), - ConvertedType::DATE, - ), - ( - "ttm_currency", - PhysicalType::BYTE_ARRAY, - Repetition::OPTIONAL, - Some(LogicalType::String), - ConvertedType::UTF8, - ), - ( - "ttm_revenue", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "ttm_net_income", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "ttm_operating_cash_flow", - PhysicalType::DOUBLE, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ( - "ttm_has_estimated_lag", - PhysicalType::BOOLEAN, - Repetition::OPTIONAL, - None, - ConvertedType::NONE, - ), - ]; - - for (idx, (name, phys, rep, logical, converted)) in expected_cols.into_iter().enumerate() { - let field = &fields[idx]; - assert_eq!(field.name(), name, "column {idx} name"); - assert_eq!(field.get_physical_type(), phys, "column {idx} physical type"); - assert_eq!( - field.get_basic_info().repetition(), - rep, - "column {idx} repetition" - ); - assert_eq!( - field.get_basic_info().logical_type_ref().cloned(), - logical, - "column {idx} logical type" - ); - assert_eq!( - field.get_basic_info().converted_type(), - converted, - "column {idx} converted type" - ); - } - - for rg in meta.row_groups() { - for col in rg.columns() { - assert!( - matches!(col.compression(), Compression::ZSTD(_)), - "column {} must use ZSTD compression", - col.column_path() - ); - } - } - - let decoded = read_parquet_rows(&path); - assert_eq!(decoded.len(), 3); - - // Row 0: no TTM -> all 6 ttm_* columns are None. - assert_eq!(decoded[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!decoded[0].has_estimated_lag); - assert_eq!(decoded[0].revenue, Some(100.0)); - assert_eq!(decoded[0].net_income, None); - assert_eq!(decoded[0].operating_cash_flow, Some(15.0)); - assert_eq!(decoded[0].total_assets, None); - assert_eq!(decoded[0].total_equity, Some(220.0)); - assert_eq!(decoded[0].shares_outstanding, None); - assert_eq!(decoded[0].ttm_period_end, None); - assert_eq!(decoded[0].ttm_currency, None); - assert_eq!(decoded[0].ttm_revenue, None); - assert_eq!(decoded[0].ttm_net_income, None); - assert_eq!(decoded[0].ttm_operating_cash_flow, None); - assert_eq!(decoded[0].ttm_has_estimated_lag, None); - - // Row 1: ttm_has_estimated_lag = Some(false) - assert_eq!(decoded[1].ttm_period_end, Some(day(2024, 6, 30))); - assert_eq!(decoded[1].ttm_currency.as_deref(), Some("USD")); - assert_eq!(decoded[1].ttm_revenue, Some(370.0)); - assert_eq!(decoded[1].ttm_net_income, Some(37.0)); - assert_eq!(decoded[1].ttm_operating_cash_flow, Some(55.0)); - assert_eq!(decoded[1].ttm_has_estimated_lag, Some(false)); - - // Row 2: ttm_has_estimated_lag = Some(true), partial missing TTM flow, statutory lag source. - assert_eq!(decoded[2].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert!(decoded[2].has_estimated_lag); - assert_eq!(decoded[2].fiscal_period, "FY"); - assert_eq!(decoded[2].currency, "CAD"); - assert_eq!(decoded[2].ttm_period_end, Some(day(2024, 9, 30))); - assert_eq!(decoded[2].ttm_currency.as_deref(), Some("CAD")); - assert_eq!(decoded[2].ttm_revenue, Some(450.0)); - assert_eq!(decoded[2].ttm_net_income, None); - assert_eq!(decoded[2].ttm_operating_cash_flow, Some(60.0)); - assert_eq!(decoded[2].ttm_has_estimated_lag, Some(true)); - - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); -} - -#[test] -fn restatement_of_q1_after_q2_preserves_q2_on_disk_and_updates_ttm() { - let listing_id = 42_i32; - let venues = BTreeMap::from([(listing_id, StatutoryLagVenue::UsTsx)]); - - let p_2023_q3 = day(2023, 9, 30); - let p_2023_q4 = day(2023, 12, 31); - let p_2024_q1 = day(2024, 3, 31); - let p_2024_q2 = day(2024, 6, 30); - - let initial_filings = vec![ - filing(listing_id, "2023-11-01T16:15:00 EDT", "10-Q"), - filing(listing_id, "2024-02-01T16:15:00 EST", "10-Q"), - filing(listing_id, "2024-05-01T16:15:00 EDT", "10-Q"), - filing(listing_id, "2024-08-01T16:15:00 EDT", "10-Q"), - ]; - let amendment_filing = filing(listing_id, "2024-09-15T17:00:00 EDT", "10-Q/A"); - - let initial_obs = vec![ - obs( - listing_id, - p_2023_q3, - FiscalPeriod::Quarterly, - "USD", - Some(day(2023, 11, 1)), - FundamentalsFields { - revenue: Some(70.0), - net_income: Some(7.0), - operating_cash_flow: Some(10.0), - total_assets: Some(500.0), - total_equity: Some(200.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - listing_id, - p_2023_q4, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 2, 1)), - FundamentalsFields { - revenue: Some(80.0), - net_income: Some(8.0), - operating_cash_flow: Some(12.0), - total_assets: Some(520.0), - total_equity: Some(210.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - listing_id, - p_2024_q1, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 5, 1)), - FundamentalsFields { - revenue: Some(100.0), - net_income: Some(10.0), - operating_cash_flow: Some(15.0), - total_assets: Some(540.0), - total_equity: Some(220.0), - shares_outstanding: Some(100.0), - }, - ), - obs( - listing_id, - p_2024_q2, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 8, 1)), - FundamentalsFields { - revenue: Some(120.0), - net_income: Some(12.0), - operating_cash_flow: Some(18.0), - total_assets: Some(560.0), - total_equity: Some(230.0), - shares_outstanding: Some(100.0), - }, - ), - ]; - - // Late Q1 amendment filed on 2024-09-15 (after Q2's 2024-08-01 filing). - // Restates revenue 100 -> 110 and net_income 10 -> 11, while omitting operating_cash_flow. - let q1_amendment = obs( - listing_id, - p_2024_q1, - FiscalPeriod::Quarterly, - "USD", - Some(day(2024, 9, 15)), - FundamentalsFields { - revenue: Some(110.0), - net_income: Some(11.0), - operating_cash_flow: None, - total_assets: None, - total_equity: Some(225.0), - shares_outstanding: None, - }, - ); - - let mut full_obs = initial_obs.clone(); - full_obs.push(q1_amendment); - let mut full_filings = initial_filings.clone(); - full_filings.push(amendment_filing); - - let full_build = build_fundamentals_rows(full_obs, full_filings, &venues); - let full_snaps = build_fundamentals_snapshots(&full_build.rows, 4).expect("full snapshots"); - assert_eq!(full_snaps.len(), 5); - - let baseline_build = build_fundamentals_rows(initial_obs, initial_filings, &venues); - let baseline_snaps = - build_fundamentals_snapshots(&baseline_build.rows, 4).expect("baseline snapshots"); - assert_eq!(baseline_snaps.len(), 4); - - let full_rows_from_ref: Vec = - full_snaps.iter().map(FundamentalsPitParquetRow::from).collect(); - let full_rows_from_owned: Vec = full_snaps - .into_iter() - .map(FundamentalsPitParquetRow::from) - .collect(); - assert_eq!(full_rows_from_ref, full_rows_from_owned); - - let baseline_rows: Vec = baseline_snaps - .iter() - .map(FundamentalsPitParquetRow::from) - .collect(); - - let tmp_full = TempDirGuard::new("restatement-full"); - let tmp_base = TempDirGuard::new("restatement-baseline"); - - let full_stats = write_fundamentals_pit_dataset( - tmp_full.path(), - &full_rows_from_ref, - FundamentalsPitWriteOptions::default(), - ) - .expect("write full dataset"); - assert_eq!(full_stats.rows_written, 5); - assert_eq!(full_stats.files_written, 2); - assert_eq!(full_stats.rows_by_year, BTreeMap::from([(2023, 1), (2024, 4)])); - - let base_stats = write_fundamentals_pit_dataset( - tmp_base.path(), - &baseline_rows, - FundamentalsPitWriteOptions::default(), - ) - .expect("write baseline dataset"); - assert_eq!(base_stats.rows_written, 4); - assert_eq!(base_stats.files_written, 2); - assert_eq!(base_stats.rows_by_year, BTreeMap::from([(2023, 1), (2024, 3)])); - - let mut full_decoded = read_parquet_rows( - &tmp_full - .path() - .join("fundamentals_pit/year=2023/part.parquet"), - ); - full_decoded.extend(read_parquet_rows( - &tmp_full - .path() - .join("fundamentals_pit/year=2024/part.parquet"), - )); - assert_eq!(full_decoded.len(), 5); - - let mut base_decoded = read_parquet_rows( - &tmp_base - .path() - .join("fundamentals_pit/year=2023/part.parquet"), - ); - base_decoded.extend(read_parquet_rows( - &tmp_base - .path() - .join("fundamentals_pit/year=2024/part.parquet"), - )); - assert_eq!(base_decoded.len(), 4); - - let ts_q2 = utc_micros(2024, 8, 1, 20, 15, 0, 0); - let ts_amend = utc_micros(2024, 9, 15, 21, 0, 0, 0); - - // Every earlier row (before the amendment) must match the unamended baseline identically. - assert_eq!(&full_decoded[..4], &base_decoded[..]); - - // Every row at or after Q2 filing must keep Q2 as the latest visible period with unchanged fields. - let post_q2_rows: Vec<&DecodedFundamentalsPitRow> = full_decoded - .iter() - .filter(|r| r.effective_known_at >= ts_q2) - .collect(); - assert_eq!(post_q2_rows.len(), 2); - assert_eq!(post_q2_rows[0].effective_known_at, ts_q2); - assert_eq!(post_q2_rows[1].effective_known_at, ts_amend); - - for row in &post_q2_rows { - assert_eq!(row.listing_id, listing_id); - assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!row.has_estimated_lag); - assert_eq!(row.period_end, p_2024_q2); - assert_eq!(row.period_known_at, ts_q2); - assert_eq!(row.fiscal_period, "Q"); - assert_eq!(row.currency, "USD"); - assert_eq!(row.revenue, Some(120.0)); - assert_eq!(row.net_income, Some(12.0)); - assert_eq!(row.operating_cash_flow, Some(18.0)); - assert_eq!(row.total_assets, Some(560.0)); - assert_eq!(row.total_equity, Some(230.0)); - assert_eq!(row.shares_outstanding, Some(100.0)); - assert_eq!(row.ttm_period_end, Some(p_2024_q2)); - assert_eq!(row.ttm_currency.as_deref(), Some("USD")); - assert_eq!(row.ttm_has_estimated_lag, Some(false)); - } - - // At Q2 filing (before amendment): TTM uses original Q1 (revenue=100, net_income=10, ocf=15). - assert_eq!(post_q2_rows[0].ttm_revenue, Some(370.0)); - assert_eq!(post_q2_rows[0].ttm_net_income, Some(37.0)); - assert_eq!(post_q2_rows[0].ttm_operating_cash_flow, Some(55.0)); - - // At Q1 amendment: TTM revenue & net_income update (+10, +1); TTM OCF preserves prior Q1's 15.0. - assert_eq!(post_q2_rows[1].ttm_revenue, Some(380.0)); - assert_eq!(post_q2_rows[1].ttm_net_income, Some(38.0)); - assert_eq!(post_q2_rows[1].ttm_operating_cash_flow, Some(55.0)); - - assert_no_transient_files(&tmp_full.path().join("fundamentals_pit")); - assert_no_transient_files(&tmp_base.path().join("fundamentals_pit")); -} - -#[test] -fn utc_year_partitioning_interleaved_listings_and_midnight_boundary() { - let tmp = TempDirGuard::new("partitioning"); - - // Globally ordered by (listing_id, effective_known_at), with interleaved UTC years across - // multiple listings and timestamps 1 microsecond apart across midnight UTC. - let ts_2023_end = utc_micros(2023, 12, 31, 23, 59, 59, 999_999); - let ts_2024_start = utc_micros(2024, 1, 1, 0, 0, 0, 0); - assert_eq!(partition_year_utc(ts_2023_end), 2023); - assert_eq!(partition_year_utc(ts_2024_start), 2024); - - let rows = vec![ - make_row(1, utc_micros(2023, 5, 1, 14, 0, 0, 0), day(2023, 3, 31), Some(10.0), None), - make_row(1, ts_2023_end, day(2023, 9, 30), Some(11.0), None), - make_row(1, ts_2024_start, day(2023, 12, 31), Some(12.0), None), - make_row(2, utc_micros(2023, 8, 1, 14, 0, 0, 0), day(2023, 6, 30), Some(20.0), None), - make_row(2, utc_micros(2024, 2, 1, 14, 0, 0, 0), day(2023, 12, 31), Some(21.0), None), - make_row(3, utc_micros(2023, 11, 1, 14, 0, 0, 0), day(2023, 9, 30), Some(30.0), None), - make_row(3, utc_micros(2024, 5, 1, 14, 0, 0, 0), day(2024, 3, 31), Some(31.0), None), - ]; - - let stats = write_fundamentals_pit_dataset( - tmp.path(), - &rows, - FundamentalsPitWriteOptions { - row_group_rows: 2, - zstd_level: DEFAULT_ZSTD_LEVEL, - }, - ) - .expect("write partitioned dataset"); - - assert_eq!(stats.rows_written, 7); - assert_eq!(stats.files_written, 2); - // 2023: 4 rows -> 2 row groups; 2024: 3 rows -> 2 row groups - assert_eq!(stats.row_groups_written, 4); - assert_eq!(stats.rows_by_year, BTreeMap::from([(2023, 4), (2024, 3)])); - - let path_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); - let path_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); - assert!(path_2023.is_file()); - assert!(path_2024.is_file()); - - let decoded_2023 = read_parquet_rows(&path_2023); - let decoded_2024 = read_parquet_rows(&path_2024); - - assert_eq!(decoded_2023.len(), 4); - assert_eq!(decoded_2024.len(), 3); - - // Verify exact membership and strict sort order by (listing_id, effective_known_at). - for (year, decoded) in [(2023, &decoded_2023), (2024, &decoded_2024)] { - for r in decoded { - assert_eq!(partition_year_utc(r.effective_known_at), year); - } - for pair in decoded.windows(2) { - assert!( - (pair[0].listing_id, pair[0].effective_known_at) - < (pair[1].listing_id, pair[1].effective_known_at), - "year {year} rows must be strictly increasing by (listing_id, effective_known_at)" - ); - } - } - - assert_eq!(decoded_2023[1].effective_known_at, ts_2023_end); - assert_eq!(decoded_2024[0].effective_known_at, ts_2024_start); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); -} - -#[test] -fn invalid_inputs_return_typed_errors_and_preserve_existing_partitions() { - let tmp = TempDirGuard::new("errors"); - - // Seed an existing 2024 partition and snapshot its exact bytes. - let seed = vec![make_row( - 1, - utc_micros(2024, 3, 1, 15, 0, 0, 0), - day(2023, 12, 31), - Some(50.0), - None, - )]; - write_fundamentals_pit_dataset( - tmp.path(), - &seed, - FundamentalsPitWriteOptions::default(), - ) - .expect("seed existing partition"); - let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); - let before_bytes = fs::read(&part_2024).expect("read seed bytes"); - - let rg1 = FundamentalsPitWriteOptions { - row_group_rows: 1, - zstd_level: DEFAULT_ZSTD_LEVEL, - }; - - // 1. Duplicate (listing_id, effective_known_at) with different payload after a valid row. - let ts_a = utc_micros(2024, 5, 1, 20, 0, 0, 0); - let dup_rows = vec![ - make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), - make_row(1, ts_a, day(2024, 3, 31), Some(999.0), None), - ]; - let err = write_fundamentals_pit_dataset(tmp.path(), &dup_rows, rg1).unwrap_err(); - assert!( - matches!( - err, - ParquetFundamentalsError::DuplicateRow { - row_index: 1, - listing_id: 1, - effective_known_at_micros, - } if effective_known_at_micros == ts_a - ), - "expected DuplicateRow, got {err:?}" - ); - assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); - - // 2. Unsorted (descending effective_known_at for same listing) after a valid row. - let ts_b = utc_micros(2024, 8, 1, 20, 0, 0, 0); - let unsorted_ts = vec![ - make_row(1, ts_b, day(2024, 6, 30), Some(120.0), None), - make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), - ]; - let err = write_fundamentals_pit_dataset(tmp.path(), &unsorted_ts, rg1).unwrap_err(); - assert!( - matches!( - err, - ParquetFundamentalsError::UnsortedInput { - row_index: 1, - prev_listing_id: 1, - prev_effective_known_at_micros, - listing_id: 1, - effective_known_at_micros, - } if prev_effective_known_at_micros == ts_b && effective_known_at_micros == ts_a - ), - "expected UnsortedInput, got {err:?}" - ); - assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); - - // 3. Unsorted (descending listing_id) after a valid row. - let unsorted_lid = vec![ - make_row(2, ts_a, day(2024, 3, 31), Some(100.0), None), - make_row(1, ts_b, day(2024, 6, 30), Some(120.0), None), - ]; - let err = write_fundamentals_pit_dataset(tmp.path(), &unsorted_lid, rg1).unwrap_err(); - assert!( - matches!( - err, - ParquetFundamentalsError::UnsortedInput { - row_index: 1, - prev_listing_id: 2, - listing_id: 1, - .. - } - ), - "expected UnsortedInput for descending listing_id, got {err:?}" - ); - assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); - - // 4. Empty periods snapshot (at row_index 0 and at row_index 1 after a flushed row group). - let empty_snap = FundamentalsSnapshot { - key: 1_i32, - effective_known_at_utc_micros: ts_b, - known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, - has_estimated_lag: false, - periods: Vec::new(), - ttm: None, - }; - let empty_row = FundamentalsPitParquetRow::from(&empty_snap); - assert!(empty_row.latest_period().is_none()); - - let tmp_fresh = TempDirGuard::new("empty-periods-first"); - let err_first = write_fundamentals_pit_dataset(tmp_fresh.path(), &[empty_row.clone()], rg1) - .unwrap_err(); - assert!( - matches!( - err_first, - ParquetFundamentalsError::EmptyPeriods { - row_index: 0, - listing_id: 1, - effective_known_at_micros, - } if effective_known_at_micros == ts_b - ), - "expected EmptyPeriods at row 0, got {err_first:?}" - ); - assert!(!tmp_fresh.path().join("fundamentals_pit").exists()); - - let mixed = vec![ - make_row(1, ts_a, day(2024, 3, 31), Some(100.0), None), - empty_row, - ]; - let err_second = write_fundamentals_pit_dataset(tmp.path(), &mixed, rg1).unwrap_err(); - assert!( - matches!( - err_second, - ParquetFundamentalsError::EmptyPeriods { - row_index: 1, - listing_id: 1, - effective_known_at_micros, - } if effective_known_at_micros == ts_b - ), - "expected EmptyPeriods at row 1, got {err_second:?}" - ); - assert_eq!(fs::read(&part_2024).unwrap(), before_bytes); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); - - // 5. Empty input does not create directory or touch existing partitions. - let tmp_empty = TempDirGuard::new("empty-input"); - let empty_stats = write_fundamentals_pit_dataset( - tmp_empty.path(), - std::iter::empty::(), - FundamentalsPitWriteOptions::default(), - ) - .expect("empty input succeeds"); - assert_eq!(empty_stats, FundamentalsPitWriteStats::default()); - assert!(!tmp_empty.path().join("fundamentals_pit").exists()); -} - -#[test] -fn publish_failure_on_later_year_rolls_back_replaced_and_new_partitions() { - let tmp = TempDirGuard::new("rollback"); - - // Seed an existing 2023 partition. - let seed = vec![make_row( - 1, - utc_micros(2023, 5, 1, 14, 0, 0, 0), - day(2023, 3, 31), - Some(50.0), - None, - )]; - write_fundamentals_pit_dataset( - tmp.path(), - &seed, - FundamentalsPitWriteOptions::default(), - ) - .expect("seed 2023"); - - let part_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); - let part_2024 = tmp.path().join("fundamentals_pit/year=2024/part.parquet"); - let part_2025 = tmp.path().join("fundamentals_pit/year=2025/part.parquet"); - let before_2023 = fs::read(&part_2023).expect("read seed 2023"); - - // Occupy year=2025/part.parquet with a directory so rename fails after 2023 (replaced) - // and 2024 (newly created) have been renamed into place. - fs::create_dir_all(&part_2025).expect("create blocking directory at year=2025/part.parquet"); - - let rows = vec![ - make_row(1, utc_micros(2023, 8, 1, 14, 0, 0, 0), day(2023, 6, 30), Some(75.0), None), - make_row(1, utc_micros(2024, 5, 1, 14, 0, 0, 0), day(2024, 3, 31), Some(100.0), None), - make_row(1, utc_micros(2025, 5, 1, 14, 0, 0, 0), day(2025, 3, 31), Some(125.0), None), - ]; - - let err = write_fundamentals_pit_dataset( - tmp.path(), - &rows, - FundamentalsPitWriteOptions::default(), - ) - .unwrap_err(); - assert!( - matches!(err, ParquetFundamentalsError::Io { ref path, .. } if path == &part_2025), - "expected Io error at year=2025/part.parquet, got {err:?}" - ); - - // 2023 must be restored byte for byte; 2024 must be removed; no transient files remain. - assert_eq!(fs::read(&part_2023).expect("read restored 2023"), before_2023); - assert!( - !part_2024.exists(), - "newly published 2024 partition must be removed on rollback" - ); - assert!(part_2025.is_dir()); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); -} - - -// --------------------------------------------------------------------------------------------- -// QA additions (T-143): full-row round-trip equality, builder estimated-lag provenance, -// partial-rewrite semantics, deterministic bytes, and remaining typed validation errors. -// --------------------------------------------------------------------------------------------- - -/// Expected decoded form of a row: what the reader must see after a write/read round trip. -fn expected_decoded(row: &FundamentalsPitParquetRow) -> DecodedFundamentalsPitRow { - let latest = row - .latest_period() - .expect("expected row must have a latest period"); - let ttm = row.ttm.as_ref(); - DecodedFundamentalsPitRow { - listing_id: row.listing_id, - effective_known_at: row.effective_known_at_micros, - known_at_source: row.known_at_source.to_string(), - has_estimated_lag: row.has_estimated_lag, - period_end: latest.period_end, - fiscal_period: latest.fiscal_period.to_string(), - currency: latest.currency.clone(), - period_known_at: latest.period_known_at_micros, - revenue: latest.fields.revenue, - net_income: latest.fields.net_income, - operating_cash_flow: latest.fields.operating_cash_flow, - total_assets: latest.fields.total_assets, - total_equity: latest.fields.total_equity, - shares_outstanding: latest.fields.shares_outstanding, - ttm_period_end: ttm.map(|t| t.ending_period_end), - ttm_currency: ttm.map(|t| t.currency.clone()), - ttm_revenue: ttm.and_then(|t| t.flows.revenue), - ttm_net_income: ttm.and_then(|t| t.flows.net_income), - ttm_operating_cash_flow: ttm.and_then(|t| t.flows.operating_cash_flow), - ttm_has_estimated_lag: ttm.map(|t| t.has_estimated_lag), - } -} - -fn read_year(out_dir: &Path, year: i32) -> Vec { - read_parquet_rows(&out_dir.join(format!("fundamentals_pit/year={year}/part.parquet"))) -} - -fn list_year_dirs(out_dir: &Path) -> Vec { - let mut names: Vec = fs::read_dir(out_dir.join("fundamentals_pit")) - .expect("read dataset dir") - .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned()) - .filter(|n| n.starts_with("year=")) - .collect(); - names.sort(); - names -} - -/// Deterministic LCG so fixtures are reproducible without an RNG crate. -struct Lcg(u64); - -impl Lcg { - fn next_u32(&mut self) -> u32 { - self.0 = self - .0 - .wrapping_mul(6_364_136_223_846_793_005) - .wrapping_add(1_442_695_040_888_963_407); - (self.0 >> 33) as u32 - } - fn chance(&mut self, pct: u32) -> bool { - self.next_u32() % 100 < pct - } - fn opt(&mut self, pct_null: u32, v: f64) -> Option { - if self.chance(pct_null) { - None - } else { - Some(v) - } - } -} - -#[test] -fn partition_files_contain_exact_expected_row_sequence_per_year() { - let tmp = TempDirGuard::new("qa-partition-exact"); - let ttm = |end: i32, rev: f64| FundamentalsTtm { - ending_period_end: end, - currency: "USD".to_string(), - flows: TtmFlowFields { - revenue: Some(rev), - net_income: None, - operating_cash_flow: Some(rev / 2.0), - }, - has_estimated_lag: false, - }; - let ts_2023_end = utc_micros(2023, 12, 31, 23, 59, 59, 999_999); - let ts_2024_start = utc_micros(2024, 1, 1, 0, 0, 0, 0); - let rows = vec![ - make_row( - 1, - utc_micros(2023, 5, 1, 14, 0, 0, 0), - day(2023, 3, 31), - Some(10.0), - None, - ), - make_row( - 1, - ts_2023_end, - day(2023, 9, 30), - Some(11.0), - Some(ttm(day(2023, 9, 30), 40.0)), - ), - make_row( - 1, - ts_2024_start, - day(2023, 12, 31), - Some(12.0), - Some(ttm(day(2023, 12, 31), 44.0)), - ), - make_row( - 2, - utc_micros(2023, 8, 1, 14, 0, 0, 0), - day(2023, 6, 30), - None, - None, - ), - make_row( - 2, - utc_micros(2024, 2, 1, 14, 0, 0, 0), - day(2023, 12, 31), - Some(21.0), - None, - ), - make_row( - 3, - utc_micros(2023, 11, 1, 14, 0, 0, 0), - day(2023, 9, 30), - Some(30.0), - None, - ), - make_row( - 3, - utc_micros(2024, 5, 1, 14, 0, 0, 0), - day(2024, 3, 31), - Some(31.0), - Some(ttm(day(2024, 3, 31), 120.0)), - ), - ]; - - write_fundamentals_pit_dataset( - tmp.path(), - &rows, - FundamentalsPitWriteOptions { - row_group_rows: 2, - zstd_level: DEFAULT_ZSTD_LEVEL, - }, - ) - .expect("write"); - - let expected_2023: Vec<_> = [0, 1, 3, 5] - .iter() - .map(|&i| expected_decoded(&rows[i])) - .collect(); - let expected_2024: Vec<_> = [2, 4, 6] - .iter() - .map(|&i| expected_decoded(&rows[i])) - .collect(); - assert_eq!(list_year_dirs(tmp.path()), vec!["year=2023", "year=2024"]); - assert_eq!(read_year(tmp.path(), 2023), expected_2023); - assert_eq!(read_year(tmp.path(), 2024), expected_2024); -} - -#[test] -fn seeded_mixed_null_patterns_round_trip_across_many_row_groups() { - let tmp = TempDirGuard::new("qa-seeded"); - let mut rng = Lcg(0x5EED_1430); - let mut rows = Vec::new(); - for listing_id in 1..=9_i32 { - for q in 0..12_i32 { - // One quarter apart; spans 2021..=2023 so multiple partitions get interleaved. - let ts = utc_micros( - 2021 + q / 4, - (q % 4) as u32 * 3 + 2, - 10, - 20, - 30, - 0, - i64::from(listing_id), - ); - let period_end = day(2021 + q / 4, (q % 4) as u32 * 3 + 1, 1); - let base = f64::from(listing_id * 1000 + q); - let estimated = rng.chance(30); - let currency = if rng.chance(20) { "CAD" } else { "USD" }; - let ttm = if rng.chance(40) { - None - } else { - Some(FundamentalsTtm { - ending_period_end: period_end, - currency: currency.to_string(), - flows: TtmFlowFields { - revenue: rng.opt(25, base * 4.0), - net_income: rng.opt(25, -base * 0.25), - operating_cash_flow: rng.opt(25, 0.0), - }, - has_estimated_lag: rng.chance(50), - }) - }; - rows.push(FundamentalsPitParquetRow::new( - listing_id, - ts, - Cow::Borrowed(if estimated { - KNOWN_AT_SOURCE_STATUTORY_LAG - } else { - KNOWN_AT_SOURCE_FILING_TIMESTAMP - }), - estimated, - FundamentalsPitLatestPeriod { - period_end, - fiscal_period: Cow::Borrowed(if q % 4 == 3 { "FY" } else { "Q" }), - currency: currency.to_string(), - period_known_at_micros: ts - 1, - fields: FundamentalsFields { - revenue: rng.opt(20, base), - net_income: rng.opt(20, -base / 10.0), - operating_cash_flow: rng.opt(20, base / 7.0), - total_assets: rng.opt(20, base * 5.0), - total_equity: rng.opt(20, base * 2.0), - shares_outstanding: rng.opt(20, 1.0e9), - }, - }, - ttm, - )); - } - } - // Sanity: the fixture really exercises all-null and all-present TTM in the same file. - assert!(rows.iter().any(|r| r.ttm.is_none())); - assert!(rows - .iter() - .any(|r| r.ttm.as_ref().is_some_and(|t| t.flows.revenue.is_none()))); - - let stats = write_fundamentals_pit_dataset( - tmp.path(), - &rows, - FundamentalsPitWriteOptions { - row_group_rows: 5, - zstd_level: 1, - }, - ) - .expect("write seeded dataset"); - assert_eq!(stats.rows_written, rows.len()); - assert_eq!( - stats.rows_by_year, - BTreeMap::from([(2021, 36), (2022, 36), (2023, 36)]) - ); - // 36 rows per year at 5 rows per group -> 8 groups per year. - assert_eq!(stats.row_groups_written, 24); - - for year in 2021..=2023 { - let expected: Vec<_> = rows - .iter() - .filter(|r| partition_year_utc(r.effective_known_at_micros) == year) - .map(expected_decoded) - .collect(); - assert_eq!(read_year(tmp.path(), year), expected, "year {year}"); - } - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); -} - -#[test] -fn builder_statutory_lag_snapshots_keep_estimated_provenance_on_disk() { - // Listing 7 (TSXV/CSE venue) files Q1 via a 10-Q; Q2 has no filing and no report date, - // so its known_at falls back to period_end + 60d at 16:05 America/Toronto. - let listing_id = 7_i32; - let venues = BTreeMap::from([(listing_id, StatutoryLagVenue::TsxvCse)]); - let p_q1 = day(2024, 3, 31); - let p_q2 = day(2024, 6, 30); - let fields = |rev: f64| FundamentalsFields { - revenue: Some(rev), - net_income: Some(rev / 10.0), - operating_cash_flow: None, - total_assets: Some(900.0), - total_equity: Some(400.0), - shares_outstanding: Some(50.0), - }; - let observations = vec![ - obs( - listing_id, - p_q1, - FiscalPeriod::Quarterly, - "CAD", - None, - fields(100.0), - ), - obs( - listing_id, - p_q2, - FiscalPeriod::Quarterly, - "CAD", - None, - fields(130.0), - ), - ]; - let filings = vec![filing(listing_id, "2024-05-10T16:30:00 EDT", "10-Q")]; - - let build = build_fundamentals_rows(observations, filings, &venues); - let snaps = build_fundamentals_snapshots(&build.rows, 4).expect("snapshots"); - assert_eq!(snaps.len(), 2); - let rows: Vec = - snaps.iter().map(FundamentalsPitParquetRow::from).collect(); - - let tmp = TempDirGuard::new("qa-estimated"); - write_fundamentals_pit_dataset(tmp.path(), &rows, FundamentalsPitWriteOptions::default()) - .expect("write"); - let decoded = read_year(tmp.path(), 2024); - assert_eq!( - decoded, - rows.iter().map(expected_decoded).collect::>() - ); - - // Q1: filing-backed, at the 10-Q's UTC timestamp. - let ts_q1 = utc_micros(2024, 5, 10, 20, 30, 0, 0); - assert_eq!(decoded[0].effective_known_at, ts_q1); - assert_eq!(decoded[0].known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); - assert!(!decoded[0].has_estimated_lag); - assert_eq!(decoded[0].period_end, p_q1); - assert_eq!(decoded[0].period_known_at, ts_q1); - assert_eq!(decoded[0].currency, "CAD"); - - // Q2: estimated, 2024-06-30 + 60d = 2024-08-29 16:05 EDT = 20:05 UTC. - let ts_q2_est = utc_micros(2024, 8, 29, 20, 5, 0, 0); - assert_eq!(decoded[1].effective_known_at, ts_q2_est); - assert_eq!(decoded[1].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); - assert!(decoded[1].has_estimated_lag); - assert_eq!(decoded[1].period_end, p_q2); - assert_eq!(decoded[1].period_known_at, ts_q2_est); - assert_eq!(decoded[1].revenue, Some(130.0)); - assert_eq!(decoded[1].operating_cash_flow, None); - // Only two quarters exist, so TTM is unavailable and every ttm_* column is null. - for r in &decoded { - assert_eq!(r.ttm_period_end, None); - assert_eq!(r.ttm_currency, None); - assert_eq!(r.ttm_revenue, None); - assert_eq!(r.ttm_net_income, None); - assert_eq!(r.ttm_operating_cash_flow, None); - assert_eq!(r.ttm_has_estimated_lag, None); - } -} - -#[test] -fn rewrite_replaces_only_years_present_in_new_input() { - let tmp = TempDirGuard::new("qa-rewrite"); - let first = vec![ - make_row( - 1, - utc_micros(2023, 5, 1, 14, 0, 0, 0), - day(2023, 3, 31), - Some(10.0), - None, - ), - make_row( - 1, - utc_micros(2024, 5, 1, 14, 0, 0, 0), - day(2024, 3, 31), - Some(20.0), - None, - ), - ]; - write_fundamentals_pit_dataset(tmp.path(), &first, FundamentalsPitWriteOptions::default()) - .expect("first write"); - let part_2023 = tmp.path().join("fundamentals_pit/year=2023/part.parquet"); - let bytes_2023 = fs::read(&part_2023).expect("read 2023"); - - let second = vec![ - make_row( - 5, - utc_micros(2024, 2, 1, 14, 0, 0, 0), - day(2023, 12, 31), - Some(55.0), - None, - ), - make_row( - 5, - utc_micros(2024, 6, 1, 14, 0, 0, 0), - day(2024, 3, 31), - Some(56.0), - None, - ), - ]; - let stats = - write_fundamentals_pit_dataset(tmp.path(), &second, FundamentalsPitWriteOptions::default()) - .expect("second write"); - assert_eq!(stats.rows_by_year, BTreeMap::from([(2024, 2)])); - - // 2024 is fully replaced (no merge with old rows); 2023 is untouched byte for byte. - assert_eq!( - read_year(tmp.path(), 2024), - second.iter().map(expected_decoded).collect::>() - ); - assert_eq!(fs::read(&part_2023).expect("reread 2023"), bytes_2023); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); -} - -#[test] -fn identical_input_produces_byte_identical_partitions() { - let rows = vec![ - make_row( - 1, - utc_micros(2023, 5, 1, 14, 0, 0, 0), - day(2023, 3, 31), - Some(10.0), - None, - ), - make_row( - 2, - utc_micros(2024, 5, 1, 14, 0, 0, 0), - day(2024, 3, 31), - None, - None, - ), - ]; - let a = TempDirGuard::new("qa-determinism-a"); - let b = TempDirGuard::new("qa-determinism-b"); - let opts = FundamentalsPitWriteOptions { - row_group_rows: 1, - zstd_level: DEFAULT_ZSTD_LEVEL, - }; - write_fundamentals_pit_dataset(a.path(), &rows, opts).expect("write a"); - write_fundamentals_pit_dataset(b.path(), &rows, opts).expect("write b"); - for year in [2023, 2024] { - let rel = format!("fundamentals_pit/year={year}/part.parquet"); - assert_eq!( - fs::read(a.path().join(&rel)).expect("read a"), - fs::read(b.path().join(&rel)).expect("read b"), - "year {year} bytes differ between identical runs" - ); - } -} - -#[test] -fn remaining_validation_errors_are_typed_and_publish_nothing() { - let ts = utc_micros(2024, 5, 1, 20, 0, 0, 0); - let valid = make_row(1, ts - 1, day(2024, 3, 31), Some(1.0), None); - let defaults = FundamentalsPitWriteOptions::default(); - - let run = |label: &str, bad: FundamentalsPitParquetRow, opts: FundamentalsPitWriteOptions| { - let tmp = TempDirGuard::new(label); - let err = write_fundamentals_pit_dataset(tmp.path(), [valid.clone(), bad], opts) - .expect_err("invalid input must fail"); - let year_dir = tmp.path().join("fundamentals_pit/year=2024"); - assert!( - !year_dir.join("part.parquet").exists(), - "{label}: partial file published" - ); - assert_no_transient_files(&tmp.path().join("fundamentals_pit")); - err - }; - - let mut nan_row = make_row(1, ts, day(2024, 3, 31), Some(f64::NAN), None); - nan_row.has_estimated_lag = true; - let err = run("qa-nan", nan_row, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::NonFiniteValue { - row_index: 1, - field: "revenue", - .. - } - ), - "got {err:?}" - ); - - let inf_ttm = make_row( - 1, - ts, - day(2024, 3, 31), - Some(1.0), - Some(FundamentalsTtm { - ending_period_end: day(2024, 3, 31), - currency: "USD".to_string(), - flows: TtmFlowFields { - revenue: Some(1.0), - net_income: None, - operating_cash_flow: Some(f64::INFINITY), - }, - has_estimated_lag: false, - }), - ); - let err = run("qa-inf-ttm", inf_ttm, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::NonFiniteValue { - field: "ttm_operating_cash_flow", - .. - } - ), - "got {err:?}" - ); - - let mut blank_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); - blank_source.known_at_source = Cow::Borrowed(" "); - let err = run("qa-blank-source", blank_source, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::EmptyKnownAtSource { row_index: 1, .. } - ), - "got {err:?}" - ); - - let mut invalid_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); - invalid_source.known_at_source = Cow::Borrowed("manual_override"); - let err = run("qa-invalid-source", invalid_source, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::InvalidKnownAtSource { - row_index: 1, - ref value, - .. - } if value == "manual_override" - ), - "got {err:?}" - ); - - let mut padded_source = make_row(1, ts, day(2024, 3, 31), Some(1.0), None); - padded_source.known_at_source = Cow::Borrowed(" filing_timestamp "); - let err = run("qa-padded-source", padded_source, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::InvalidKnownAtSource { - row_index: 1, - ref value, - .. - } if value == " filing_timestamp " - ), - "got {err:?}" - ); - - let blank_ttm_currency = make_row( - 1, - ts, - day(2024, 3, 31), - Some(1.0), - Some(FundamentalsTtm { - ending_period_end: day(2024, 3, 31), - currency: String::new(), - flows: TtmFlowFields { - revenue: None, - net_income: None, - operating_cash_flow: None, - }, - has_estimated_lag: false, - }), - ); - let err = run("qa-blank-ttm-ccy", blank_ttm_currency, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::EmptyTtmCurrency { row_index: 1, .. } - ), - "got {err:?}" - ); - - let blank_currency = FundamentalsPitParquetRow::new( - 1, - ts, - Cow::Borrowed(KNOWN_AT_SOURCE_FILING_TIMESTAMP), - false, - FundamentalsPitLatestPeriod { - period_end: day(2024, 3, 31), - fiscal_period: Cow::Borrowed("Q"), - currency: String::new(), - period_known_at_micros: ts, - fields: FundamentalsFields { - revenue: None, - net_income: None, - operating_cash_flow: None, - total_assets: None, - total_equity: None, - shares_outstanding: None, - }, - }, - None, - ); - let err = run("qa-blank-ccy", blank_currency, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::EmptyCurrency { row_index: 1, .. } - ), - "got {err:?}" - ); - - // Year 2201 is above MAX_PARQUET_YEAR (2200). - let far_future = make_row( - 1, - utc_micros(2201, 1, 1, 0, 0, 0, 0), - day(2024, 3, 31), - Some(1.0), - None, - ); - let err = run("qa-year-range", far_future, defaults); - assert!( - matches!( - err, - ParquetFundamentalsError::PartitionYearOutOfRange { - row_index: 1, - year: 2201, - .. - } - ), - "got {err:?}" - ); - - // Option validation happens before any filesystem side effects. - let tmp = TempDirGuard::new("qa-bad-options"); - let err = write_fundamentals_pit_dataset( - tmp.path(), - [valid.clone()], - FundamentalsPitWriteOptions { - row_group_rows: 0, - zstd_level: DEFAULT_ZSTD_LEVEL, - }, - ) - .unwrap_err(); - assert!( - matches!(err, ParquetFundamentalsError::InvalidRowGroupRows), - "got {err:?}" - ); - let err = write_fundamentals_pit_dataset( - tmp.path(), - [valid], - FundamentalsPitWriteOptions { - row_group_rows: 1, - zstd_level: 99, - }, - ) - .unwrap_err(); - assert!( - matches!( - err, - ParquetFundamentalsError::InvalidZstdLevel { level: 99 } - ), - "got {err:?}" - ); - assert!(!tmp.path().join("fundamentals_pit").exists()); -} diff --git a/tools/curate-etl/src/parquet_publish.rs b/tools/curate-etl/src/parquet_publish.rs index 00d6f1a4..fd9b89c2 100644 --- a/tools/curate-etl/src/parquet_publish.rs +++ b/tools/curate-etl/src/parquet_publish.rs @@ -363,25 +363,6 @@ fn next_column<'a>( } } -pub(crate) fn write_bool_col( - rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, - values: &[bool], - def_levels: Option<&[i16]>, -) -> Result<(), ParquetError> { - let mut col = next_column(rg_writer)?; - match col.untyped() { - ColumnWriter::BoolColumnWriter(typed) => { - typed.write_batch(values, def_levels, None)?; - } - _ => { - return Err(ParquetError::General( - "expected BOOLEAN column writer".to_string(), - )); - } - } - col.close() -} - pub(crate) fn write_i32_col( rg_writer: &mut SerializedRowGroupWriter<'_, BufWriter>, values: &[i32], diff --git a/tools/curate-etl/src/posts.rs b/tools/curate-etl/src/posts.rs deleted file mode 100644 index 3769fcf8..00000000 --- a/tools/curate-etl/src/posts.rs +++ /dev/null @@ -1,248 +0,0 @@ -//! Pure, in-memory `posts` builder for `ceoPosts` (`bot == "1"` newswire vs. retail split, -//! `edited` text point-in-time `known_at` guard, and deterministic global `spielId` deduplication). -//! -//! Aligned with `design/DATA-CONTRACTS.md` §1 (`ceoSymbols`, `ceoPosts`, `ceoShorts` row): -//! - Separates `bot == "1"` newswire posts (e.g. `@thenewswire`) from retail posts so wire -//! releases are never pooled with crowd chat. -//! - Computes text availability as `known_at = COALESCE(edited, timestamp)` in UTC microseconds, -//! clamped so `known_at >= posted_at` always holds. -//! - **Point-in-time rule:** any text-based feature or sentiment model MUST join on `known_at`, -//! never `posted_at`. In `ceoPosts`, an edit overwrites `spiel` in place without version -//! history, so the builder retains one supplied version per `spiel_id` and cannot recover -//! earlier pre-edit text. - -use std::error::Error; -use std::fmt; - -/// Canonical provenance label written to [`PostRow::source`]. -pub const POSTS_SOURCE_CEO: &str = "ceo_posts"; - -/// Typed errors returned by [`build_posts`]. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum PostsError { - /// Converting a millisecond timestamp (`timestamp_ms` or `edited_ms`) to UTC microseconds - /// overflowed `i64`. - TimestampOverflow { - spiel_id: String, - field: &'static str, - timestamp_ms: i64, - }, -} - -impl fmt::Display for PostsError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::TimestampOverflow { - spiel_id, - field, - timestamp_ms, - } => write!( - f, - "timestamp overflow converting {field}={timestamp_ms} ms to UTC microseconds for spiel_id '{spiel_id}'" - ), - } - } -} - -impl Error for PostsError {} - -/// A single already-decoded `ceoPosts` input row. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct CeoPost { - /// Channel / `ceoId` (or resolved listing key). - pub key: K, - /// Provider post identifier (`spielId`, MongoDB upsert key). - pub spiel_id: String, - /// Provider post creation time in epoch milliseconds (`timestamp`). - pub timestamp_ms: i64, - /// Optional provider last-edit time in epoch milliseconds (`edited`). - pub edited_ms: Option, - /// Raw provider bot flag (`bot`; only `"1"` after trim classifies as newswire). - pub bot: Option, - /// Optional provider author identifier (`userId`). - pub user_id: Option, - /// Post text (`spiel`). - pub text: String, -} - -/// A single curated `ceoPosts` output row. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PostRow { - pub key: K, - pub spiel_id: String, - /// Post creation timestamp in UTC microseconds (`timestamp_ms * 1_000`). - pub posted_at: i64, - /// Point-in-time text availability timestamp in UTC microseconds (`max(posted_at, edited_at)`). - /// Downstream text features MUST join on `known_at`, never `posted_at`. - pub known_at: i64, - pub is_bot: bool, - pub is_edited: bool, - pub user_id: Option, - pub text: String, - pub source: &'static str, -} - -/// Summary accounting counters produced alongside [`PostsBuild::newswire`] and -/// [`PostsBuild::retail`]. -/// -/// Conservation invariant: -/// `input == newswire + retail + duplicates_dropped + rejected_invalid` -/// -/// Accounting note: `edited` and `edited_before_posted` are counted on valid input rows before -/// `spiel_id` deduplication (so they include valid duplicates and exclude `rejected_invalid`). -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct PostsStats { - pub input: usize, - pub newswire: usize, - pub retail: usize, - pub edited: usize, - pub edited_before_posted: usize, - pub duplicates_dropped: usize, - pub rejected_invalid: usize, -} - -/// Output of [`build_posts`]: disjoint, deterministically sorted `newswire` and `retail` streams -/// plus exact accounting stats. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct PostsBuild { - pub newswire: Vec>, - pub retail: Vec>, - pub stats: PostsStats, -} - -/// Builds disjoint, deterministically sorted `newswire` and `retail` post streams from raw -/// `ceoPosts` inputs. -/// -/// Rules: -/// - Rejects (counts in [`PostsStats::rejected_invalid`] without aborting) rows with an empty -/// `spiel_id` or `timestamp_ms <= 0` before timestamp conversion. -/// - Classifies `is_bot` as `true` iff `bot` is `"1"` after trimming whitespace; all other values -/// (`None`, `"0"`, `""`, etc.) route to `retail`. -/// - Sets `is_edited = edited_ms.is_some()`, counts valid edited rows in [`PostsStats::edited`], -/// and guards against look-ahead / clock-skew edits earlier than posting (`edited_ms < -/// timestamp_ms`) by clamping `known_at` to `posted_at` and incrementing -/// [`PostsStats::edited_before_posted`]. Both edit counters are recorded on valid rows prior to -/// deduplication. -/// - Converts `timestamp_ms` and the selected `known_at` millisecond value to UTC microseconds via -/// `checked_mul(1_000)`, returning [`PostsError::TimestampOverflow`] on overflow. -/// - Deduplicates globally on `spiel_id` before splitting into `newswire` and `retail` (keeping -/// one supplied version per `spiel_id`; earlier pre-edit versions cannot be recovered). Within a -/// `spiel_id` group, the survivor is the row with the greatest `known_at`, breaking ties -/// deterministically by the maximum lexicographic tuple -/// `(posted_at, is_edited, is_bot, key, user_id, text)` (`None < Some` for `user_id`), with zero -/// dependence on input order. All other `group_len - 1` rows are counted in -/// [`PostsStats::duplicates_dropped`]. -/// - Sorts both `newswire` and `retail` strictly ascending by `(key, known_at, spiel_id)`. -/// - Any permutation of `rows` produces identical `newswire`, `retail`, and `stats`. -pub fn build_posts(rows: I) -> Result, PostsError> -where - K: Ord + Clone, - I: IntoIterator>, -{ - let iter = rows.into_iter(); - let (lower, _) = iter.size_hint(); - let mut stats = PostsStats::default(); - let mut normalized: Vec> = Vec::with_capacity(lower); - - for row in iter { - stats.input += 1; - - if row.spiel_id.is_empty() || row.timestamp_ms <= 0 { - stats.rejected_invalid += 1; - continue; - } - - let is_bot = row.bot.as_deref().map(str::trim) == Some("1"); - let is_edited = row.edited_ms.is_some(); - - let known_at_ms = match row.edited_ms { - Some(edited_ms) => { - stats.edited += 1; - if edited_ms < row.timestamp_ms { - stats.edited_before_posted += 1; - row.timestamp_ms - } else { - edited_ms - } - } - None => row.timestamp_ms, - }; - - let posted_at = - row.timestamp_ms - .checked_mul(1_000) - .ok_or_else(|| PostsError::TimestampOverflow { - spiel_id: row.spiel_id.clone(), - field: "timestamp_ms", - timestamp_ms: row.timestamp_ms, - })?; - - let known_at = if known_at_ms == row.timestamp_ms { - posted_at - } else { - known_at_ms - .checked_mul(1_000) - .ok_or_else(|| PostsError::TimestampOverflow { - spiel_id: row.spiel_id.clone(), - field: "edited_ms", - timestamp_ms: known_at_ms, - })? - }; - - normalized.push(PostRow { - key: row.key, - spiel_id: row.spiel_id, - posted_at, - known_at, - is_bot, - is_edited, - user_id: row.user_id, - text: row.text, - source: POSTS_SOURCE_CEO, - }); - } - - normalized.sort_unstable_by(|a, b| { - a.spiel_id - .cmp(&b.spiel_id) - .then_with(|| b.known_at.cmp(&a.known_at)) - .then_with(|| b.posted_at.cmp(&a.posted_at)) - .then_with(|| b.is_edited.cmp(&a.is_edited)) - .then_with(|| b.is_bot.cmp(&a.is_bot)) - .then_with(|| b.key.cmp(&a.key)) - .then_with(|| b.user_id.cmp(&a.user_id)) - .then_with(|| b.text.cmp(&a.text)) - }); - - let before_dedup = normalized.len(); - normalized.dedup_by(|a, b| a.spiel_id == b.spiel_id); - stats.duplicates_dropped = before_dedup - normalized.len(); - - let mut newswire: Vec> = Vec::new(); - let mut retail: Vec> = Vec::new(); - for row in normalized { - if row.is_bot { - newswire.push(row); - } else { - retail.push(row); - } - } - - let output_order = |a: &PostRow, b: &PostRow| { - a.key - .cmp(&b.key) - .then_with(|| a.known_at.cmp(&b.known_at)) - .then_with(|| a.spiel_id.cmp(&b.spiel_id)) - }; - newswire.sort_unstable_by(output_order); - retail.sort_unstable_by(output_order); - - stats.newswire = newswire.len(); - stats.retail = retail.len(); - - Ok(PostsBuild { - newswire, - retail, - stats, - }) -} diff --git a/tools/curate-etl/src/posts_tests.rs b/tools/curate-etl/src/posts_tests.rs deleted file mode 100644 index 53f0f91d..00000000 --- a/tools/curate-etl/src/posts_tests.rs +++ /dev/null @@ -1,988 +0,0 @@ -use std::collections::HashSet; - -use crate::posts::{ - build_posts, CeoPost, PostRow, PostsBuild, PostsError, PostsStats, POSTS_SOURCE_CEO, -}; - -fn post( - key: &str, - spiel_id: &str, - timestamp_ms: i64, - edited_ms: Option, - bot: Option<&str>, - user_id: Option<&str>, - text: &str, -) -> CeoPost { - CeoPost { - key: key.to_string(), - spiel_id: spiel_id.to_string(), - timestamp_ms, - edited_ms, - bot: bot.map(str::to_string), - user_id: user_id.map(str::to_string), - text: text.to_string(), - } -} - -fn assert_invariants(build: &PostsBuild) { - let s = &build.stats; - assert_eq!( - s.input, - s.newswire + s.retail + s.duplicates_dropped + s.rejected_invalid, - "accounting invariant failed: {s:?}" - ); - assert_eq!(s.newswire, build.newswire.len()); - assert_eq!(s.retail, build.retail.len()); - assert!(s.edited_before_posted <= s.edited); - - let mut seen_ids = HashSet::with_capacity(s.newswire + s.retail); - for (stream_name, rows, expected_bot) in [ - ("newswire", &build.newswire, true), - ("retail", &build.retail, false), - ] { - for pair in rows.windows(2) { - assert!( - (&pair[0].key, pair[0].known_at, &pair[0].spiel_id) - < (&pair[1].key, pair[1].known_at, &pair[1].spiel_id), - "{stream_name} must be strictly sorted by (key, known_at, spiel_id)" - ); - } - for row in rows { - assert_eq!(row.is_bot, expected_bot); - assert_eq!(row.source, POSTS_SOURCE_CEO); - assert!( - row.known_at >= row.posted_at, - "look-ahead violation in {stream_name}: known_at {} < posted_at {}", - row.known_at, - row.posted_at - ); - assert!( - seen_ids.insert(row.spiel_id.as_str()), - "spiel_id '{}' appeared more than once across streams", - row.spiel_id - ); - } - } -} - -/// Deterministic SplitMix64 PRNG for fixture generation and shuffles. -struct SplitMix64(u64); - -impl SplitMix64 { - 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 shuffle(&mut self, slice: &mut [T]) { - for i in (1..slice.len()).rev() { - let j = (self.next_u64() as usize) % (i + 1); - slice.swap(i, j); - } - } -} - -/// Generates all permutations of `items` via Heap's algorithm. -fn all_permutations(items: &[T]) -> Vec> { - let mut out = Vec::new(); - let mut arr = items.to_vec(); - let n = arr.len(); - let mut c = vec![0usize; n]; - out.push(arr.clone()); - - let mut i = 0; - while i < n { - if c[i] < i { - if i % 2 == 0 { - arr.swap(0, i); - } else { - arr.swap(c[i], i); - } - out.push(arr.clone()); - c[i] += 1; - i = 0; - } else { - c[i] = 0; - i += 1; - } - } - out -} - -#[test] -fn bot_split_routes_only_trimmed_one_to_newswire_and_preserves_fields() { - let input = vec![ - post( - "chan_a", - "sp_bot_exact", - 1_700_000_000_000, - None, - Some("1"), - Some("wire_user"), - "News release headline", - ), - post( - "chan_b", - "sp_bot_trimmed", - 1_700_000_001_000, - None, - Some(" 1 "), - None, - "Trimmed bot flag release", - ), - post( - "chan_a", - "sp_retail_zero", - 1_700_000_002_000, - None, - Some("0"), - Some("u1"), - "Retail zero flag", - ), - post( - "chan_a", - "sp_retail_empty", - 1_700_000_003_000, - None, - Some(""), - Some("u2"), - "Retail empty flag", - ), - post( - "chan_b", - "sp_retail_none", - 1_700_000_004_000, - None, - None, - None, - "Retail missing flag", - ), - post( - "chan_b", - "sp_retail_other", - 1_700_000_005_000, - None, - Some("true"), - Some("u3"), - "Non-1 string is retail", - ), - ]; - - let built = build_posts(input).expect("valid posts should build"); - assert_invariants(&built); - - assert_eq!( - built.stats, - PostsStats { - input: 6, - newswire: 2, - retail: 4, - edited: 0, - edited_before_posted: 0, - duplicates_dropped: 0, - rejected_invalid: 0, - } - ); - - assert_eq!( - built.newswire, - vec![ - PostRow { - key: "chan_a".to_string(), - spiel_id: "sp_bot_exact".to_string(), - posted_at: 1_700_000_000_000_000, - known_at: 1_700_000_000_000_000, - is_bot: true, - is_edited: false, - user_id: Some("wire_user".to_string()), - text: "News release headline".to_string(), - source: POSTS_SOURCE_CEO, - }, - PostRow { - key: "chan_b".to_string(), - spiel_id: "sp_bot_trimmed".to_string(), - posted_at: 1_700_000_001_000_000, - known_at: 1_700_000_001_000_000, - is_bot: true, - is_edited: false, - user_id: None, - text: "Trimmed bot flag release".to_string(), - source: POSTS_SOURCE_CEO, - }, - ] - ); - - let retail_ids: Vec<&str> = built.retail.iter().map(|r| r.spiel_id.as_str()).collect(); - assert_eq!( - retail_ids, - vec![ - "sp_retail_zero", - "sp_retail_empty", - "sp_retail_none", - "sp_retail_other" - ] - ); - assert_eq!(built.retail[0].user_id.as_deref(), Some("u1")); - assert_eq!(built.retail[0].text, "Retail zero flag"); - assert_eq!(built.retail[2].user_id, None); - assert_eq!(built.retail[2].source, POSTS_SOURCE_CEO); -} - -#[test] -fn edited_timestamps_guard_known_at_and_availability_cutoff() { - let t_post = 1_710_000_000_000_i64; - let t_edit_later = t_post + 720_000; // +12 minutes - let t_edit_earlier = t_post - 5_000; // -5 seconds (clock skew) - - let input = vec![ - post( - "TSX:ABC", - "sp_unedited", - t_post, - None, - None, - Some("u1"), - "Unedited baseline", - ), - post( - "TSX:ABC", - "sp_edited_equal", - t_post, - Some(t_post), - None, - Some("u2"), - "Edited at exact post ms", - ), - post( - "TSX:ABC", - "sp_edited_later", - t_post, - Some(t_edit_later), - None, - Some("u3"), - "Rewritten after move", - ), - post( - "TSX:ABC", - "sp_edited_earlier", - t_post, - Some(t_edit_earlier), - None, - Some("u4"), - "Skewed edit timestamp", - ), - ]; - - let built = build_posts(input).expect("valid posts should build"); - assert_invariants(&built); - - assert_eq!(built.stats.edited, 3); - assert_eq!(built.stats.edited_before_posted, 1); - - let by_id = |id: &str| { - built - .retail - .iter() - .find(|r| r.spiel_id == id) - .expect("expected row in retail") - }; - - let unedited = by_id("sp_unedited"); - assert_eq!(unedited.posted_at, t_post * 1_000); - assert_eq!(unedited.known_at, t_post * 1_000); - assert!(!unedited.is_edited); - - let equal = by_id("sp_edited_equal"); - assert_eq!(equal.posted_at, t_post * 1_000); - assert_eq!(equal.known_at, t_post * 1_000); - assert!(equal.is_edited); - - let later = by_id("sp_edited_later"); - assert_eq!(later.posted_at, t_post * 1_000); - assert_eq!(later.known_at, t_edit_later * 1_000); - assert!(later.is_edited); - - // Point-in-time availability check: at a cutoff strictly between posted_at and edited_at, - // the unedited post is visible (known_at < cutoff) while the edited post is NOT yet visible. - let cutoff = (t_post + 300_000) * 1_000; // +5 minutes after post - assert!(unedited.known_at < cutoff); - assert!(later.posted_at < cutoff); - assert!(later.known_at > cutoff); - - let earlier = by_id("sp_edited_earlier"); - assert_eq!(earlier.posted_at, t_post * 1_000); - assert_eq!(earlier.known_at, t_post * 1_000); - assert!(earlier.is_edited); -} - -#[test] -fn generated_fixture_preserves_known_at_ge_posted_at_and_edit_accounting() { - let mut rng = SplitMix64(0x5eed_cafe_1234_5678); - let mut input = Vec::with_capacity(220); - let mut expected_edited = 0usize; - let mut expected_edited_before_posted = 0usize; - let mut expected_rejected = 0usize; - - // 200 valid rows (including intentional duplicate spiel_ids across 120 buckets). - for i in 0..200usize { - let key = format!("CH_{:02}", rng.next_u64() % 10); - let spiel_id = format!("sp_{:03}", rng.next_u64() % 120); - let timestamp_ms = 1_700_000_000_000 + (rng.next_u64() % 10_000_000) as i64; - let edit_mode = rng.next_u64() % 4; - let edited_ms = match edit_mode { - 0 => None, - 1 => { - expected_edited += 1; - Some(timestamp_ms + (rng.next_u64() % 900_000) as i64 + 1) - } - 2 => { - expected_edited += 1; - expected_edited_before_posted += 1; - Some(timestamp_ms - (rng.next_u64() % 60_000) as i64 - 1) - } - _ => { - expected_edited += 1; - Some(timestamp_ms) - } - }; - let bot = match rng.next_u64() % 5 { - 0 => Some("1"), - 1 => Some(" 1 "), - 2 => Some("0"), - 3 => Some(""), - _ => None, - }; - input.push(post( - &key, - &spiel_id, - timestamp_ms, - edited_ms, - bot, - Some(&format!("u{}", i % 17)), - &format!("generated post {i}"), - )); - } - - // 20 rejected rows (some carrying edited_ms that must NOT count toward edited stats). - for i in 0..20usize { - expected_rejected += 1; - if i % 2 == 0 { - input.push(post( - "CH_BAD", - "", - 1_700_000_000_000, - Some(1_699_999_999_000), - Some("1"), - None, - "empty id", - )); - } else { - input.push(post( - "CH_BAD", - &format!("bad_ts_{i}"), - -(i as i64), - Some(-(i as i64) - 100), - None, - None, - "non-positive ts", - )); - } - } - - let built = build_posts(input).expect("generated fixture should build"); - assert_invariants(&built); - assert_eq!(built.stats.input, 220); - assert_eq!(built.stats.rejected_invalid, expected_rejected); - assert_eq!(built.stats.edited, expected_edited); - assert_eq!( - built.stats.edited_before_posted, - expected_edited_before_posted - ); - assert!(built.stats.duplicates_dropped > 0); -} - -#[test] -fn dedup_keeps_greatest_known_at_globally_across_channels_and_streams() { - let base_ms = 1_720_000_000_000_i64; - let input = vec![ - post( - "chan_a", - "shared_id", - base_ms, - None, - Some("1"), - Some("wire"), - "v1 newswire", - ), - post( - "chan_b", - "shared_id", - base_ms, - Some(base_ms + 120_000), - Some("0"), - Some("retail_u"), - "v2 edited later in another channel/stream", - ), - post( - "chan_c", - "shared_id", - base_ms + 60_000, - None, - Some("1"), - Some("wire"), - "v1.5 intermediate known_at", - ), - ]; - - let built = build_posts(input).expect("valid posts should build"); - assert_invariants(&built); - - assert_eq!(built.stats.input, 3); - assert_eq!(built.stats.newswire, 0); - assert_eq!(built.stats.retail, 1); - assert_eq!(built.stats.duplicates_dropped, 2); - assert_eq!(built.retail[0].key, "chan_b"); - assert_eq!(built.retail[0].known_at, (base_ms + 120_000) * 1_000); - assert_eq!( - built.retail[0].text, - "v2 edited later in another channel/stream" - ); -} - -fn conflicting_tie_group() -> Vec> { - let t = 1_725_000_000_000_i64; - vec![ - // Same spiel_id & same known_at = t * 1_000, differing in text and bot flag. - post( - "chan_m", - "tie_spiel", - t, - None, - Some("0"), - Some("u_b"), - "alpha text", - ), - post( - "chan_m", - "tie_spiel", - t, - None, - Some("0"), - Some("u_b"), - "zeta text", - ), - // is_bot = true beats is_bot = false on same (known_at, posted_at, is_edited). - post( - "chan_m", - "tie_spiel", - t, - None, - Some("1"), - Some("u_a"), - "bot winner text", - ), - // is_edited = true beats is_edited = false on same (known_at, posted_at), even with bot="0". - post( - "chan_a", - "tie_spiel", - t, - Some(t), - Some("0"), - None, - "edited winner text", - ), - ] -} - -#[test] -fn dedup_conflicting_known_at_ties_pick_exact_tuple_winner_across_all_permutations() { - let group = conflicting_tie_group(); - let expected_drops = group.len() - 1; - let perms = all_permutations(&group); - assert_eq!(perms.len(), 24); - - let baseline = build_posts(group).expect("tie group should build"); - assert_invariants(&baseline); - assert_eq!(baseline.stats.duplicates_dropped, expected_drops); - assert_eq!(baseline.newswire.len(), 0); - assert_eq!(baseline.retail.len(), 1); - assert_eq!(baseline.retail[0].text, "edited winner text"); - assert!(baseline.retail[0].is_edited); - assert!(!baseline.retail[0].is_bot); - - for perm in perms { - let built = build_posts(perm).expect("permutation should build"); - assert_eq!(built, baseline); - } - - // Also verify each individual tie-break field in exact precedence order: - // (posted_at, is_edited, is_bot, key, user_id [None < Some], text). - let t = 1_725_000_100_000_i64; - // 1. posted_at beats is_edited - let b1 = build_posts(vec![ - post( - "z", - "tb1", - t - 1_000, - Some(t), - Some("1"), - Some("z"), - "earlier post edited to t", - ), - post( - "a", - "tb1", - t, - None, - Some("0"), - None, - "later posted_at wins", - ), - ]) - .unwrap(); - assert_eq!(b1.retail[0].text, "later posted_at wins"); - - // 2. is_bot beats key - let b2 = build_posts(vec![ - post("zzz", "tb2", t, None, Some("0"), Some("z"), "retail"), - post("aaa", "tb2", t, None, Some("1"), None, "bot wins"), - ]) - .unwrap(); - assert_eq!(b2.newswire[0].text, "bot wins"); - - // 3. key beats user_id - let b3 = build_posts(vec![ - post("chan_a", "tb3", t, None, Some("0"), Some("zzz"), "low key"), - post("chan_z", "tb3", t, None, Some("0"), None, "high key wins"), - ]) - .unwrap(); - assert_eq!(b3.retail[0].text, "high key wins"); - - // 4. user_id (None < Some) beats text - let b4 = build_posts(vec![ - post("chan_a", "tb4", t, None, Some("0"), None, "zzz text"), - post( - "chan_a", - "tb4", - t, - None, - Some("0"), - Some("a"), - "some user_id wins", - ), - ]) - .unwrap(); - assert_eq!(b4.retail[0].text, "some user_id wins"); - - // 5. text breaks final tie - let b5 = build_posts(vec![ - post("chan_a", "tb5", t, None, Some("0"), Some("u1"), "alpha"), - post("chan_a", "tb5", t, None, Some("0"), Some("u1"), "omega"), - ]) - .unwrap(); - assert_eq!(b5.retail[0].text, "omega"); -} - -#[test] -fn shuffle_invariance_with_conflicting_ties_and_sort_order() { - let mut fixture = conflicting_tie_group(); - fixture.extend([ - post( - "chan_b", - "sp_10", - 1_725_000_010_000, - None, - Some("1"), - Some("wire"), - "wire 10", - ), - post( - "chan_a", - "sp_02", - 1_725_000_020_000, - None, - Some("1"), - Some("wire"), - "wire 02", - ), - post( - "chan_a", - "sp_01", - 1_725_000_020_000, - None, - Some("1"), - Some("wire"), - "wire 01 same known_at", - ), - post( - "chan_b", - "sp_20", - 1_725_000_005_000, - Some(1_725_000_030_000), - None, - Some("u20"), - "retail edited later", - ), - post( - "chan_b", - "sp_20", - 1_725_000_005_000, - None, - None, - Some("u20"), - "retail older version", - ), - post( - "chan_a", - "sp_03", - 1_725_000_001_000, - Some(1_725_000_000_000), - Some("0"), - Some("u03"), - "retail edited before posted", - ), - post( - "chan_a", - "", - 1_725_000_001_000, - None, - Some("1"), - None, - "invalid empty id", - ), - post( - "chan_a", - "sp_bad_ts", - 0, - None, - None, - None, - "invalid zero ts", - ), - ]); - - let baseline = build_posts(fixture.clone()).expect("fixture should build"); - assert_invariants(&baseline); - - // Reversed order. - let mut reversed = fixture.clone(); - reversed.reverse(); - assert_eq!(build_posts(reversed).unwrap(), baseline); - - // Multiple deterministic shuffles. - let mut rng = SplitMix64(0x1234_5678_9abc_def0); - for _ in 0..16 { - let mut shuffled = fixture.clone(); - rng.shuffle(&mut shuffled); - let built = build_posts(shuffled).expect("shuffled fixture should build"); - assert_eq!(built, baseline); - } - - // Verify generic non-String key (e.g., listing_id: i32) works identically. - let int_keyed = build_posts(vec![ - CeoPost { - key: 200_i32, - spiel_id: "s2".to_string(), - timestamp_ms: 1_700_000_000_000, - edited_ms: None, - bot: None, - user_id: None, - text: "listing 200".to_string(), - }, - CeoPost { - key: 100_i32, - spiel_id: "s1".to_string(), - timestamp_ms: 1_700_000_000_000, - edited_ms: None, - bot: Some("1".to_string()), - user_id: None, - text: "listing 100".to_string(), - }, - ]) - .expect("i32 keys should build"); - assert_invariants(&int_keyed); - assert_eq!(int_keyed.newswire[0].key, 100); - assert_eq!(int_keyed.retail[0].key, 200); -} - -#[test] -fn empty_invalid_and_timestamp_overflow_boundaries() { - // Empty input. - let empty = build_posts(Vec::>::new()).expect("empty input should succeed"); - assert!(empty.newswire.is_empty()); - assert!(empty.retail.is_empty()); - assert_eq!(empty.stats, PostsStats::default()); - - // Empty spiel_id, zero timestamp_ms, negative timestamp_ms (including i64::MIN). - let invalid = build_posts(vec![ - post("c", "", 1_700_000_000_000, None, Some("1"), None, "empty id"), - post("c", "sp_zero", 0, None, None, None, "zero ts"), - post("c", "sp_neg", -1, None, None, None, "negative ts"), - post("c", "sp_min", i64::MIN, None, None, None, "i64 min ts"), - ]) - .expect("invalid rows should be rejected, not error"); - assert_invariants(&invalid); - assert_eq!(invalid.stats.input, 4); - assert_eq!(invalid.stats.rejected_invalid, 4); - assert_eq!(invalid.stats.newswire, 0); - assert_eq!(invalid.stats.retail, 0); - - // Greatest convertible millisecond value succeeds for both timestamp_ms and edited_ms. - let max_ms = i64::MAX / 1_000; - let boundary_ok = build_posts(vec![ - post("c", "sp_max_post", max_ms, None, None, None, "max posted"), - post( - "c", - "sp_max_edit", - max_ms - 1, - Some(max_ms), - None, - None, - "max edited", - ), - // Clamped earlier edited_ms = i64::MIN must not overflow when rejected in favor of timestamp_ms. - post( - "c", - "sp_clamped_min_edit", - 1_000, - Some(i64::MIN), - None, - None, - "clamped min edit", - ), - ]) - .expect("max convertible ms should succeed"); - assert_invariants(&boundary_ok); - assert_eq!(boundary_ok.stats.retail, 3); - assert_eq!(boundary_ok.stats.edited, 2); - assert_eq!(boundary_ok.stats.edited_before_posted, 1); - - // Overflow on timestamp_ms returns typed PostsError::TimestampOverflow. - let err_post = build_posts(vec![post( - "c", - "sp_overflow_post", - max_ms + 1, - None, - None, - None, - "overflow post", - )]) - .expect_err("timestamp_ms overflow should error"); - assert_eq!( - err_post, - PostsError::TimestampOverflow { - spiel_id: "sp_overflow_post".to_string(), - field: "timestamp_ms", - timestamp_ms: max_ms + 1, - } - ); - assert!(err_post.to_string().contains("timestamp_ms")); - assert!(err_post.to_string().contains("sp_overflow_post")); - - // Overflow on selected edited_ms returns typed PostsError::TimestampOverflow. - let err_edit = build_posts(vec![post( - "c", - "sp_overflow_edit", - 1_700_000_000_000, - Some(max_ms + 1), - None, - None, - "overflow edit", - )]) - .expect_err("edited_ms overflow should error"); - assert_eq!( - err_edit, - PostsError::TimestampOverflow { - spiel_id: "sp_overflow_edit".to_string(), - field: "edited_ms", - timestamp_ms: max_ms + 1, - } - ); - assert!(err_edit.to_string().contains("edited_ms")); - assert!(err_edit.to_string().contains("sp_overflow_edit")); -} - -#[test] -fn bot_flag_whitespace_and_near_miss_values() { - let base = 1_730_000_000_000_i64; - let input = vec![ - post("c", "b_exact", base, None, Some("1"), None, "exact"), - post("c", "b_tabs", base + 1, None, Some("\t1\r\n"), None, "tabs"), - post("c", "r_leading_zero", base + 2, None, Some("01"), None, "01"), - post("c", "r_decimal", base + 3, None, Some("1.0"), None, "1.0"), - post("c", "r_plus", base + 4, None, Some("+1"), None, "+1"), - post("c", "r_ten", base + 5, None, Some("10"), None, "10"), - post("c", "r_two_ones", base + 6, None, Some("1 1"), None, "1 1"), - post("c", "r_spaces", base + 7, None, Some(" "), None, "spaces"), - ]; - - let built = build_posts(input).expect("valid posts should build"); - assert_invariants(&built); - - let wire_ids: Vec<&str> = built.newswire.iter().map(|r| r.spiel_id.as_str()).collect(); - let retail_ids: Vec<&str> = built.retail.iter().map(|r| r.spiel_id.as_str()).collect(); - assert_eq!(wire_ids, vec!["b_exact", "b_tabs"]); - assert_eq!( - retail_ids, - vec![ - "r_leading_zero", - "r_decimal", - "r_plus", - "r_ten", - "r_two_ones", - "r_spaces", - ] - ); -} - -#[test] -fn exact_duplicate_rows_collapse_and_preserve_pre_dedup_edit_counts() { - let t = 1_730_100_000_000_i64; - let edited_dup = post( - "TSXV:XYZ", - "dup_edited", - t, - Some(t + 60_000), - Some("0"), - Some("u1"), - "exact same edited text", - ); - let skewed_dup = post( - "TSXV:XYZ", - "dup_skewed", - t + 1_000, - Some(t), - Some("1"), - Some("wire"), - "exact same skewed wire", - ); - - let input = vec![ - edited_dup.clone(), - edited_dup.clone(), - edited_dup, - skewed_dup.clone(), - skewed_dup, - ]; - - let built = build_posts(input).expect("exact duplicates should build"); - assert_invariants(&built); - assert_eq!( - built.stats, - PostsStats { - input: 5, - newswire: 1, - retail: 1, - edited: 5, - edited_before_posted: 2, - duplicates_dropped: 3, - rejected_invalid: 0, - } - ); - assert_eq!(built.retail[0].spiel_id, "dup_edited"); - assert_eq!(built.newswire[0].spiel_id, "dup_skewed"); -} - -#[test] -fn dedup_alternating_stream_winners_and_losers_across_shuffles() { - let t = 1_730_200_000_000_i64; - let fixture = vec![ - // Group 1: newswire wins over retail via higher known_at. - post("c1", "sp_01", t, None, Some("0"), Some("r1"), "retail v1"), - post("c1", "sp_01", t, Some(t + 5_000), Some("1"), Some("w1"), "wire v2"), - // Group 2: retail wins over newswire via higher known_at. - post("c1", "sp_02", t, None, Some("1"), Some("w2"), "wire v1"), - post("c1", "sp_02", t, Some(t + 5_000), Some("0"), Some("r2"), "retail v2"), - // Group 3: newswire wins over retail via tie-break (is_bot = true > false). - post("c1", "sp_03", t, None, Some("0"), Some("r3"), "retail tie"), - post("c1", "sp_03", t, None, Some("1"), Some("w3"), "wire tie"), - // Group 4: retail wins over newswire via tie-break (is_edited = true > false). - post("c1", "sp_04", t, None, Some("1"), Some("w4"), "wire unedited"), - post("c1", "sp_04", t, Some(t), Some("0"), Some("r4"), "retail edited"), - ]; - - let baseline = build_posts(fixture.clone()).expect("alternating fixture should build"); - assert_invariants(&baseline); - assert_eq!(baseline.stats.newswire, 2); - assert_eq!(baseline.stats.retail, 2); - assert_eq!(baseline.stats.duplicates_dropped, 4); - - let wire_ids: Vec<&str> = baseline - .newswire - .iter() - .map(|r| r.spiel_id.as_str()) - .collect(); - let retail_ids: Vec<&str> = baseline - .retail - .iter() - .map(|r| r.spiel_id.as_str()) - .collect(); - assert_eq!(wire_ids, vec!["sp_03", "sp_01"]); - assert_eq!(retail_ids, vec!["sp_04", "sp_02"]); - - let mut rng = SplitMix64(0xdead_beef_cafe_babe); - for _ in 0..32 { - let mut shuffled = fixture.clone(); - rng.shuffle(&mut shuffled); - let built = build_posts(shuffled).expect("shuffled alternating fixture should build"); - assert_eq!(built, baseline); - } -} - -#[test] -fn cutoff_filter_on_known_at_hides_post_edited_after_cutoff() { - // Mirrors the worked example: cutoff at 15:45, six retail posts (one posted at 15:40 and - // rewritten at 15:52 after the stock drops), plus three unedited wire releases. - let t_1530 = 1_730_300_000_000_i64; - let t_1540 = t_1530 + 10 * 60_000; - let t_1545_cutoff_us = (t_1530 + 15 * 60_000) * 1_000; - let t_1552 = t_1530 + 22 * 60_000; - - let input = vec![ - post("TSXV:EX", "r1", t_1530, None, None, Some("u1"), "+1"), - post("TSXV:EX", "r2", t_1530 + 60_000, None, None, Some("u2"), "+1"), - post("TSXV:EX", "r3", t_1530 + 120_000, None, None, Some("u3"), "0"), - post("TSXV:EX", "r4", t_1530 + 180_000, None, None, Some("u4"), "-1"), - post("TSXV:EX", "r5", t_1530 + 240_000, None, None, Some("u5"), "0"), - post( - "TSXV:EX", - "r6_edited_after_cutoff", - t_1540, - Some(t_1552), - None, - Some("u6"), - "-1 rewritten after drop", - ), - post("TSXV:EX", "w1", t_1530 + 30_000, None, Some("1"), Some("wire"), "+1"), - post("TSXV:EX", "w2", t_1530 + 90_000, None, Some("1"), Some("wire"), "+1"), - post("TSXV:EX", "w3", t_1530 + 150_000, None, Some("1"), Some("wire"), "+1"), - ]; - - let built = build_posts(input).expect("worked example should build"); - assert_invariants(&built); - assert_eq!(built.retail.len(), 6); - assert_eq!(built.newswire.len(), 3); - - // Filtering retail on known_at < cutoff excludes the post edited at 15:52. - let visible_by_known_at: Vec<&str> = built - .retail - .iter() - .filter(|r| r.known_at < t_1545_cutoff_us) - .map(|r| r.spiel_id.as_str()) - .collect(); - assert_eq!(visible_by_known_at.len(), 5); - assert!(!visible_by_known_at.contains(&"r6_edited_after_cutoff")); - - // Filtering on posted_at < cutoff would leak the post edited at 15:52. - let leaked_by_posted_at: Vec<&str> = built - .retail - .iter() - .filter(|r| r.posted_at < t_1545_cutoff_us) - .map(|r| r.spiel_id.as_str()) - .collect(); - assert_eq!(leaked_by_posted_at.len(), 6); - assert!(leaked_by_posted_at.contains(&"r6_edited_after_cutoff")); -} diff --git a/tools/curate-etl/src/session_close.rs b/tools/curate-etl/src/session_close.rs index 1969073a..49630836 100644 --- a/tools/curate-etl/src/session_close.rs +++ b/tools/curate-etl/src/session_close.rs @@ -42,37 +42,10 @@ 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; -/// 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`]. +/// Typed error returned by [`et_session_close_utc_micros`]. #[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]`. @@ -81,12 +54,6 @@ 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 { @@ -100,14 +67,6 @@ 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)" - ), } } } @@ -193,52 +152,6 @@ pub fn et_session_close_utc_micros(epoch_day: i32) -> Result Result { - if !(SESSION_MIN_SUPPORTED_UTC_MICROS..=SESSION_MAX_SUPPORTED_UTC_MICROS).contains(&utc_micros) { - return Err(SessionCloseError::TimestampOutOfRange { - utc_micros, - min_supported: SESSION_MIN_SUPPORTED_UTC_MICROS, - max_supported: SESSION_MAX_SUPPORTED_UTC_MICROS, - }); - } - - // Bounds check above guarantees `est_micros >= 2191 * MICROS_PER_DAY > 0` without overflow. - let est_micros = utc_micros - 5 * MICROS_PER_HOUR; - let est_day = (est_micros / MICROS_PER_DAY) as i32; - let (year, _, _) = epoch_days_to_ymd(est_day); - let (dst_start, dst_end) = dst_bounds()[(year - SESSION_CLOSE_MIN_SUPPORTED_YEAR) as usize]; - - // Spring forward: 02:00:00 EST = 07:00:00 UTC on `dst_start`. - // Fall back: 02:00:00 EDT = 06:00:00 UTC on `dst_end`. - let dst_start_utc = i64::from(dst_start) * MICROS_PER_DAY + 7 * MICROS_PER_HOUR; - let dst_end_utc = i64::from(dst_end) * MICROS_PER_DAY + 6 * MICROS_PER_HOUR; - let is_edt = utc_micros >= dst_start_utc && utc_micros < dst_end_utc; - - let local_micros = if is_edt { - est_micros + MICROS_PER_HOUR - } else { - est_micros - }; - let session_date = (local_micros / MICROS_PER_DAY) as i32; - let rem_micros = local_micros - i64::from(session_date) * MICROS_PER_DAY; - let minute_of_day = (rem_micros / MICROS_PER_MINUTE) as u16; - - Ok(EtLocalDateTime { - session_date, - minute_of_day, - is_edt, - }) -} - #[cfg(test)] mod tests { use super::*; @@ -394,207 +307,4 @@ mod tests { ); } } - - fn utc_micros(y: i32, m: u32, d: u32, h: i64, min: i64, sec: i64, us: i64) -> i64 { - let ep = day(y, m, d); - ((i64::from(ep) * 86_400 + h * 3_600 + min * 60 + sec) * 1_000_000) + us - } - - #[test] - fn utc_micros_to_et_local_round_trips_et_session_close_across_all_supported_days() { - for d in SESSION_CLOSE_MIN_SUPPORTED_DATE..=SESSION_CLOSE_MAX_SUPPORTED_DATE { - let close_utc = et_session_close_utc_micros(d).expect("in-range date"); - let local = utc_micros_to_et_local(close_utc).expect("in-range timestamp"); - assert_eq!(local.session_date, d, "session_date mismatch on day={d}"); - assert_eq!( - local.minute_of_day, - 16 * 60, - "16:00 ET minute mismatch on day={d}" - ); - let expected_edt = - (close_utc - i64::from(d) * MICROS_PER_DAY) == 20 * MICROS_PER_HOUR; - assert_eq!(local.is_edt, expected_edt, "DST flag mismatch on day={d}"); - } - } - - #[test] - fn utc_micros_to_et_local_handles_dst_transitions_across_all_three_eras() { - // (year, spring_month, spring_day, fall_month, fall_day) - let eras = [ - // Era 1 (1976..=1986): last Sun Apr -> last Sun Oct - (1976, 4, 25, 10, 31), - (1986, 4, 27, 10, 26), - // Era 2 (1987..=2006): 1st Sun Apr -> last Sun Oct (including 2003) - (1987, 4, 5, 10, 25), - (2003, 4, 6, 10, 26), - (2006, 4, 2, 10, 29), - // Era 3 (2007..=2030): 2nd Sun Mar -> 1st Sun Nov - (2007, 3, 11, 11, 4), - (2024, 3, 10, 11, 3), - (2030, 3, 10, 11, 3), - ]; - - for (y, sm, sd, fm, fd) in eras { - let spring_day = day(y, sm, sd); - // 06:59:59.999999 UTC -> 01:59:59.999999 EST - let before_spring = utc_micros(y, sm, sd, 6, 59, 59, 999_999); - assert_eq!( - utc_micros_to_et_local(before_spring).unwrap(), - EtLocalDateTime { - session_date: spring_day, - minute_of_day: 60 + 59, - is_edt: false, - }, - "before spring-forward in {y}" - ); - // 07:00:00.000000 UTC -> 03:00:00.000000 EDT (skips 02:xx) - let at_spring = utc_micros(y, sm, sd, 7, 0, 0, 0); - assert_eq!( - utc_micros_to_et_local(at_spring).unwrap(), - EtLocalDateTime { - session_date: spring_day, - minute_of_day: 3 * 60, - is_edt: true, - }, - "at spring-forward in {y}" - ); - - let fall_day = day(y, fm, fd); - // 05:59:59.999999 UTC -> 01:59:59.999999 EDT (first 01:59) - let before_fall = utc_micros(y, fm, fd, 5, 59, 59, 999_999); - assert_eq!( - utc_micros_to_et_local(before_fall).unwrap(), - EtLocalDateTime { - session_date: fall_day, - minute_of_day: 60 + 59, - is_edt: true, - }, - "before fall-back in {y}" - ); - // 06:00:00.000000 UTC -> 01:00:00.000000 EST (repeated 01:00) - let at_fall = utc_micros(y, fm, fd, 6, 0, 0, 0); - assert_eq!( - utc_micros_to_et_local(at_fall).unwrap(), - EtLocalDateTime { - session_date: fall_day, - minute_of_day: 60, - is_edt: false, - }, - "at fall-back in {y}" - ); - } - } - - #[test] - fn utc_micros_to_et_local_handles_utc_vs_et_midnight_crossovers() { - // Summer (EDT, UTC-4): 2024-06-10 00:30 UTC == 2024-06-09 20:30 EDT (previous calendar day) - assert_eq!( - utc_micros_to_et_local(utc_micros(2024, 6, 10, 0, 30, 0, 0)).unwrap(), - EtLocalDateTime { - session_date: day(2024, 6, 9), - minute_of_day: 20 * 60 + 30, - is_edt: true, - } - ); - // 2024-06-10 03:59:59.999999 UTC == 2024-06-09 23:59 EDT - assert_eq!( - utc_micros_to_et_local(utc_micros(2024, 6, 10, 3, 59, 59, 999_999)).unwrap(), - EtLocalDateTime { - session_date: day(2024, 6, 9), - minute_of_day: 23 * 60 + 59, - is_edt: true, - } - ); - // 2024-06-10 04:00:00.000000 UTC == 2024-06-10 00:00 EDT - assert_eq!( - utc_micros_to_et_local(utc_micros(2024, 6, 10, 4, 0, 0, 0)).unwrap(), - EtLocalDateTime { - session_date: day(2024, 6, 10), - minute_of_day: 0, - is_edt: true, - } - ); - - // Winter (EST, UTC-5): 2025-01-16 00:30 UTC == 2025-01-15 19:30 EST - assert_eq!( - utc_micros_to_et_local(utc_micros(2025, 1, 16, 0, 30, 0, 0)).unwrap(), - EtLocalDateTime { - session_date: day(2025, 1, 15), - minute_of_day: 19 * 60 + 30, - is_edt: false, - } - ); - // 2025-01-16 04:59:59.999999 UTC == 2025-01-15 23:59 EST - assert_eq!( - utc_micros_to_et_local(utc_micros(2025, 1, 16, 4, 59, 59, 999_999)).unwrap(), - EtLocalDateTime { - session_date: day(2025, 1, 15), - minute_of_day: 23 * 60 + 59, - is_edt: false, - } - ); - // 2025-01-16 05:00:00.000000 UTC == 2025-01-16 00:00 EST - assert_eq!( - utc_micros_to_et_local(utc_micros(2025, 1, 16, 5, 0, 0, 0)).unwrap(), - EtLocalDateTime { - session_date: day(2025, 1, 16), - minute_of_day: 0, - is_edt: false, - } - ); - } - - #[test] - fn utc_micros_to_et_local_bounds_and_out_of_range_errors() { - // Exact inclusive bounds - assert_eq!( - SESSION_MIN_SUPPORTED_UTC_MICROS, - utc_micros(1976, 1, 1, 5, 0, 0, 0) - ); - assert_eq!( - SESSION_MAX_SUPPORTED_UTC_MICROS, - utc_micros(2031, 1, 1, 4, 59, 59, 999_999) - ); - assert_eq!( - utc_micros_to_et_local(SESSION_MIN_SUPPORTED_UTC_MICROS).unwrap(), - EtLocalDateTime { - session_date: SESSION_CLOSE_MIN_SUPPORTED_DATE, - minute_of_day: 0, - is_edt: false, - } - ); - assert_eq!( - utc_micros_to_et_local(SESSION_MAX_SUPPORTED_UTC_MICROS).unwrap(), - EtLocalDateTime { - session_date: SESSION_CLOSE_MAX_SUPPORTED_DATE, - minute_of_day: 23 * 60 + 59, - is_edt: false, - } - ); - - let bad_ts = [ - SESSION_MIN_SUPPORTED_UTC_MICROS - 1, - SESSION_MAX_SUPPORTED_UTC_MICROS + 1, - 0, - i64::MIN, - i64::MAX, - ]; - for ts in bad_ts { - let err = utc_micros_to_et_local(ts).unwrap_err(); - assert_eq!( - err, - SessionCloseError::TimestampOutOfRange { - utc_micros: ts, - min_supported: SESSION_MIN_SUPPORTED_UTC_MICROS, - max_supported: SESSION_MAX_SUPPORTED_UTC_MICROS, - } - ); - assert!(err.source().is_none()); - let msg = err.to_string(); - assert!( - msg.contains(&ts.to_string()) && msg.contains("1976-01-01T05:00:00Z"), - "unexpected Display message: {msg}" - ); - } - } } diff --git a/tools/curate-etl/tests/bars_1m_qa_contract.rs b/tools/curate-etl/tests/bars_1m_qa_contract.rs deleted file mode 100644 index 0ffcc1ef..00000000 --- a/tools/curate-etl/tests/bars_1m_qa_contract.rs +++ /dev/null @@ -1,584 +0,0 @@ -//! QA contract tests for `bars_1m::build_bars_1m` / `check_session_closes` (T-130 / M2.3a). -//! -//! Uses only the public crate API. Expected Eastern session dates and minutes come from how the -//! fixtures are generated (`et_to_utc_micros(date, hh, mm)`), not from `utc_micros_to_et_local`, -//! and expected split factors come from `SplitTable::cum_factor_after`, so the builder's -//! two-pointer split cursor and ET conversion are checked against independent oracles. - -use std::cmp::Ordering; -use std::collections::{HashMap, HashSet}; - -use curate_etl::{ - build_bars_1m, check_session_closes, check_session_closes_against_bars_1d, et_to_utc_micros, - unadjust_ohlcv, ymd_to_epoch_days, Bar1dRow, Bar1mRow, Bars1mStats, DailySessionClose, - EodIntradayBar, IntradaySession, OhlcvBar, SessionCloseCutoffPolicy, SessionCloseStats, - SplitEvent, SplitTable, BARS_1M_SOURCE_EOD, MAX_MISMATCH_SAMPLES, -}; - -/// Deterministic SplitMix64 so every run sees identical fixtures. -struct Rng(u64); - -impl Rng { - fn next_u64(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } - - fn below(&mut self, n: u64) -> u64 { - self.next_u64() % n - } -} - -fn day(y: i32, m: u32, d: u32) -> i32 { - ymd_to_epoch_days(y, m, d).expect("valid date") -} - -fn et(date: i32, hour: u8, minute: u8) -> i64 { - et_to_utc_micros(date, hour, minute, 0).expect("valid ET timestamp") -} - -fn bar(key: &str, ts: i64, o: f64, h: f64, l: f64, c: f64, v: f64) -> EodIntradayBar { - EodIntradayBar { - key: key.to_string(), - ts, - open: o, - high: h, - low: l, - close: c, - volume: v, - } -} - -fn flat(key: &str, ts: i64, price: f64, volume: f64) -> EodIntradayBar { - bar(key, ts, price, price, price, price, volume) -} - -fn expected_session(minute_of_day: u16) -> IntradaySession { - if minute_of_day < 570 { - IntradaySession::Pre - } else if minute_of_day < 960 { - IntradaySession::Rth - } else { - IntradaySession::Post - } -} - -fn assert_conservation(stats: &Bars1mStats) { - assert_eq!( - stats.bars_in, - stats.rows_out - + stats.dropped_invalid_ohlc - + stats.dropped_inconsistent_ohlc - + stats.dropped_invalid_volume - + stats.dropped_ts_out_of_range - + stats.duplicate_collapsed - + stats.duplicate_conflict_dropped, - "conservation invariant failed: {stats:?}" - ); - assert_eq!( - stats.rows_out, - stats.pre_rows_out + stats.rth_rows_out + stats.post_rows_out - ); -} - -fn assert_close_invariants(stats: &SessionCloseStats) { - assert_eq!( - stats.checked + stats.unchecked, - stats.rth_sessions, - "{stats:?}" - ); - assert_eq!( - stats.within_tolerance + stats.mismatched, - stats.checked, - "{stats:?}" - ); - assert_eq!( - stats.daily_rows_in, - stats.daily_unique_partners - + stats.daily_invalid_close_dropped - + stats.daily_duplicate_collapsed - + stats.daily_duplicate_conflict_dropped, - "{stats:?}" - ); -} - -fn assert_strictly_sorted(rows: &[Bar1mRow]) { - for w in rows.windows(2) { - let ord = w[0].key.cmp(&w[1].key).then_with(|| w[0].ts.cmp(&w[1].ts)); - assert_eq!( - ord, - Ordering::Less, - "rows not strictly sorted: {:?} / {:?}", - w[0], - w[1] - ); - } -} - -#[test] -fn seeded_clean_bars_match_independent_et_and_cum_factor_oracle_bitwise() { - // Arrange: 40 keys, 0-3 splits each (forward/reverse, some on weekends), bars spread across - // 2023-2025 at arbitrary ET minutes (including 00:00 and 23:59) so EST, EDT and DST-transition - // days are all exercised. - let mut rng = Rng(0x0B45_1A11_7E57_0001); - let ratios = [0.05, 0.1, 0.25, 0.5, 2.0, 3.0, 4.0, 10.0, 1.5]; - let min_date = day(2023, 1, 1); - let span = (day(2025, 12, 31) - min_date + 1) as u64; - - let mut events = Vec::new(); - for k in 0..40 { - for _ in 0..rng.below(4) { - events.push(( - format!("K{k:02}"), - SplitEvent { - ex_date: min_date + rng.below(span) as i32, - ratio: ratios[rng.below(ratios.len() as u64) as usize], - }, - )); - } - } - let splits = SplitTable::from_events(events).expect("valid splits"); - - let mut inputs = Vec::new(); - let mut expected: HashMap<(String, i64), (i32, u16, EodIntradayBar)> = HashMap::new(); - while inputs.len() < 5_000 { - let key = format!("K{:02}", rng.below(40)); - let date = min_date + rng.below(span) as i32; - let minute = rng.below(1_440) as u16; - let (hh, mm) = ((minute / 60) as u8, (minute % 60) as u8); - // Skip wall-clock times that do not exist on spring-forward day. - let Ok(ts) = et_to_utc_micros(date, hh, mm, 0) else { - continue; - }; - if expected.contains_key(&(key.clone(), ts)) { - continue; - } - let low = 1.0 + rng.below(10_000) as f64 / 100.0; - let high = low * (1.0 + rng.below(500) as f64 / 10_000.0); - let open = low + (high - low) * 0.25; - let close = low + (high - low) * 0.75; - let volume = rng.below(1_000_000) as f64; - let b = bar(&key, ts, open, high, low, close, volume); - // Fall-back day repeats 01:xx; keep only the first occurrence's ET minute oracle. - expected.insert((key, ts), (date, minute, b.clone())); - inputs.push(b); - } - - // Act - let built = build_bars_1m(inputs.clone(), &splits); - - // Assert - assert_conservation(&built.stats); - assert_eq!(built.stats.rows_out, inputs.len()); - assert_strictly_sorted(&built.rows); - let mut applied_non_unit = 0usize; - for row in &built.rows { - let (date, minute, ref input) = expected[&(row.key.clone(), row.ts)]; - assert_eq!(row.session_date, date, "ET session_date for {row:?}"); - assert_eq!(row.session, expected_session(minute), "session for {row:?}"); - assert_eq!(row.source, BARS_1M_SOURCE_EOD); - let factor = splits.cum_factor_after(row.key.as_str(), date); - if factor != 1.0 { - applied_non_unit += 1; - } - let want = unadjust_ohlcv( - OhlcvBar { - open: input.open, - high: input.high, - low: input.low, - close: input.close, - volume: input.volume, - }, - factor, - ); - assert_eq!(row.open.to_bits(), want.open.to_bits(), "{row:?}"); - assert_eq!(row.high.to_bits(), want.high.to_bits(), "{row:?}"); - assert_eq!(row.low.to_bits(), want.low.to_bits(), "{row:?}"); - assert_eq!(row.close.to_bits(), want.close.to_bits(), "{row:?}"); - assert_eq!(row.volume.to_bits(), want.volume.to_bits(), "{row:?}"); - } - assert!( - applied_non_unit > 500, - "fixture must exercise splits: {applied_non_unit}" - ); -} - -#[test] -fn et_midnight_is_the_split_boundary_not_utc_midnight_in_est_and_edt() { - // Arrange: 2:1 splits; ex-dates in EDT (2024-06-10) and EST (2025-01-16). - for ex in [day(2024, 6, 10), day(2025, 1, 16)] { - let splits = SplitTable::from_events([( - "S".to_string(), - SplitEvent { - ex_date: ex, - ratio: 2.0, - }, - )]) - .unwrap(); - let last_pre_minute = et(ex - 1, 23, 59); - let first_ex_minute = et(ex, 0, 0); - - // Act - let built = build_bars_1m( - [ - flat("S", first_ex_minute, 10.0, 100.0), - flat("S", last_pre_minute, 10.0, 100.0), - ], - &splits, - ); - - // Assert: 23:59 ET (already the next UTC day) still gets the pre-split factor. - assert_conservation(&built.stats); - assert_eq!(built.rows.len(), 2); - assert_eq!(built.rows[0].session_date, ex - 1); - assert_eq!(built.rows[0].session, IntradaySession::Post); - assert_eq!(built.rows[0].close, 20.0); - assert_eq!(built.rows[0].volume, 50.0); - assert_eq!(built.rows[1].session_date, ex); - assert_eq!(built.rows[1].session, IntradaySession::Pre); - assert_eq!(built.rows[1].close.to_bits(), 10.0_f64.to_bits()); - assert_eq!(built.rows[1].volume.to_bits(), 100.0_f64.to_bits()); - } -} - -#[test] -fn cumulative_factor_spans_multiple_splits_and_weekend_ex_dates() { - // Arrange: 2:1 ex Saturday 2024-03-02, then 1:4 reverse ex Monday 2024-03-11. - let splits = SplitTable::from_events([ - ( - "M".to_string(), - SplitEvent { - ex_date: day(2024, 3, 2), - ratio: 2.0, - }, - ), - ( - "M".to_string(), - SplitEvent { - ex_date: day(2024, 3, 11), - ratio: 0.25, - }, - ), - ]) - .unwrap(); - - // Act - let built = build_bars_1m( - [ - flat("M", et(day(2024, 3, 1), 15, 59), 8.0, 1_000.0), // Fri: both splits ahead - flat("M", et(day(2024, 3, 4), 15, 59), 8.0, 1_000.0), // Mon: only reverse ahead - flat("M", et(day(2024, 3, 11), 15, 59), 8.0, 1_000.0), // ex-date of reverse - ], - &splits, - ); - - // Assert: factor 2*0.25 = 0.5, then 0.25, then 1. - assert_conservation(&built.stats); - let closes: Vec = built.rows.iter().map(|r| r.close).collect(); - let volumes: Vec = built.rows.iter().map(|r| r.volume).collect(); - assert_eq!(closes, vec![4.0, 2.0, 8.0]); - assert_eq!(volumes, vec![2_000.0, 4_000.0, 1_000.0]); -} - -#[test] -fn rth_boundaries_hold_on_dst_transition_sundays() { - // Arrange: spring-forward 2024-03-10 and fall-back 2024-11-03 (EDT->EST). - let splits: SplitTable = SplitTable::default(); - let mut inputs = Vec::new(); - for d in [day(2024, 3, 10), day(2024, 11, 3)] { - for (h, m) in [(9, 29), (9, 30), (15, 59), (16, 0)] { - inputs.push(flat("D", et(d, h, m), 10.0, 1.0)); - } - } - - // Act - let built = build_bars_1m(inputs, &splits); - - // Assert - let sessions: Vec<&str> = built.rows.iter().map(|r| r.session.as_str()).collect(); - assert_eq!( - sessions, - vec!["PRE", "RTH", "RTH", "POST", "PRE", "RTH", "RTH", "POST"] - ); -} - -#[test] -fn seeded_dirty_input_conserves_counts_and_is_permutation_invariant() { - // Arrange: mix of valid bars, every bad-row category, exact and conflicting duplicates. - let mut rng = Rng(0x0B45_1A11_D127_0002); - let splits = SplitTable::from_events([ - ( - "A".to_string(), - SplitEvent { - ex_date: day(2024, 6, 10), - ratio: 10.0, - }, - ), - ( - "B".to_string(), - SplitEvent { - ex_date: day(2024, 6, 12), - ratio: 0.05, - }, - ), - ]) - .unwrap(); - let keys = ["A", "B", "C"]; - let base = et(day(2024, 6, 7), 4, 0); - let mut inputs = Vec::new(); - for _ in 0..3_000 { - let key = keys[rng.below(3) as usize]; - let ts = base + rng.below(8 * 1_440) as i64 * 60_000_000; - let p = 10.0 + rng.below(100) as f64 / 10.0; - let b = match rng.below(12) { - 0 => bar(key, ts, f64::NAN, p, p, p, 1.0), - 1 => bar(key, ts, p, p, p, -p, 1.0), - 2 => bar(key, ts, p, p - 1.0, p, p, 1.0), - 3 => bar(key, ts, p, p, p, p, f64::NEG_INFINITY), - 4 => bar(key, i64::MAX - rng.below(10) as i64, p, p, p, p, 1.0), - 5 => bar(key, ts, p, p, p, p, -0.0), - _ => bar(key, ts, p, p + 0.5, p - 0.5, p, rng.below(1_000) as f64), - }; - inputs.push(b.clone()); - // ~10% exact duplicates, ~5% conflicting duplicates. - match rng.below(20) { - 0 | 1 => inputs.push(b), - 2 => { - let mut c = b; - c.volume += 1.0; - inputs.push(c); - } - _ => {} - } - } - - // Act - let forward = build_bars_1m(inputs.clone(), &splits); - let mut shuffled = inputs.clone(); - for i in (1..shuffled.len()).rev() { - shuffled.swap(i, rng.below(i as u64 + 1) as usize); - } - let permuted = build_bars_1m(shuffled, &splits); - - // Assert - assert_conservation(&forward.stats); - assert_eq!(forward, permuted, "output must not depend on input order"); - assert_strictly_sorted(&forward.rows); - for counter in [ - forward.stats.dropped_invalid_ohlc, - forward.stats.dropped_inconsistent_ohlc, - forward.stats.dropped_invalid_volume, - forward.stats.dropped_ts_out_of_range, - forward.stats.duplicate_collapsed, - forward.stats.duplicate_conflict_dropped, - ] { - assert!( - counter > 0, - "every category must be exercised: {:?}", - forward.stats - ); - } - let unique: HashSet<(String, i64)> = - forward.rows.iter().map(|r| (r.key.clone(), r.ts)).collect(); - assert_eq!(unique.len(), forward.rows.len()); - assert!(forward - .rows - .iter() - .all(|r| r.volume.to_bits() != (-0.0_f64).to_bits())); -} - -#[test] -fn keys_out_ignores_keys_whose_every_bar_is_dropped() { - let splits: SplitTable = SplitTable::default(); - let ts = et(day(2024, 6, 10), 10, 0); - let built = build_bars_1m( - [ - flat("GONE", ts, 10.0, 1.0), - flat("GONE", ts, 10.5, 1.0), // conflict drops the whole group - flat("NAN", ts, f64::NAN, 1.0), - flat("KEEP", ts, 10.0, 1.0), - ], - &splits, - ); - assert_conservation(&built.stats); - assert_eq!(built.stats.keys_out, 1); - assert_eq!(built.rows.len(), 1); - assert_eq!(built.rows[0].key, "KEEP"); -} - -#[test] -fn session_close_tolerance_is_inclusive_and_zero_tolerance_is_accepted() { - let d = day(2024, 6, 10); - let splits: SplitTable = SplitTable::default(); - let built = build_bars_1m([flat("T", et(d, 15, 59), 100.5, 1.0)], &splits); - let daily = [DailySessionClose::new("T".to_string(), d, 100.0)]; - - // rel == 0.5 / 100 == 0.005 exactly -> within tolerance. - let at_edge = check_session_closes(&built.rows, daily.clone(), 0.005).unwrap(); - assert_close_invariants(&at_edge.stats); - assert_eq!(at_edge.stats.within_tolerance, 1); - assert_eq!(at_edge.stats.mismatched, 0); - - let zero = check_session_closes(&built.rows, daily.clone(), 0.0).unwrap(); - assert_eq!(zero.stats.mismatched, 1); - let neg_zero = check_session_closes(&built.rows, daily, -0.0).unwrap(); - assert_eq!(neg_zero.stats.mismatched, 1); -} - -#[test] -fn daily_partner_without_intraday_rows_and_post_only_sessions_are_not_rth_sessions() { - let d1 = day(2024, 6, 10); - let d2 = day(2024, 6, 11); - let splits: SplitTable = SplitTable::default(); - let built = build_bars_1m( - [ - flat("X", et(d1, 15, 59), 50.0, 1.0), - flat("X", et(d2, 16, 30), 99.0, 1.0), // POST only - ], - &splits, - ); - let rows_1d = [ - Bar1dRow { - key: "X".to_string(), - session_date: d1, - open: 50.0, - high: 50.0, - low: 50.0, - close: 50.0, - volume: 1.0, - }, - Bar1dRow { - key: "X".to_string(), - session_date: d2, - open: 50.0, - high: 50.0, - low: 50.0, - close: 50.0, - volume: 1.0, - }, - Bar1dRow { - key: "Y".to_string(), - session_date: d1, - open: 7.0, - high: 7.0, - low: 7.0, - close: 7.0, - volume: 1.0, - }, - ]; - let check = check_session_closes_against_bars_1d( - &built.rows, - &rows_1d, - &SessionCloseCutoffPolicy::standard_rth(), - 0.005, - ) - .unwrap(); - assert_close_invariants(&check.stats); - assert_eq!(check.stats.rth_sessions, 1); - assert_eq!(check.stats.checked, 1); - assert_eq!(check.stats.within_tolerance, 1); - assert_eq!(check.stats.daily_unique_partners, 3); -} - -#[test] -fn early_close_date_cutoff_applies_to_listings_without_override() { - // Arrange: Friday after US Thanksgiving 2024 (13:00 ET close); policy sets only a date cutoff. - let d = day(2024, 11, 29); - let splits: SplitTable = SplitTable::default(); - let built = build_bars_1m( - [ - flat("U", et(d, 12, 59), 40.0, 1.0), - flat("U", et(d, 13, 15), 44.0, 1.0), - flat("V", et(d, 12, 59), 70.0, 1.0), - flat("V", et(d, 15, 59), 77.0, 1.0), - ], - &splits, - ); - let policy = SessionCloseCutoffPolicy::standard_rth().with_date_cutoff(d, et(d, 13, 0)); - let rows_1d = [ - Bar1dRow { - key: "U".to_string(), - session_date: d, - open: 40.0, - high: 40.0, - low: 40.0, - close: 40.0, - volume: 1.0, - }, - Bar1dRow { - key: "V".to_string(), - session_date: d, - open: 70.0, - high: 70.0, - low: 70.0, - close: 70.0, - volume: 1.0, - }, - ]; - - // Act - let check = check_session_closes_against_bars_1d(&built.rows, rows_1d, &policy, 0.005).unwrap(); - - // Assert: both listings resolve to their 12:59 ET bar. - assert_close_invariants(&check.stats); - assert_eq!(check.stats.checked, 2); - assert_eq!(check.stats.mismatched, 0); - assert_eq!(check.stats.max_rel_diff, 0.0); -} - -#[test] -fn split_fixture_cross_check_is_order_independent_and_samples_are_capped() { - // Arrange: 150 sessions on one 1:20 reverse-split key; feed adjusted (empty split table) and - // un-adjusted builds against the same raw daily closes. - let ex = day(2025, 6, 18); - let splits = SplitTable::from_events([( - "NEXM.V".to_string(), - SplitEvent { - ex_date: ex, - ratio: 0.05, - }, - )]) - .unwrap(); - let empty: SplitTable = SplitTable::default(); - let mut bars = Vec::new(); - let mut daily = Vec::new(); - for i in 0..150 { - let d = ex - 150 + i; - let adj_close = 20.0 + f64::from(i) * 0.01; - bars.push(flat("NEXM.V", et(d, 15, 59), adj_close, 1_000.0)); - bars.push(flat("NEXM.V", et(d, 16, 5), adj_close * 1.1, 10.0)); // POST noise - daily.push(DailySessionClose::new( - "NEXM.V".to_string(), - d, - adj_close * 0.05, - )); - } - - // Act - let unadj = build_bars_1m(bars.clone(), &splits); - let still_adj = build_bars_1m(bars, &empty); - let good = check_session_closes(&unadj.rows, daily.clone(), 0.005).unwrap(); - let bad = check_session_closes(&still_adj.rows, daily.clone(), 0.005).unwrap(); - let mut reversed = still_adj.rows.clone(); - reversed.reverse(); - let bad_reversed = check_session_closes(&reversed, daily, 0.005).unwrap(); - - // Assert - assert_close_invariants(&good.stats); - assert_eq!(good.stats.checked, 150); - assert_eq!(good.stats.mismatched, 0); - assert!(good.stats.max_rel_diff < 1e-12); - - assert_close_invariants(&bad.stats); - assert_eq!(bad.stats.mismatched, 150); - assert!(bad.stats.max_rel_diff > 0.005); - assert_eq!(bad.mismatch_samples.len(), MAX_MISMATCH_SAMPLES); - assert_eq!(bad, bad_reversed); - for s in &bad.mismatch_samples { - assert!((s.rel - 19.0).abs() < 1e-9, "rel {s:?}"); - assert_eq!(s.last_rth_ts, et(s.session_date, 15, 59)); - } -} diff --git a/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs b/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs deleted file mode 100644 index 5fe00412..00000000 --- a/tools/curate-etl/tests/bson_eod_intraday_qa_contract.rs +++ /dev/null @@ -1,438 +0,0 @@ -//! QA contract tests for the public `eodIntraday1M` raw BSON decoder (T-141 / M2.3d). -//! -//! Covers gaps left by the in-crate `bson_eod_intraday_tests.rs`, using only the public API: -//! - field-order independence, case-sensitive keys, nested look-alike keys ignored; -//! - error precedence: corrupt skipped payload beats an earlier semantic error, and the first -//! semantic error in document order wins over later ones; -//! - timestamp edge values (`i32::MAX`, subnormal / half-second / huge doubles); -//! - `Display` names the offending field; empty buffer; `i32::MAX` declared length; -//! - seeded byte-mutation fuzz: never panics, conservation always holds, every buffer row equals -//! the single-document decode of the same frame, and the stream decode reproduces the buffer -//! rows, per-document errors, and terminal framing offset; -//! - stream: empty input, `max_doc_bytes` overflow, and invalid options; -//! - UTC bar-start micros map to the right `build_bars_1m` session date across the UTC midnight. - -use std::io::{self, Cursor, Read}; - -use bson::raw::{cstr, RawBsonRef, RawDocumentBuf}; -use curate_etl::{ - build_bars_1m, decode_eod_intraday_buffer, decode_eod_intraday_bytes, - decode_eod_intraday_doc, decode_eod_intraday_stream, iter_raw_bson_docs, ymd_to_epoch_days, - BsonEodIntradayDecodeStats, BsonEodIntradayError, BsonStreamError, BsonStreamOptions, - RawEodIntradayBar, SplitTable, -}; - -const TS: i64 = 1_717_767_000; - -struct SplitMix64(u64); - -impl SplitMix64 { - 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) - } -} - -/// Reader returning seeded pseudo-random short reads of 1..=61 bytes. -struct JitterReader<'a> { - data: &'a [u8], - pos: usize, - rng: SplitMix64, -} - -impl Read for JitterReader<'_> { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - let remaining = self.data.len() - self.pos; - if remaining == 0 { - return Ok(0); - } - let step = (self.rng.next_u64() % 61) as usize + 1; - let take = remaining.min(step).min(buf.len()); - buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]); - self.pos += take; - Ok(take) - } -} - -fn valid_doc(code: &str, ts: i64, close: f64, volume: f64) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("symbol"), "X"); - doc.append(cstr!("eodSearchCode"), code); - doc.append(cstr!("datetime"), "2024-06-07 13:30:00"); - doc.append(cstr!("timestamp"), ts); - doc.append(cstr!("gmtoffset"), 0_i32); - doc.append(cstr!("open"), close - 0.25); - doc.append(cstr!("high"), close + 0.5); - doc.append(cstr!("low"), close - 0.5); - doc.append(cstr!("close"), close); - doc.append(cstr!("volume"), volume); - doc -} - -fn with_timestamp(ts: RawBsonRef<'_>) -> RawDocumentBuf { - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("timestamp"), ts); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), 1.0_f64); - doc -} - -type Row = (String, i64, [u64; 5]); - -fn row(b: RawEodIntradayBar<'_>) -> Row { - ( - b.eod_search_code.to_owned(), - b.ts, - [ - b.open.to_bits(), - b.high.to_bits(), - b.low.to_bits(), - b.close.to_bits(), - b.volume.to_bits(), - ], - ) -} - -#[test] -fn field_order_does_not_change_the_decoded_bar() { - let forward = valid_doc("NVDA.US", TS, 120.5, 1_000.0); - let mut reversed = RawDocumentBuf::new(); - reversed.append(cstr!("volume"), 1_000.0_f64); - reversed.append(cstr!("close"), 120.5_f64); - reversed.append(cstr!("low"), 120.0_f64); - reversed.append(cstr!("high"), 121.0_f64); - reversed.append(cstr!("open"), 120.25_f64); - reversed.append(cstr!("timestamp"), TS); - reversed.append(cstr!("eodSearchCode"), "NVDA.US"); - - assert_eq!( - decode_eod_intraday_doc(&forward).unwrap(), - decode_eod_intraday_doc(&reversed).unwrap() - ); -} - -#[test] -fn keys_are_case_sensitive_and_nested_look_alikes_are_ignored() { - // `Timestamp` (capital T) is not `timestamp`; a nested `timestamp` must not satisfy it either. - let mut nested = RawDocumentBuf::new(); - nested.append(cstr!("timestamp"), TS); - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), "NVDA.US"); - doc.append(cstr!("Timestamp"), TS); - doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref())); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), 1.0_f64); - - assert_eq!( - decode_eod_intraday_doc(&doc), - Err(BsonEodIntradayError::MissingField { field: "timestamp" }) - ); -} - -#[test] -fn eod_search_code_is_borrowed_verbatim_without_trimming() { - let doc = valid_doc(" NVDA.US ", TS, 10.0, 1.0); - let bar = decode_eod_intraday_bytes(doc.as_bytes()).unwrap(); - assert_eq!(bar.eod_search_code, " NVDA.US "); -} - -#[test] -fn first_semantic_error_in_document_order_wins() { - // close is invalid before eodSearchCode is blank: close error must be reported. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("close"), -1.0_f64); - doc.append(cstr!("eodSearchCode"), ""); - doc.append(cstr!("timestamp"), -5_i64); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("volume"), 1.0_f64); - - match decode_eod_intraday_doc(&doc) { - Err(BsonEodIntradayError::InvalidNumber { field: "close", value }) => { - assert_eq!(value, -1.0) - } - other => panic!("expected InvalidNumber(close), got {other:?}"), - } - - // A semantic error plus a missing field: the semantic error wins over MissingField. - let mut doc2 = RawDocumentBuf::new(); - doc2.append(cstr!("eodSearchCode"), "NVDA.US"); - doc2.append(cstr!("timestamp"), RawBsonRef::Null); - assert!(matches!( - decode_eod_intraday_doc(&doc2), - Err(BsonEodIntradayError::WrongType { field: "timestamp", .. }) - )); -} - -#[test] -fn corrupt_skipped_payload_after_semantic_error_is_reported_as_corrupt_bson() { - // Blank key (semantic) first, then a later `datetime` string with invalid UTF-8. - let mut doc = RawDocumentBuf::new(); - doc.append(cstr!("eodSearchCode"), " "); - doc.append(cstr!("timestamp"), TS); - doc.append(cstr!("open"), 10.0_f64); - doc.append(cstr!("high"), 11.0_f64); - doc.append(cstr!("low"), 9.0_f64); - doc.append(cstr!("close"), 10.5_f64); - doc.append(cstr!("volume"), 1.0_f64); - doc.append(cstr!("datetime"), "ZZZZ"); - let mut bytes = doc.into_bytes(); - let pos = bytes.windows(4).position(|w| w == b"ZZZZ").unwrap(); - bytes[pos + 1] = 0xFF; - - let mut stats = BsonEodIntradayDecodeStats::default(); - let mut errs = Vec::new(); - let s = decode_eod_intraday_buffer(&bytes, |_| panic!("no row"), |o, e| errs.push((o, e))); - stats.merge(&s); - assert_eq!(errs.len(), 1); - assert!(matches!(errs[0], (0, BsonEodIntradayError::CorruptBson { offset: 0, .. }))); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(stats.rejected_empty_field, 0); - assert_eq!(stats.rejected_total(), 1); -} - -#[test] -fn timestamp_edge_values_are_accepted_or_rejected_exactly() { - // i32::MAX seconds (2038-01-19) is valid in Int32 form. - let bar_doc = with_timestamp(RawBsonRef::Int32(i32::MAX)); - let bar = decode_eod_intraday_doc(&bar_doc).unwrap(); - assert_eq!(bar.ts, i64::from(i32::MAX) * 1_000_000); - - let max_secs = i64::MAX / 1_000_000; - for bad in [ - RawBsonRef::Double(f64::MIN_POSITIVE), - RawBsonRef::Double(5e-324), - RawBsonRef::Double(max_secs as f64 + 0.5), - RawBsonRef::Double(1e300), - RawBsonRef::Double(f64::MAX), - RawBsonRef::Int32(i32::MIN), - RawBsonRef::Int64(i64::MIN), - ] { - let doc = with_timestamp(bad); - assert_eq!( - decode_eod_intraday_doc(&doc), - Err(BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }), - "timestamp {bad:?}" - ); - } -} - -#[test] -fn display_messages_name_the_offending_field_and_offset() { - let cases = [ - (BsonEodIntradayError::MissingField { field: "eodSearchCode" }, "eodSearchCode"), - (BsonEodIntradayError::EmptyField { field: "eodSearchCode" }, "eodSearchCode"), - (BsonEodIntradayError::InvalidTimestamp { field: "timestamp" }, "timestamp"), - (BsonEodIntradayError::InvalidNumber { field: "volume", value: -1.0 }, ">= 0"), - (BsonEodIntradayError::InvalidNumber { field: "close", value: 0.0 }, "> 0"), - ( - BsonEodIntradayError::CorruptBson { offset: 77, detail: "x".into() }, - "77", - ), - ]; - for (err, needle) in cases { - let msg = err.to_string(); - assert!(msg.contains(needle), "{msg:?} should contain {needle:?}"); - } -} - -#[test] -fn empty_buffer_and_huge_declared_length_never_panic() { - let stats = decode_eod_intraday_buffer(&[], |_| panic!(), |_, _| panic!()); - assert_eq!(stats, BsonEodIntradayDecodeStats::default()); - - let mut bytes = valid_doc("NVDA.US", TS, 10.0, 1.0).into_bytes(); - let first_len = bytes.len(); - bytes.extend_from_slice(&i32::MAX.to_le_bytes()); - bytes.extend_from_slice(&[0u8; 8]); - let mut rows = 0usize; - let mut errs = Vec::new(); - let stats = decode_eod_intraday_buffer(&bytes, |_| rows += 1, |o, e| errs.push((o, e))); - assert_eq!(rows, 1); - assert_eq!(stats.docs_seen, 2); - assert_eq!(stats.rejected_corrupt_document, 1); - assert_eq!(errs.len(), 1); - assert_eq!(errs[0].0, first_len); - assert!(matches!( - errs[0].1, - BsonEodIntradayError::TruncatedDocument { declared_len: Some(i32::MAX), .. } - )); -} - -fn is_framing(e: &BsonEodIntradayError) -> bool { - matches!( - e, - BsonEodIntradayError::TruncatedDocument { .. } - | BsonEodIntradayError::CorruptDocumentLength { .. } - ) -} - -#[test] -fn seeded_mutation_fuzz_buffer_and_stream_agree_and_conserve_counts() { - let mut clean = Vec::new(); - for i in 0..20i64 { - let doc = valid_doc(&format!("S{i:02}.US"), TS + 60 * i, 10.0 + i as f64, 100.0 * i as f64); - clean.extend_from_slice(doc.as_bytes()); - } - let mut rng = SplitMix64(0x7141_B50E); - let (mut framing_cases, mut ok_cases, mut rows_seen) = (0usize, 0usize, 0usize); - - for case in 0..400u64 { - let mut bytes = clean.clone(); - for _ in 0..1 + (rng.next_u64() % 4) as usize { - let idx = (rng.next_u64() as usize) % bytes.len(); - bytes[idx] = rng.next_u64() as u8; - } - if rng.next_u64() % 5 == 0 { - let cut = (rng.next_u64() as usize) % bytes.len(); - bytes.truncate(cut); - } - - // Buffer decode: every row must equal the single-frame decode of the same bytes. - let mut frames = Vec::new(); - let mut it = iter_raw_bson_docs(&bytes); - while let Some(item) = it.next_with_offset() { - if let Ok((off, doc)) = item { - frames.push((off, doc.as_bytes().len())); - } - } - let mut exp_rows = Vec::new(); - let mut exp_errs = Vec::new(); - let stats = decode_eod_intraday_buffer( - &bytes, - |b| { - let start = b.eod_search_code.as_ptr() as usize - bytes.as_ptr() as usize; - let &(off, len) = frames - .iter() - .find(|(o, l)| start >= *o && start < o + l) - .expect("row borrows from a framed doc"); - assert_eq!(decode_eod_intraday_bytes(&bytes[off..off + len]).unwrap(), b); - exp_rows.push(row(b)); - }, - |o, e| exp_errs.push((o as u64, e)), - ); - assert_eq!(stats.docs_seen, stats.rows_decoded + stats.rejected_total(), "case={case}"); - assert_eq!(stats.rows_decoded, exp_rows.len()); - assert_eq!(stats.rejected_total(), exp_errs.len()); - rows_seen += exp_rows.len(); - - let exp_framing = match exp_errs.last() { - Some((off, e)) if is_framing(e) => { - let off = *off; - exp_errs.pop(); - Some(off) - } - _ => None, - }; - - let cap = [1usize, 5, 41, 300, 4096][(case % 5) as usize]; - let mut rows = Vec::new(); - let mut errs = Vec::new(); - let result = decode_eod_intraday_stream( - JitterReader { data: &bytes, pos: 0, rng: SplitMix64(case) }, - BsonStreamOptions { chunk_capacity_bytes: cap, max_doc_bytes: 1 << 20 }, - |b| rows.push(row(b)), - |o, e| errs.push((o, e)), - ); - assert_eq!(rows, exp_rows, "case={case} cap={cap}"); - assert_eq!(errs, exp_errs, "case={case} cap={cap}"); - match (exp_framing, result) { - (None, Ok(s)) => { - ok_cases += 1; - assert_eq!(s, stats, "case={case}"); - } - (Some(off), Err(BsonStreamError::CorruptDocumentLength { offset, .. })) - | (Some(off), Err(BsonStreamError::TruncatedDocument { offset, .. })) => { - framing_cases += 1; - assert_eq!(offset, off, "case={case} cap={cap}"); - } - (exp, got) => panic!("case={case}: expected framing={exp:?}, got {got:?}"), - } - } - assert!(framing_cases >= 20, "framing_cases={framing_cases}"); - assert!(ok_cases >= 20, "ok_cases={ok_cases}"); - assert!(rows_seen > 1000, "rows_seen={rows_seen}"); -} - -#[test] -fn stream_handles_empty_input_oversized_docs_and_invalid_options() { - let stats = decode_eod_intraday_stream( - Cursor::new(Vec::::new()), - BsonStreamOptions::default(), - |_| panic!(), - |_, _| panic!(), - ) - .unwrap(); - assert_eq!(stats, BsonEodIntradayDecodeStats::default()); - - let first = valid_doc("NVDA.US", TS, 10.0, 1.0).into_bytes(); - let mut big = valid_doc("BIG.US", TS, 10.0, 1.0); - big.append(cstr!("pad"), "p".repeat(256).as_str()); - let mut input = first.clone(); - input.extend_from_slice(big.as_bytes()); - - let mut rows = Vec::new(); - let err = decode_eod_intraday_stream( - Cursor::new(&input), - BsonStreamOptions { chunk_capacity_bytes: 16, max_doc_bytes: 200 }, - |b| rows.push(row(b)), - |_, e| panic!("unexpected per-doc error {e:?}"), - ) - .unwrap_err(); - assert_eq!(rows.len(), 1); - assert!(matches!( - err, - BsonStreamError::CorruptDocumentLength { offset, max_doc_bytes: 200, .. } - if offset == first.len() as u64 - )); - - for (opts, want_cap) in [ - (BsonStreamOptions { chunk_capacity_bytes: 0, max_doc_bytes: 4096 }, true), - (BsonStreamOptions { chunk_capacity_bytes: 16, max_doc_bytes: 4 }, false), - ] { - let err = decode_eod_intraday_stream(Cursor::new(&input), opts, |_| {}, |_, _| {}) - .unwrap_err(); - if want_cap { - assert!(matches!(err, BsonStreamError::InvalidChunkCapacity)); - } else { - assert!(matches!(err, BsonStreamError::InvalidMaxDocBytes)); - } - } -} - -#[test] -fn utc_bar_start_micros_assign_late_et_bars_to_the_correct_session_date() { - // 2024-06-07 19:59 EDT = 2024-06-07 23:59 UTC (same UTC date) and - // 2024-06-07 20:00 EDT = 2024-06-08 00:00 UTC (next UTC date) both belong to the 06-07 - // US session; a seconds/micros unit slip would push them to 1970 or far future dates. - let late = 1_717_804_740_i64; // 2024-06-07T23:59:00Z - let after_midnight = 1_717_804_800_i64; // 2024-06-08T00:00:00Z - let mut buf = Vec::new(); - buf.extend_from_slice(valid_doc("NVDA.US", late, 120.0, 10.0).as_bytes()); - buf.extend_from_slice(valid_doc("NVDA.US", after_midnight, 120.1, 10.0).as_bytes()); - - let mut bars = Vec::new(); - decode_eod_intraday_buffer( - &buf, - |b| bars.push(b.into_eod_intraday_bar(|c, _| c.to_owned())), - |_, e| panic!("{e:?}"), - ); - let built = build_bars_1m(bars, &SplitTable::::default()); - let june7 = ymd_to_epoch_days(2024, 6, 7).unwrap(); - let dates: Vec = built.rows.iter().map(|r| r.session_date).collect(); - assert_eq!(built.rows.len(), 2); - assert_eq!(dates, vec![june7, june7]); - assert_eq!(built.rows[0].ts, late * 1_000_000); - assert_eq!(built.rows[1].ts, after_midnight * 1_000_000); -} diff --git a/tools/curate-etl/tests/cli.rs b/tools/curate-etl/tests/cli.rs index 8902eb10..055232fc 100644 --- a/tools/curate-etl/tests/cli.rs +++ b/tools/curate-etl/tests/cli.rs @@ -46,7 +46,6 @@ fn no_args_and_help_print_usage_and_succeed() { "{args:?}: {text}" ); assert!(text.contains("bench-split"), "{args:?}: {text}"); - assert!(text.contains("bench-ilp-bars-1m"), "{args:?}: {text}"); assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}"); assert!(text.contains("bench-fx"), "{args:?}: {text}"); assert!(text.contains("bench-events"), "{args:?}: {text}"); @@ -91,10 +90,6 @@ fn invalid_invocations_exit_nonzero_with_usage_on_stderr() { &["bench-curate-fx", "0"][..], &["bench-curate-fx", "-5"][..], &["bench-curate-fx", "10", "20"][..], - &["bench-ilp-bars-1m", "abc"][..], - &["bench-ilp-bars-1m", "0"][..], - &["bench-ilp-bars-1m", "-5"][..], - &["bench-ilp-bars-1m", "10", "20"][..], &["--unknown"][..], &["export"][..], ] { @@ -265,33 +260,6 @@ fn bench_curate_fx_small_run_is_headless_deterministic_and_reports_rates() { assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes=")); } -#[test] -fn bench_ilp_bars_1m_small_run_is_headless_deterministic_and_reports_rates() { - let a = run(&["bench-ilp-bars-1m", "2000"]); - let b = run(&["bench-ilp-bars-1m", "2000"]); - assert!(a.status.success(), "{}", stderr(&a)); - assert!(b.status.success(), "{}", stderr(&b)); - assert!(stderr(&a).is_empty(), "unexpected stderr: {}", stderr(&a)); - assert!(stderr(&b).is_empty(), "unexpected stderr: {}", stderr(&b)); - - let text_a = stdout(&a); - let text_b = stdout(&b); - assert!(text_a.contains("curate-etl bench-ilp-bars-1m"), "{text_a}"); - assert!(text_a.contains("rows=2000 "), "{text_a}"); - assert!(text_a.contains("rows_encoded=2000 "), "{text_a}"); - assert!(text_a.contains("rows/s"), "{text_a}"); - assert!(text_a.contains("bytes/row"), "{text_a}"); - assert!(text_a.contains("MB/s"), "{text_a}"); - - let field = |s: &str, prefix: &str| { - s.split_whitespace() - .find(|t| t.starts_with(prefix)) - .map(str::to_owned) - }; - assert_eq!(field(&text_a, "bytes="), field(&text_b, "bytes=")); - assert_eq!(field(&text_a, "flushes="), field(&text_b, "flushes=")); -} - static CLI_TEST_DIR_SEQ: AtomicU64 = AtomicU64::new(0); struct CliTempDir { diff --git a/tools/curate-etl/tests/ilp_qa_contract.rs b/tools/curate-etl/tests/ilp_qa_contract.rs deleted file mode 100644 index 36f053ac..00000000 --- a/tools/curate-etl/tests/ilp_qa_contract.rs +++ /dev/null @@ -1,381 +0,0 @@ -//! QA contract tests for the QuestDB ILP v2 encoder and sharded writer (T-137 / M2.3c). -//! -//! Uses only the public crate API. Expected wire bytes are written out by hand (decimal -//! timestamps, hex IEEE-754 payloads) and shard routing is checked against an independently -//! written FNV-1a reference, so the encoder is not used as its own oracle. - -use std::io::{self, Write}; -use std::sync::{Arc, Mutex}; - -use curate_etl::{ - encode_bar_1m, encode_fx_1m, fnv1a_64, shard_for_fx_pair, shard_for_listing_id, Bar1mRow, - Fx1mRow, IlpEncodeError, IlpShardedWriter, IlpWriterError, IlpWriterOptions, - IntradaySession, BARS_1M_SOURCE_EOD, ILP_V2_DOUBLE_TYPE, TABLE_BARS_1M, TABLE_FX_1M, -}; - -fn bar(key: i32, ts: i64) -> Bar1mRow { - Bar1mRow { - key, - ts, - session_date: 20_000, - open: 1.0, - high: 2.0, - low: 0.5, - close: 1.5, - volume: 0.0, - session: IntradaySession::Rth, - source: BARS_1M_SOURCE_EOD, - } -} - -fn fx(pair: &'static str, ts: i64) -> Fx1mRow<'static> { - Fx1mRow { - pair, - ts, - open: 1.0, - high: 2.0, - low: 0.5, - close: 1.5, - source: "eod", - } -} - -type BarSetter = fn(&mut Bar1mRow, f64); -type FxSetter = fn(&mut Fx1mRow<'static>, f64); - -fn encoded_bar(row: &Bar1mRow, known_at: i64) -> Vec { - let mut v = Vec::new(); - encode_bar_1m(&mut v, row, known_at).unwrap(); - v -} - -/// Independent FNV-1a 64 reference (spec constants written inline). -fn ref_fnv1a(bytes: &[u8]) -> u64 { - bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, &b| { - (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3) - }) -} - -/// Sink that records every `write` call and flush, optionally failing a numbered write. -#[derive(Clone, Default)] -struct Rec { - writes: Arc>>>, - flushes: Arc>, - fail_write_call: Option, -} - -impl Rec { - fn writes(&self) -> Vec> { - self.writes.lock().unwrap().clone() - } - fn bytes(&self) -> Vec { - self.writes().concat() - } - fn flushes(&self) -> usize { - *self.flushes.lock().unwrap() - } -} - -impl Write for Rec { - fn write(&mut self, buf: &[u8]) -> io::Result { - let mut w = self.writes.lock().unwrap(); - if self.fail_write_call == Some(w.len()) { - return Err(io::Error::new(io::ErrorKind::BrokenPipe, "injected")); - } - w.push(buf.to_vec()); - Ok(buf.len()) - } - fn flush(&mut self) -> io::Result<()> { - *self.flushes.lock().unwrap() += 1; - Ok(()) - } -} - -#[test] -fn table_names_and_double_marker_match_contract() { - assert_eq!(TABLE_BARS_1M, "bars_1m"); - assert_eq!(TABLE_FX_1M, "fx_1m"); - assert_eq!(ILP_V2_DOUBLE_TYPE, 16); -} - -#[test] -fn fx_1m_golden_bytes_use_hand_written_little_endian_payloads() { - let row = Fx1mRow { - pair: "USD.CAD", - ts: 1_700_000_000_000_000, - open: 1.0, - high: 2.0, - low: 0.5, - close: -1.5, - source: "eod", - }; - let mut actual = Vec::new(); - encode_fx_1m(&mut actual, &row).unwrap(); - - let mut expected = b"fx_1m,pair=USD.CAD,source=eod ".to_vec(); - expected.extend_from_slice(b"open==\x10\x00\x00\x00\x00\x00\x00\xf0\x3f"); - expected.extend_from_slice(b",high==\x10\x00\x00\x00\x00\x00\x00\x00\x40"); - expected.extend_from_slice(b",low==\x10\x00\x00\x00\x00\x00\x00\xe0\x3f"); - expected.extend_from_slice(b",close==\x10\x00\x00\x00\x00\x00\x00\xf8\xbf"); - expected.extend_from_slice(b" 1700000000000000t\n"); - assert_eq!(actual, expected); -} - -#[test] -fn encoder_appends_to_existing_buffer_without_clearing_it() { - let mut buf = b"prior-line\n".to_vec(); - encode_bar_1m(&mut buf, &bar(1, 10), 20).unwrap(); - encode_fx_1m(&mut buf, &fx("EUR.USD", 30)).unwrap(); - - let mut expected = b"prior-line\n".to_vec(); - expected.extend(encoded_bar(&bar(1, 10), 20)); - let mut fx_line = Vec::new(); - encode_fx_1m(&mut fx_line, &fx("EUR.USD", 30)).unwrap(); - expected.extend(fx_line); - assert_eq!(buf, expected); -} - -#[test] -fn integer_extremes_encode_as_exact_decimal_without_overflow() { - // i32::MIN listing id, i64::MIN known_at, i64::MAX designated ts. - let row = bar(i32::MIN, i64::MAX); - let line = encoded_bar(&row, i64::MIN); - assert!(line.starts_with(b"bars_1m,listing_id=-2147483648,session=RTH,source=eod_unadj ")); - assert!(line.ends_with(b",known_at=-9223372036854775808t 9223372036854775807t\n")); - - // Zero designated ts and zero known_at are valid boundaries. - let zero = encoded_bar(&bar(0, 0), 0); - assert!(zero.starts_with(b"bars_1m,listing_id=0,")); - assert!(zero.ends_with(b",known_at=0t 0t\n")); - - let mut buf = Vec::new(); - encode_fx_1m(&mut buf, &fx("X", i64::MAX)).unwrap(); - assert!(buf.ends_with(b" 9223372036854775807t\n")); -} - -#[test] -fn extreme_finite_doubles_round_trip_bit_exactly() { - for v in [ - -0.0_f64, - f64::MIN_POSITIVE, - f64::from_bits(1), // smallest subnormal - f64::MAX, - f64::MIN, - f64::EPSILON, - ] { - let mut row = bar(5, 1); - row.low = v; - let line = encoded_bar(&row, 2); - let prefix = b",low==\x10"; - let pos = line.windows(prefix.len()).position(|w| w == prefix).unwrap() + prefix.len(); - let raw: [u8; 8] = line[pos..pos + 8].try_into().unwrap(); - assert_eq!(f64::from_le_bytes(raw).to_bits(), v.to_bits(), "value {v:e}"); - } -} - -#[test] -fn every_double_field_rejects_each_non_finite_value_atomically() { - let sentinel = b"keep".to_vec(); - let bar_fields: [(&str, BarSetter); 5] = [ - ("open", |r, v| r.open = v), - ("high", |r, v| r.high = v), - ("low", |r, v| r.low = v), - ("close", |r, v| r.close = v), - ("volume", |r, v| r.volume = v), - ]; - let fx_fields: [(&str, FxSetter); 4] = [ - ("open", |r, v| r.open = v), - ("high", |r, v| r.high = v), - ("low", |r, v| r.low = v), - ("close", |r, v| r.close = v), - ]; - for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { - for (name, set) in bar_fields { - let mut row = bar(1, 1); - set(&mut row, bad); - let mut buf = sentinel.clone(); - match encode_bar_1m(&mut buf, &row, 1) { - Err(IlpEncodeError::NonFiniteDouble { field, .. }) => assert_eq!(field, name), - other => panic!("bars_1m {name}={bad}: unexpected {other:?}"), - } - assert_eq!(buf, sentinel); - } - for (name, set) in fx_fields { - let mut row = fx("USD.CAD", 1); - set(&mut row, bad); - let mut buf = sentinel.clone(); - match encode_fx_1m(&mut buf, &row) { - Err(IlpEncodeError::NonFiniteDouble { field, .. }) => assert_eq!(field, name), - other => panic!("fx_1m {name}={bad}: unexpected {other:?}"), - } - assert_eq!(buf, sentinel); - } - } - - let mut buf = sentinel.clone(); - assert_eq!( - encode_fx_1m(&mut buf, &Fx1mRow { source: "", ..fx("USD.CAD", 1) }), - Err(IlpEncodeError::EmptySymbol { field: "source" }) - ); - assert_eq!(buf, sentinel); -} - -#[test] -fn routing_matches_independent_fnv1a_reference_and_published_vectors() { - // Published FNV-1a 64 test vectors. - assert_eq!(fnv1a_64(b""), 0xcbf2_9ce4_8422_2325); - assert_eq!(fnv1a_64(b"a"), 0xaf63_dc4c_8601_ec8c); - assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8); - - for shards in [1usize, 2, 3, 4, 7, 16] { - for id in [-1_000_000, -1, 0, 1, 42, 65_535, i32::MAX, i32::MIN] { - let expected = (ref_fnv1a(&id.to_le_bytes()) % shards as u64) as usize; - assert_eq!(shard_for_listing_id(id, shards), expected, "id {id} shards {shards}"); - } - for pair in ["USD.CAD", "EUR.USD", "a b", "caf\u{e9}"] { - let expected = (ref_fnv1a(pair.as_bytes()) % shards as u64) as usize; - assert_eq!(shard_for_fx_pair(pair, shards), expected); - } - } -} - -#[test] -fn fx_routing_hashes_raw_pair_not_escaped_wire_form() { - // A pair that needs escaping must route by its raw bytes. - let pair = "US D"; - let shards = 8; - let sinks: Vec = (0..shards).map(|_| Rec::default()).collect(); - let mut w = IlpShardedWriter::new(sinks.clone(), IlpWriterOptions::default()).unwrap(); - w.write_fx_1m(&fx(pair, 1)).unwrap(); - let stats = w.finish().unwrap(); - - let target = (ref_fnv1a(pair.as_bytes()) % shards as u64) as usize; - assert_eq!(stats.per_shard_rows[target], 1); - assert!(sinks[target].bytes().starts_with(b"fx_1m,pair=US\\ D,source=eod ")); -} - -#[test] -fn single_shard_writer_preserves_global_input_order() { - let sink = Rec::default(); - let mut w = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 7 }, - ) - .unwrap(); - let mut expected = Vec::new(); - for i in 0..50i64 { - let row = bar((i % 9) as i32 - 4, 1_000 + i); - expected.extend(encoded_bar(&row, 2_000 + i)); - w.write_bar_1m(&row, 2_000 + i).unwrap(); - } - let stats = w.finish().unwrap(); - assert_eq!(sink.bytes(), expected); - assert_eq!(stats.rows, 50); - assert_eq!(stats.per_shard_rows, vec![50]); - assert_eq!(stats.flushes, 8); // 7 full batches of 7 + one remainder of 1 - assert_eq!(stats.bytes, expected.len()); -} - -#[test] -fn row_and_byte_limits_hit_on_same_row_produce_one_flush() { - let row = bar(3, 100); - let len = encoded_bar(&row, 200).len(); - let sink = Rec::default(); - let mut w = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { max_batch_bytes: 2 * len, max_batch_rows: 2 }, - ) - .unwrap(); - for _ in 0..4 { - w.write_bar_1m(&row, 200).unwrap(); - } - let stats = w.finish().unwrap(); - let writes = sink.writes(); - assert_eq!(writes.len(), 2); - assert!(writes.iter().all(|b| b.len() == 2 * len)); - assert_eq!(stats.flushes, 2); - assert_eq!(sink.flushes(), 1); -} - -#[test] -fn bytes_and_rows_are_counted_only_after_a_successful_batch() { - // Interleave two shards; shard holding the failing sink fails on its 2nd batch. - let a = (1..1000).find(|&id| shard_for_listing_id(id, 2) == 0).unwrap(); - let b = (1..1000).find(|&id| shard_for_listing_id(id, 2) == 1).unwrap(); - let ok = Rec::default(); - let bad = Rec { fail_write_call: Some(1), ..Rec::default() }; - let mut w = IlpShardedWriter::new( - vec![ok.clone(), bad.clone()], - IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 2 }, - ) - .unwrap(); - for i in 0..3 { - w.write_bar_1m(&bar(a, i), i).unwrap(); - } - w.write_bar_1m(&bar(b, 1), 1).unwrap(); - w.write_bar_1m(&bar(b, 2), 2).unwrap(); // first batch on shard 1 succeeds - w.write_bar_1m(&bar(b, 3), 3).unwrap(); - let err = w.write_bar_1m(&bar(b, 4), 4).unwrap_err(); - assert!(matches!(err, IlpWriterError::Io { shard: 1, .. })); - assert!(err.to_string().contains("shard 1"), "{err}"); - assert!(std::error::Error::source(&err).is_some()); - - // Healthy shard got exactly its one full batch; buffered remainder is never sent. - assert_eq!(ok.writes().len(), 1); - assert_eq!(bad.writes().len(), 1); - assert!(matches!(w.finish(), Err(IlpWriterError::Poisoned { failed_shard: 1 }))); - assert_eq!(ok.writes().len(), 1); - assert_eq!(ok.flushes(), 0); -} - -#[test] -fn encode_error_inside_writer_leaves_pending_batch_and_stats_intact() { - let sink = Rec::default(); - let mut w = IlpShardedWriter::new( - vec![sink.clone()], - IlpWriterOptions { max_batch_bytes: 1 << 20, max_batch_rows: 3 }, - ) - .unwrap(); - let good1 = bar(9, 1); - let good2 = bar(9, 2); - let good3 = bar(9, 3); - w.write_bar_1m(&good1, 10).unwrap(); - let mut bad = bar(9, -5); - bad.close = 3.0; - assert!(matches!( - w.write_bar_1m(&bad, 10), - Err(IlpWriterError::Encode(IlpEncodeError::NegativeTimestamp { field: "ts", value: -5 })) - )); - w.write_bar_1m(&good2, 10).unwrap(); - w.write_bar_1m(&good3, 10).unwrap(); // third valid row hits the row limit - let writes = sink.writes(); - assert_eq!(writes.len(), 1); - let mut expected = encoded_bar(&good1, 10); - expected.extend(encoded_bar(&good2, 10)); - expected.extend(encoded_bar(&good3, 10)); - assert_eq!(writes[0], expected); - - let stats = w.finish().unwrap(); - assert_eq!(stats.rows, 3); - assert_eq!(stats.bytes, expected.len()); -} - -#[test] -fn bars_and_fx_rows_can_share_a_writer_with_independent_routing() { - let shards = 4; - let sinks: Vec = (0..shards).map(|_| Rec::default()).collect(); - let mut w = IlpShardedWriter::new(sinks.clone(), IlpWriterOptions::default()).unwrap(); - w.write_bar_1m(&bar(42, 1), 2).unwrap(); - w.write_fx_1m(&fx("USD.CAD", 3)).unwrap(); - let stats = w.finish().unwrap(); - assert_eq!(stats.rows, 2); - - let bar_shard = shard_for_listing_id(42, shards); - let fx_shard = shard_for_fx_pair("USD.CAD", shards); - let total: usize = sinks.iter().map(|s| s.bytes().len()).sum(); - assert_eq!(stats.bytes, total); - let bar_bytes = sinks[bar_shard].bytes(); - let fx_bytes = sinks[fx_shard].bytes(); - assert!(bar_bytes.windows(8).any(|w| w == b"bars_1m,")); - assert!(fx_bytes.windows(6).any(|w| w == b"fx_1m,")); -} diff --git a/tools/curate-etl/tests/posts_qa_contract.rs b/tools/curate-etl/tests/posts_qa_contract.rs deleted file mode 100644 index 06bb8a27..00000000 --- a/tools/curate-etl/tests/posts_qa_contract.rs +++ /dev/null @@ -1,332 +0,0 @@ -//! QA contract tests for the public `posts` builder (T-140 / M2.2b). -//! -//! Covers gaps left by the in-crate `posts_tests.rs`, checking against independent references -//! rather than the builder's own logic: -//! - seeded differential test against a naive reference (group by `spiel_id`, `max_by` winner -//! tuple, route, sort) on high-collision fixtures that force `known_at` ties; -//! - truncation test: every row visible at a cutoff in the full build is reproduced unchanged by a -//! build over only the inputs available before that cutoff; -//! - poison test: absurd future edits to existing posts never change what is visible before the -//! cutoff, except that the poisoned posts stop being visible (latest-only text, no recovery); -//! - an overflow row anywhere in the batch fails the whole build for every input order. - -use std::collections::{BTreeMap, BTreeSet}; - -use curate_etl::{build_posts, CeoPost, PostRow, PostsBuild, PostsError, POSTS_SOURCE_CEO}; - -/// Deterministic SplitMix64 PRNG (seeded; no wall clock). -struct Rng(u64); - -impl Rng { - fn next(&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() % n - } - - fn shuffle(&mut self, v: &mut [T]) { - for i in (1..v.len()).rev() { - let j = self.below(i as u64 + 1) as usize; - v.swap(i, j); - } - } -} - -const BASE_MS: i64 = 1_735_000_000_000; - -/// High-collision fixture: few ids, few channels, coarse timestamps, so ties on `known_at` and on -/// several tie-break fields are frequent. Includes invalid rows. -fn collision_fixture(seed: u64, n: usize, ids: u64) -> Vec> { - let mut rng = Rng(seed); - let bots = [ - Some("1"), - Some(" 1"), - Some("0"), - Some(""), - None, - Some("yes"), - ]; - let users = [None, Some("u_a"), Some("u_b")]; - let texts = ["a", "b", "c"]; - (0..n) - .map(|_| { - let spiel_id = match rng.below(25) { - 0 => String::new(), - _ => format!("sp_{}", rng.below(ids)), - }; - let timestamp_ms = match rng.below(20) { - 0 => 0, - 1 => -5, - _ => BASE_MS + 1_000 * rng.below(4) as i64, - }; - let edited_ms = match rng.below(4) { - 0 => None, - 1 => Some(timestamp_ms), - 2 => Some(timestamp_ms - 1_000), - _ => Some(BASE_MS + 1_000 * rng.below(6) as i64), - }; - CeoPost { - key: format!("ch_{}", rng.below(3)), - spiel_id, - timestamp_ms, - edited_ms, - bot: bots[rng.below(bots.len() as u64) as usize].map(str::to_string), - user_id: users[rng.below(users.len() as u64) as usize].map(str::to_string), - text: texts[rng.below(texts.len() as u64) as usize].to_string(), - } - }) - .collect() -} - -/// Independent reference written from the task's rules, not from `posts.rs`. -fn reference(rows: &[CeoPost]) -> (Vec, Vec, usize, usize) { - let mut rejected = 0usize; - let mut groups: BTreeMap> = BTreeMap::new(); - for r in rows { - if r.spiel_id.is_empty() || r.timestamp_ms <= 0 { - rejected += 1; - continue; - } - let posted_at = r.timestamp_ms * 1_000; - let known_at = r - .edited_ms - .map_or(r.timestamp_ms, |e| e.max(r.timestamp_ms)) - * 1_000; - groups.entry(r.spiel_id.clone()).or_default().push(PostRow { - key: r.key.clone(), - spiel_id: r.spiel_id.clone(), - posted_at, - known_at, - is_bot: r.bot.as_deref().map(str::trim) == Some("1"), - is_edited: r.edited_ms.is_some(), - user_id: r.user_id.clone(), - text: r.text.clone(), - source: POSTS_SOURCE_CEO, - }); - } - let mut dropped = 0usize; - let (mut wire, mut retail) = (Vec::new(), Vec::new()); - for (_, group) in groups { - dropped += group.len() - 1; - let winner = group - .into_iter() - .max_by(|a, b| { - ( - a.known_at, - a.posted_at, - a.is_edited, - a.is_bot, - &a.key, - &a.user_id, - &a.text, - ) - .cmp(&( - b.known_at, - b.posted_at, - b.is_edited, - b.is_bot, - &b.key, - &b.user_id, - &b.text, - )) - }) - .unwrap(); - if winner.is_bot { - wire.push(winner); - } else { - retail.push(winner); - } - } - let order = |r: &PostRow| (r.key.clone(), r.known_at, r.spiel_id.clone()); - wire.sort_by_key(order); - retail.sort_by_key(order); - (wire, retail, dropped, rejected) -} - -#[test] -fn seeded_differential_matches_naive_reference_on_high_collision_fixtures() { - for seed in 0..40u64 { - let input = collision_fixture(0xC0FF_EE00 + seed, 120, 8); - let built = build_posts(input.clone()).expect("fixture has no overflow"); - let (wire, retail, dropped, rejected) = reference(&input); - - assert_eq!(built.newswire, wire, "seed {seed}: newswire mismatch"); - assert_eq!(built.retail, retail, "seed {seed}: retail mismatch"); - assert_eq!(built.stats.duplicates_dropped, dropped, "seed {seed}"); - assert_eq!(built.stats.rejected_invalid, rejected, "seed {seed}"); - assert_eq!(built.stats.input, input.len()); - assert_eq!( - built.stats.input, - built.stats.newswire - + built.stats.retail - + built.stats.duplicates_dropped - + built.stats.rejected_invalid - ); - let valid = input - .iter() - .filter(|r| !r.spiel_id.is_empty() && r.timestamp_ms > 0); - assert_eq!( - built.stats.edited, - valid.clone().filter(|r| r.edited_ms.is_some()).count() - ); - assert_eq!( - built.stats.edited_before_posted, - valid - .filter(|r| r.edited_ms.is_some_and(|e| e < r.timestamp_ms)) - .count() - ); - } -} - -/// Ordered projection of a `PostRow` (which is not `Ord`) for set comparisons. -type RowKey = (String, String, i64, i64, bool, bool, Option, String); - -fn row_key(r: &PostRow) -> RowKey { - ( - r.spiel_id.clone(), - r.key.clone(), - r.posted_at, - r.known_at, - r.is_bot, - r.is_edited, - r.user_id.clone(), - r.text.clone(), - ) -} - -fn visible(build: &PostsBuild, cutoff_us: i64) -> BTreeSet { - build - .newswire - .iter() - .chain(build.retail.iter()) - .filter(|r| r.known_at < cutoff_us) - .map(row_key) - .collect() -} - -fn known_at_us(r: &CeoPost) -> i64 { - r.edited_ms - .map_or(r.timestamp_ms, |e| e.max(r.timestamp_ms)) - * 1_000 -} - -#[test] -fn truncation_rows_visible_at_cutoff_are_reproduced_from_pre_cutoff_inputs_only() { - for seed in 0..20u64 { - let input = collision_fixture(0x7A0C_0000 + seed, 150, 60); - let full = build_posts(input.clone()).unwrap(); - assert!(!visible(&full, (BASE_MS + 2_000) * 1_000).is_empty()); - for step in 0..=6i64 { - let cutoff_us = (BASE_MS + 1_000 * step) * 1_000; - let truncated_input: Vec<_> = input - .iter() - .filter(|r| r.timestamp_ms > 0 && known_at_us(r) < cutoff_us) - .cloned() - .collect(); - let truncated = build_posts(truncated_input).unwrap(); - - let full_visible = visible(&full, cutoff_us); - let trunc_visible = visible(&truncated, cutoff_us); - // Every row the full build exposes before the cutoff must be derivable from data - // available before the cutoff (no future-dependent winner selection). - assert!( - full_visible.is_subset(&trunc_visible), - "seed {seed} cutoff step {step}: full build exposes rows not reproducible pre-cutoff: {:?}", - full_visible.difference(&trunc_visible).collect::>() - ); - // Truncated build never exposes anything at/after the cutoff. - assert!(truncated - .newswire - .iter() - .chain(truncated.retail.iter()) - .all(|r| r.known_at < cutoff_us)); - } - } -} - -#[test] -fn poison_future_edits_never_change_pre_cutoff_view_except_hiding_poisoned_ids() { - let cutoff_us = (BASE_MS + 3_000) * 1_000; - let far_future_ms = BASE_MS + 10 * 365 * 86_400_000; - for seed in 0..20u64 { - let input = collision_fixture(0x9015_0000 + seed, 120, 60); - let base = build_posts(input.clone()).unwrap(); - let base_visible = visible(&base, cutoff_us); - - // Poison half of the ids that are visible before the cutoff with an absurd future edit - // flagged as a wire release in a different channel. - let poisoned: BTreeSet = base_visible - .iter() - .map(|r| r.0.clone()) - .enumerate() - .filter(|(i, _)| i % 2 == 0) - .map(|(_, id)| id) - .collect(); - assert!( - !poisoned.is_empty(), - "seed {seed}: fixture must expose pre-cutoff rows" - ); - let mut poisoned_input = input.clone(); - for id in &poisoned { - poisoned_input.push(CeoPost { - key: "ch_poison".to_string(), - spiel_id: id.clone(), - timestamp_ms: BASE_MS, - edited_ms: Some(far_future_ms), - bot: Some("1".to_string()), - user_id: Some("poison".to_string()), - text: "POISON: future restatement".to_string(), - }); - } - let mut rng = Rng(seed); - rng.shuffle(&mut poisoned_input); - let after = build_posts(poisoned_input).unwrap(); - let after_visible = visible(&after, cutoff_us); - - let expected: BTreeSet<_> = base_visible - .iter() - .filter(|r| !poisoned.contains(&r.0)) - .cloned() - .collect(); - assert_eq!(after_visible, expected, "seed {seed}"); - assert!(after_visible.iter().all(|r| !r.7.starts_with("POISON"))); - assert_eq!( - after.stats.duplicates_dropped, - base.stats.duplicates_dropped + poisoned.len() - ); - } -} - -#[test] -fn overflow_row_anywhere_fails_build_for_every_input_order() { - let mut input = collision_fixture(0x0F10_0001, 40, 8); - input.push(CeoPost { - key: "ch_x".to_string(), - spiel_id: "sp_overflow".to_string(), - timestamp_ms: BASE_MS, - edited_ms: Some(i64::MAX / 1_000 + 1), - bot: None, - user_id: None, - text: "overflow".to_string(), - }); - let mut rng = Rng(7); - for _ in 0..16 { - let mut shuffled = input.clone(); - rng.shuffle(&mut shuffled); - let err = build_posts(shuffled).expect_err("overflow must fail the build"); - assert_eq!( - err, - PostsError::TimestampOverflow { - spiel_id: "sp_overflow".to_string(), - field: "edited_ms", - timestamp_ms: i64::MAX / 1_000 + 1, - } - ); - } -} diff --git a/tools/curate-etl/tests/session_close_qa_contract.rs b/tools/curate-etl/tests/session_close_qa_contract.rs index d0a04c43..7c93a8d4 100644 --- a/tools/curate-etl/tests/session_close_qa_contract.rs +++ b/tools/curate-etl/tests/session_close_qa_contract.rs @@ -204,10 +204,7 @@ fn pre_1976_divergent_emergency_dst_years_and_post_2030_are_out_of_range() { epoch_day, min_supported, max_supported, - } = err - else { - panic!("expected SessionCloseError::DateOutOfRange, got {err:?}"); - }; + } = err; assert_eq!(epoch_day, d); assert_eq!(min_supported, SESSION_CLOSE_MIN_SUPPORTED_DATE); assert_eq!(max_supported, SESSION_CLOSE_MAX_SUPPORTED_DATE);