diff --git a/Cargo.lock b/Cargo.lock index 4fc5e43f..6d77dd3a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,21 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ahash" +version = "0.8.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3019c0b8d883a8a17df3129e417ef463c087807d245e8881a31d583dee1c0519" +dependencies = [ + "cfg-if", + "const-random", + "getrandom 0.3.4", + "getrandom 0.4.3", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -89,6 +104,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -112,6 +129,25 @@ dependencies = [ "windows-link", ] +[[package]] +name = "const-random" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38d4bb3e79c716fd0330d8da84171b0135e59e01076e99f22b75a64c56e952c" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d66bb491e9fc48cb3fed9d57df886880a751d540d645ebc86b6d9d35b8fa8457" +dependencies = [ + "getrandom 0.4.3", + "tiny-keccak", +] + [[package]] name = "convert_case" version = "0.6.0" @@ -183,6 +219,12 @@ version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + [[package]] name = "ctor" version = "0.2.9" @@ -196,6 +238,9 @@ dependencies = [ [[package]] name = "curate-etl" version = "0.1.0" +dependencies = [ + "parquet", +] [[package]] name = "dashmap" @@ -204,7 +249,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" dependencies = [ "cfg-if", - "hashbrown", + "hashbrown 0.14.5", "lock_api", "once_cell", "parking_lot_core", @@ -223,7 +268,7 @@ dependencies = [ "napi", "napi-build", "napi-derive", - "num-bigint", + "num-bigint 0.4.6", "num-rational", "num-traits", "parking_lot", @@ -299,16 +344,47 @@ checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 5.3.0", "wasip2", ] +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "wasm-bindgen", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -339,6 +415,16 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.107" @@ -556,6 +642,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -580,7 +676,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" dependencies = [ - "num-bigint", + "num-bigint 0.4.6", "num-integer", "num-traits", ] @@ -624,6 +720,25 @@ dependencies = [ "windows-link", ] +[[package]] +name = "parquet" +version = "60.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6701f0dd63f5ee23a0f1f2865ff76825c301759d6ab649e3e5686cc32d066957" +dependencies = [ + "ahash", + "bytes", + "chrono", + "half", + "hashbrown 0.17.2", + "num-bigint 0.5.1", + "num-integer", + "num-traits", + "seq-macro", + "twox-hash", + "zstd", +] + [[package]] name = "paste" version = "1.0.15" @@ -636,6 +751,12 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -669,6 +790,12 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + [[package]] name = "rand" version = "0.8.8" @@ -790,6 +917,12 @@ version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + [[package]] name = "serde" version = "1.0.229" @@ -981,6 +1114,15 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + [[package]] name = "tokio" version = "1.54.1" @@ -1066,6 +1208,12 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + [[package]] name = "typenum" version = "1.20.1" @@ -1102,6 +1250,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -1270,3 +1424,31 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zstd" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "8.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.2.0+zstd.1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index febcbba3..f61e3161 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -63,3 +63,131 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/sto - **Return correlation:** Computes two-pass centered Pearson correlation of consecutive log returns in a canonical common currency (converting CAD closes to USD via `cadClose / usdCad` for `CAD`/`USD` pairs so correlation is orientation-symmetric and unaffected by FX moves on flat USD prices), rounded to `4` decimal places (`provider_mapping.price_corr NUMERIC(5,4)`). Returns `null` when fewer than `3` returns exist or either series has zero variance. - **Strict verdict priority & defaults:** `unsupported_currency_pair` -> `insufficient_data` (`usableDates < 5` or `priceCorr === null`) -> `ratio_mismatch` (`medianRatio` outside inclusive `[1 - 0.02, 1 + 0.02]`) -> `low_correlation` (`priceCorr < 0.9`) -> `confirmed`. Malformed candidate pairs or endpoints never abort the batch; each malformed slot is counted in `stats.invalidPairs` and recorded with a deterministic non-confirming verdict so verdict counts always reconcile with `pairsIn`. - **Conflicts:** Emits `resolution_conflict`-shaped records only for `ratio_mismatch` (`price_ratio_mismatch`) and `low_correlation` (`price_low_correlation`), keyed to `left.source` and `left.sourceId` with a JSON-serializable `detail` payload. + +## Security Master Persistence (`persistSecurityMaster`) +`apps/stock/data-pipeline/src/security-master/persist.ts` persists in-memory Pass 3 (Stage A/B), Pass 5 (`resolution_conflict`), and Pass 6 (`delisting-chains`) results into the `master` track PostgreSQL tables inside a single transaction guarded by `pg_advisory_xact_lock(0x534d5053, hashtext(current_schema()))`: + +- **Permanent IDs & idempotency:** Upserts `instrument` by `primary_isin` and resolves `listing` by `(instrument_id, mic, ticker_root, class_suffix, currency)` without ever changing or deleting an existing `instrument_id` or `listing_id`. +- **Override precedence:** After upserting `provider_mapping` (`tier1_isin = 0.990`, `tier2_cusip = 0.950`, `tier3_ticker_span = 0.800`), unconditionally enforces every row in `override` (`method = 'override'`, `confidence = 1.000`, `price_corr = NULL`) so re-runs with conflicting matcher output cannot overwrite director overrides. +- **Stale fallback cleanup:** When a run supplies only dated `provider_mapping` rows (`validFrom !== '1900-01-01'`) for a `(source, source_id)`, any leftover `1900-01-01` fallback row for that pair is deleted in batched `UNNEST` statements within the same transaction and counted in `providerMappingsDeletedStaleFallback`. Rows with `method = 'override'`, rows protected by an `override` entry at `1900-01-01`, dated rows, and `(source, source_id)` pairs absent from the run are never deleted. +- **No guessing:** Instruments with null/blank `canonicalName` or absent from `securityTypeByIsin`, and listings with an unknown `mic`, are skipped and counted per reason along with all dependent listings, mappings, Pass 6 outcomes, and continuities. +- **Batched writes & local benchmark:** All bulk reads/writes use parameterised `UNNEST` batches (default/max chunk size `5000`). Run the PostgreSQL integration suite and fixed-seed 20,000-instrument / 20,000-listing / 60,000-mapping benchmark against an isolated `stock_bot_safety_*` schema with: + +```bash +bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts +``` + +- **Recorded baseline (`2026-11-28`, host PostgreSQL isolated `stock_bot_safety_*` schema, default `chunkSize = 5000`):** + - Workload: `20,000` instruments, `20,000` listings, `60,000` provider mappings (`100,000` core rows; `140,000` total rows including `20,000` `instrument_identifier_history` and `20,000` `listing_symbol_history` rows). + - Observed end-to-end test wall time: `2.20s` (`2200.02ms`, reported by `bun test`; includes isolated schema migration, synthetic fixture construction, `persistSecurityMaster`, and `COUNT(*)` verification because `test/setup.ts` suppresses `console.info`). + - Throughput (conservative lower bound over full test wall time): `45,454` core rows/s (`100,000 / 2.20002s`), `63,636` total rows/s (`140,000 / 2.20002s`). + +## Read-Only Source-Symbol Readers (`source-symbol-readers.ts`) +`apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts` adapts raw `eodSymbols`, `ibSymbols`, `qmSymbols`, `ceoSymbols`, and `eodSymbolChange` documents into deterministic Stage A (`StageASourceRecord`) and Stage B (`StageBEodListingInput`, `StageBIbContractInput`, `StageBTickerSourceInput`, `StageBSymbolChangeInput`) inputs via `readSecurityMasterSources`: + +- **Read-only streaming contract:** `ReadOnlySourceSymbolReader` exposes strictly `isReadOnly()` and `find()` returning an incremental `AsyncIterable` (rejecting buffered array results). Production callers adapt a read-only `MongoDBClient` via `createReadOnlyMongoSourceSymbolReader(client)`, which streams through `collection.find(filter, options)` (`FindCursor`, never `cursor.toArray()`), closes cursors in `finally`, projects `_id: 0` (omitting `qmSymbols.profile`/`symbolInfo`, projecting `eodSymbolChange.effective`), and pushes down `$or` country/venue filters preserving normalized spellings and venue fallbacks (default `['US', 'CA']`). +- **Provider & Pass 1 rules enforced:** `createExchangeSourceLookup` layers reviewed US+CA venue mappings (`REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS`) on top of the 17-row Pass 1 baseline (`EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS`) with caller/Pass 1 rows overriding. Readers exclude `eodSymbols` `Exchange="NMFQS"` mutual funds, preserve `delisted: true` and duplicate QM `(symbol, exchange)` pairs (`VOY:CNX` + `VOY:CC`), set Stage A country strictly to issuer country (never listing country), never use IB ATS `exchangeId` venues (`AEQLIT`, `OTCLNKECN`, etc.) as listing MIC or `primaryExchange`, strip CEO `.TO`/`.V` suffixes with Stage B double-strip protection, parse `eodSymbolChange.effective` (alongside `effectiveDate`/`date`), null invalid ISIN/CUSIP check digits without throwing, and reconcile `docsRead === emitted + sum(skips)` per collection. +- **Local synthetic benchmark:** Run the unit suite and fixed-seed 368,000-doc synthetic benchmark (`300,000` `eodSymbols` + `50,000` `qmSymbols` + `18,000` `ibSymbols`, zero DB connections) with: + +```bash +bun test test/unit/security-master-source-symbol-readers.test.ts +``` + +- **Recorded baseline (`2026-11-28`, local sandbox, in-memory async cursor fake reader):** + - Workload: `368,000` synthetic docs (`300,000` `eodSymbols`, `50,000` `qmSymbols`, `18,000` `ibSymbols`) including NMFQS exclusion, country normalization, ISIN/CUSIP check-digit validation, ticker parsing, and deterministic ASCII sorting. + - Observed throughput: `754,047 docs/s` (`488.0 ms` wall time, floor `>= 25,000 docs/s`). + +## EOD Security-Type Classifier (`security-type.ts`) +`apps/stock/data-pipeline/src/security-master/security-type.ts` maps raw EODHD `Type` strings into the canonical PostgreSQL `instrument.security_type` enum (`SecurityType`) and builds the `securityTypeByIsin` map required by `persistSecurityMaster` (wired automatically through `readEodSymbols` and `readSecurityMasterSources`). + +- **Mapping table (`EOD_SECURITY_TYPE_MAP`, trimmed, whitespace-collapsed, case-insensitive):** + +| EODHD `Type` | Canonical `SecurityType` | +| --- | --- | +| `Common Stock` | `common` | +| `Preferred Stock` | `preferred` | +| `ETF` | `etf` | +| `Unit`, `Units` | `unit` | +| `Warrant`, `Warrants` | `warrant` | +| `Right`, `Rights` | `right` | +| `CDR` | `cdr` | +| `Currency`, `Forex`, `FX` | `fx` | + +- **Published-vocabulary & no-guess rule:** Because QA MongoDB is unreachable from the agent sandbox, the table is based on the published EODHD `Type` vocabulary. Non-equity-like values (`FUND`, `Mutual Fund`, `Bond`, `Notes`, `INDEX`, etc.), blanks, non-strings, and unmapped strings return `null` and are never guessed from ticker suffixes or company names. A non-string `Type` on an `eodSymbols` document does not skip the document from Stage A/B — it is counted under `securityTypeStats.missingType`. +- **Stage A membership & raw vocabulary diagnostics:** `readEodSymbols` / `readSecurityMasterSources` build the loader-facing `securityTypeByIsin` map, `securityTypeConflicts`, and `securityTypeLoaderStats` strictly from EOD rows accepted as Stage A instrument members (`buildSecurityTypeByIsinForStageA`), so rows quarantined by Stage A (`isin_cusip_mismatch`, `duplicate_source_id`) can neither supply nor veto a valid instrument's security type. At the same time, `securityTypeStats` and `unknownSecurityTypes` reconcile over **all** emitted EOD rows (also retained in `securityTypeRecords`), so unmapped vocabulary on quarantined rows is never silently hidden. +- **Reviewing unmapped values & conflicts:** After a real security-master run, inspect `unknownSecurityTypes` (sorted by count descending, then ASCII, reconciling with `securityTypeStats.unknownType` across all emitted EOD rows) for any newly observed provider strings that should be added to `EOD_SECURITY_TYPE_MAP`, and inspect `securityTypeConflicts` (ISINs omitted from `securityTypeByIsin` because multiple Stage A-accepted EOD documents disagreed on their classified type; capped by `maxSecurityTypeConflicts`, default `200`, reconciling with `securityTypeLoaderStats.isinsConflicting` and `conflictsTruncated`). +- **Local synthetic benchmark:** Run the unit suite and fixed-seed 300,000-record synthetic benchmark (zero DB connections) with: + +```bash +bun test test/unit/security-master-security-type.test.ts +``` + +- **Recorded baseline (`2026-11-28`, local sandbox, zero DB connections):** + - Workload: `300,000` synthetic EOD records (`100,000` distinct ISIN buckets, mixed mapped/unknown/missing types, and `20` conflicting ISINs exercising Pass 2 conflict collection). + - Observed throughput: `4,277,092 records/s` (`70.1 ms` wall time, floor `>= 100,000 records/s`). + +## Security-Master Run Composer (`run.ts`) +`apps/stock/data-pipeline/src/security-master/run.ts` provides a pure, zero-I/O entry point (`composeSecurityMasterRun`) that wires in-memory source-symbol reader outputs and observed bar spans end to end without touching MongoDB, PostgreSQL, or the filesystem: + +`sources + barSpans -> matchInstrumentsStageA -> attachBarSpansToStageBInput -> matchListingsStageB -> linkDelistingChains (Pass 6) -> optional crossCheckPrices (Pass 4) -> buildMatchReport (+ Markdown / CSV / override-template SQL) + PersistSecurityMasterInput` + +- **Pure & deterministic:** Contains zero I/O imports and zero wall-clock calls. Shuffling any input array or `securityTypeByIsin` map insertion order produces byte-identical Markdown, CSV, override-template SQL, and deep-equal `PersistSecurityMasterInput`. +- **Explicit Pass 4 skipping:** When `sampleCloses` is omitted or empty, Pass 4 is marked `skipped` in both `stats.pass4` and the rendered Markdown (`- Status: skipped (no sample closes supplied)`), `pass4` is `null`, and `persistInput.pass4` is omitted — it is never reported as passed. +- **Malformed-record resilience & reconciliation:** Pre-pass sanitizers skip and count malformed or sparse entries across every input array without aborting the run, and every step reconciles `recordsIn === resolved + unresolved + skipped` with `report.conflicts.length === stageA + stageB + pass4 + pass6`. +- **Local synthetic benchmark:** Run the unit suite and fixed-seed 100,000-record synthetic benchmark (zero DB connections) with: + +```bash +bun test test/unit/security-master-run.test.ts +``` + +- **Recorded baseline (`2026-11-28`, local sandbox, zero DB connections):** + - Workload: `100,000` synthetic source records (`50,000` EOD + `25,000` IB + `25,000` QM, `75,000` bar spans, `50,000` security types) composed end to end through Stage A, Stage B, Pass 6, Pass 4 pair derivation, MatchReport + Markdown/CSV/SQL rendering, and `PersistSecurityMasterInput` assembly. + - Observed throughput: `208,502 records/s` (`479.6 ms` wall time, asserted floor `>= 10,000 records/s`). + +## Running the security master +`apps/stock/data-pipeline/src/security-master/run-security-master.ts` runs the full read-only MongoDB security-master pipeline (`read-exchanges` -> `read-sources` -> `compute-bar-spans` -> `composeSecurityMasterRun`) and writes deterministic report artifacts, with opt-in PostgreSQL persistence via `--persist`. + +### Dry run (read-only MongoDB, zero PostgreSQL connections) +```bash +MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ + bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts \ + --as-of 2026-01-15 \ + --out-dir ./tmp/security-master-report +``` + +- **Scope of `--as-of `:** `--as-of` sets the calendar reference date for Pass 6 delisting classification (active grace window vs. delisted outcome). It does **not** take a historical point-in-time snapshot of MongoDB — source symbol records and bar spans are read from the current collections, so the report can incorporate provider observations recorded after `--as-of`. + +### Persist to isolated dev PostgreSQL (`localhost:5433/trading_bot_dev`) +Apply the `master` track migrations to isolated dev PostgreSQL first (passing the dev target variables explicitly so a QA-configured shell cannot migrate QA): + +```bash +NODE_ENV=development \ +POSTGRES_HOST=localhost \ +POSTGRES_PORT=5433 \ +POSTGRES_DATABASE=trading_bot_dev \ + bun run db:migrate --track master +``` + +Then run the CLI with `--persist` against the same isolated dev PostgreSQL target: + +```bash +NODE_ENV=development \ +MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ +POSTGRES_HOST=localhost \ +POSTGRES_PORT=5433 \ +POSTGRES_DATABASE=trading_bot_dev \ + bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts \ + --as-of 2026-01-15 \ + --out-dir ./tmp/security-master-report \ + --persist +``` + +- **Safety guards:** MongoDB is always opened with `mongoReadOnly: true` via `MONGODB_READ_URI`. Without `--persist`, no PostgreSQL client is constructed. With `--persist`, `assertSecurityMasterPersistSafety()` runs `assertEnvironmentSafety()` (with `STOCK_BOT_ALLOW_DEV_ON_QA_DB` stripped) and enforces `NODE_ENV=development` against an isolated dev PostgreSQL database (`*_dev` / `stock_bot_safety*`), blocking `NODE_ENV=qa` and QA PostgreSQL (`localhost:5432/trading_bot`) before any PostgreSQL client is created. +- **Pass 4 status:** Pass 4 cross-sectional price cross-check input (`sampleCloses` / `fxRates`) is **not yet wired** into this CLI; `composeSecurityMasterRun` is invoked without sample closes and Pass 4 is explicitly reported as `skipped` (`pass4: null`). + +### Output files (`--out-dir`) +All four files are deterministic and byte-identical for identical inputs (no wall-clock timestamps or output paths): +- `match-report.md` — Human-readable match report covering exchange coverage, per-source/per-country resolution, unresolved breakdowns, Pass 4 (`skipped`), Pass 6 delisting chains, and conflicts. +- `conflicts.csv` — Unified deterministic conflict export across Stage A, Stage B, Pass 4, and Pass 6. +- `override-template.sql` — Commented SQL template for director-reviewed `override` entries. +- `run-stats.json` — Canonical ASCII-key-sorted JSON summary of exchange, reader, security-type, bar-span, composer, and report stats (`pass4Wired: false`). diff --git a/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts b/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts index de857f66..24ec1fab 100644 --- a/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts +++ b/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts @@ -272,6 +272,107 @@ export const EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMapRow[] })) ); +/** + * Reviewed US + Canada provider venue mappings supplementing the immutable + * 17-row Pass 1 baseline seed (`35-security-master-exchange-seed.sql`). + * Covers EOD US sub-exchanges under composite `eodExchange="US"` (`NASDAQ`, + * `NYSE`, `PINK`, etc.), EOD CA venues, IB primary venues, and QuoteMedia + * US/CA venue codes (whose `qmExchanges` collection carries no OperatingMICs), + * sorted by `(source, sourceCode)`. + */ +export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMapRow[] = + Object.freeze( + [ + // EOD US + CA primary venues + { source: 'eod' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'CN', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'eod' as const, sourceCode: 'IEX', role: 'primary_venue' as const, mic: 'IEXG', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' }, + { source: 'eod' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'NYSE ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'NYSE MKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'OTC', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'OTCGREY', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'OTCMKTS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'OTCQB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'TO', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' }, + { source: 'eod' as const, sourceCode: 'V', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + // IB US + CA venues (additional ATS/routing venues live in EXPLICIT_EXCHANGE_SOURCE_RULES) + { source: 'ib' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'EDGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'ISLAND', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' }, + { source: 'ib' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'PURE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'ib' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' }, + { source: 'ib' as const, sourceCode: 'VALUE', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'VENTURE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + // QuoteMedia US + CA venues (qmExchanges has 0% OperatingMIC) + { source: 'qm' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'AQL', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'ARC', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'ASE', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'BTS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'BZX', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'CC', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CCQ TSX', role: 'composite' as const, mic: null, countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CCQ TSXV', role: 'composite' as const, mic: null, countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CDX', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CNQ', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CNX', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CSE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CVE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'EDGA', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'EDGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'EGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'IEX', role: 'primary_venue' as const, mic: 'IEXG', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NCM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'NEOE', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'NGM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NGS', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NSD', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NSQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NYE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NYS', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NYSE AMERICAN', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NYSEMKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OBB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OTC', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OTCBB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OTCMKTS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OTCQB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'PCX', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'PNK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'QB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'QX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'TOR', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'TSV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'TSX', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'TSXV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'VNX', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + ].map(rule => ({ + ...rule, + method: 'explicit_rule' as const, + reviewedBy: 'reviewed_us_ca_venues', + })) + ); + function makeRuleKey(source: ExchangeSource, sourceCode: string): string { return `${source}\u0000${sourceCode}`; } diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index f47fe4bf..7fd47256 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -32,6 +32,7 @@ export { isExchangeSource, ISO_EXCHANGE_SEEDS, normalizeRawExchangeDoc, + REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS, type BoardLotPolicy, type ClassificationMethod, type ClassifySourceExchangesOptions, @@ -110,6 +111,58 @@ export { type StageBUnresolvedRecord, } from './listing-stage-b'; +export { + buildMatchReport, + DEFAULT_MAX_CONFLICT_ROWS, + DEFAULT_MIN_RESOLVED_PCT, + DEFAULT_OVERRIDE_VALID_FROM, + EXCLUDED_BY_DESIGN_STAGE_B_REASONS, + generateOverrideSeedSql, + generateOverrideTemplateSql, + MATCH_REPORT_PASSES, + renderConflictsCsv, + renderMatchReportMarkdown, + sourceCountryKey, + type BuildMatchReportOptions, + type ConflictCountRow, + type CountryResolutionSummary, + type DelistingChainSummary, + type ExchangeCoverageSummary, + type ExcludedByDesignStageBReason, + type MatchReport, + type MatchReportExitThresholds, + type MatchReportInput, + type MatchReportPass, + type OverrideSeedRow, + type PriceCrossCheckSummary, + type RenderMatchReportMarkdownOptions, + type SourceCountryLookup, + type SourceResolutionSummary, + type UnifiedConflictRow, + type UnresolvedBreakdown, + type UnresolvedBreakdownRow, +} from './match-report'; + +export { + canonicalizeJsonValue, + DEFAULT_PERSIST_CHUNK_SIZE, + DEFAULT_VALID_FROM, + formatListingNaturalKey, + MAX_PERSIST_CHUNK_SIZE, + persistSecurityMaster, + PROVIDER_MAPPING_CONFIDENCE, + SECURITY_MASTER_PERSIST_LOCK_NAMESPACE, + SECURITY_TYPES, + stableJsonStringify, + type PersistSecurityMasterInput, + type PersistSecurityMasterOptions, + type PersistSecurityMasterResult, + type PersistSecurityMasterSkippedByReason, + type SecurityMasterQueryable, + type SecurityMasterQueryResult, + type SecurityType, +} from './persist'; + export { crossCheckPrices, DEFAULT_MIN_COMMON_DATES, @@ -137,3 +190,111 @@ export { type SampleCloseRecord, type SelectSampleDatesOptions, } from './price-cross-check'; + +export { + attachBarSpansToStageBInput, + composeSecurityMasterRun, + derivePass4CandidatePairs, + deriveSourceCountries, + filterSampleClosesByMappingBounds, + type AttachBarSpansMalformedCounts, + type AttachBarSpansResult, + type BarSpansStepStats, + type ComposeConflictTotals, + type ComposeMalformedInputStats, + type ComposeSecurityMasterPass6Options, + type ComposeSecurityMasterRunInput, + type ComposeSecurityMasterRunOptions, + type ComposeSecurityMasterRunResult, + type ComposeSecurityMasterRunStats, + type ObservedBarSpansInput, + type Pass4ComposeStepStats, + type Pass6ComposeStepStats, + type ReconcilingStepStats, + type StageAComposeStepStats, + type StageBComposeStepStats, +} from './run'; + +export { + assertSecurityMasterPersistSafety, + formatRunSecurityMasterSummary, + parseRunSecurityMasterArgs, + RUN_SECURITY_MASTER_USAGE, + runSecurityMaster, + SECURITY_MASTER_OUTPUT_FILES, + type ParsedRunSecurityMasterArgs, + type RunSecurityMasterDeps, + type RunSecurityMasterOptions, + type RunSecurityMasterOutput, + type SecurityMasterPostgresHandle, +} from './run-security-master'; + +export { + buildSecurityTypeByIsin, + buildSecurityTypeByIsinForStageA, + classifyEodSecurityType, + DEFAULT_MAX_SECURITY_TYPE_CONFLICTS, + EOD_SECURITY_TYPE_MAP, + type BuildSecurityTypeByIsinOptions, + type BuildSecurityTypeByIsinResult, + type SecurityTypeClassificationStats, + type SecurityTypeConflict, + type SecurityTypeInputRecord, + type UnknownSecurityTypeCount, +} from './security-type'; + +export { + adaptCeoSymbolDoc, + adaptEodSymbolChangeDoc, + adaptEodSymbolDoc, + adaptIbSymbolDoc, + adaptQmSymbolDoc, + CEO_SYMBOLS_PROJECTION, + createExchangeSourceLookup, + createReadOnlyMongoSourceSymbolReader, + DEFAULT_SOURCE_COUNTRIES, + EOD_SYMBOL_CHANGE_PROJECTION, + EOD_SYMBOLS_PROJECTION, + IB_SYMBOLS_PROJECTION, + normalizeCountryIso2, + QM_SYMBOLS_PROJECTION, + readCeoSymbols, + readEodSymbolChanges, + readEodSymbols, + readIbSymbols, + readQmSymbols, + readSecurityMasterSources, + SOURCE_SYMBOL_COLLECTIONS, + type AdaptCeoSymbolContext, + type AdaptEodSymbolChangeContext, + type AdaptEodSymbolChangeResult, + type AdaptEodSymbolContext, + type AdaptEodSymbolResult, + type AdaptIbSymbolContext, + type AdaptIbSymbolResult, + type AdaptQmSymbolContext, + type AdaptTickerSourceResult, + type CreateExchangeSourceLookupOptions, + type ExchangeSourceLookup, + type ExchangeSourceLookupEntry, + type MongoDBClientSourceSymbolReaderCheck, + type ReadEodSymbolChangesResult, + type ReadEodSymbolsResult, + type ReadIbSymbolsResult, + type ReadOnlyMongoCollectionClient, + type ReadOnlySourceSymbolCollection, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type ReadSecurityMasterSourcesOptions, + type ReadSourceCollectionOptions, + type ReadTickerSourcesResult, + type SecurityMasterSourcesResult, + type SecurityMasterSourcesStats, + type SecurityMasterStageBSourceInput, + type SourceCollectionReadStats, + type SourceSymbolCollectionKey, + type SourceSymbolCollectionName, + type SourceSymbolFindOptions, + type SourceSymbolSkipCounts, + type SourceSymbolSkipReason, +} from './source-symbol-readers'; diff --git a/apps/stock/data-pipeline/src/security-master/match-report.ts b/apps/stock/data-pipeline/src/security-master/match-report.ts new file mode 100644 index 00000000..3e9ab06a --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/match-report.ts @@ -0,0 +1,1170 @@ +import type { + DelistingChainOutcomeStats, + DelistingChainResult, +} from './delisting-chains'; +import { DELIST_REASONS } from './delisting-chains'; +import { compareAscii, type ExchangeClassificationResult } from './exchange-pass1'; +import { escapeSqlLiteral } from './exchange-seed-sql'; +import type { StageAMatchResult } from './instrument-stage-a'; +import { + STAGE_B_SOURCES, + type StageBMatchResult, + type StageBSource, + type StageBUnresolvedReason, +} from './listing-stage-b'; +import { + PRICE_CROSS_CHECK_VERDICTS, + type PriceCrossCheckResult, + type PriceCrossCheckVerdictCounts, +} from './price-cross-check'; + +export const DEFAULT_MIN_RESOLVED_PCT = 0.95; +export const DEFAULT_MAX_CONFLICT_ROWS = 200; +export const DEFAULT_OVERRIDE_VALID_FROM = '1900-01-01'; + +export const EXCLUDED_BY_DESIGN_STAGE_B_REASONS = [ + 'excluded_fund', + 'composite_venue', + 'ats_routing_venue', + 'forex_venue', +] as const satisfies readonly StageBUnresolvedReason[]; + +export const MATCH_REPORT_PASSES = ['stage_a', 'stage_b', 'pass4', 'pass6'] as const; + +export type MatchReportPass = (typeof MATCH_REPORT_PASSES)[number]; +export type ExcludedByDesignStageBReason = (typeof EXCLUDED_BY_DESIGN_STAGE_B_REASONS)[number]; + +export type SourceCountryLookup = ReadonlyMap | Readonly>; + +export interface MatchReportInput { + readonly exchanges?: ExchangeClassificationResult; + readonly stageA: StageAMatchResult; + readonly stageB: StageBMatchResult; + readonly priceCrossCheck?: PriceCrossCheckResult; + readonly delistingChains?: DelistingChainResult; + readonly sourceCountries?: SourceCountryLookup; +} + +export interface BuildMatchReportOptions { + readonly minResolvedPct?: number; +} + +export interface ExchangeCoverageSummary { + mapped: number; + unresolved: number; + total: number; + mappedPct: number | null; +} + +/** + * Per-source resolution summary derived from Stage B stats and unresolved records. + * + * Formulas: + * - `resolvedPct = total > 0 ? matched / total : null` + * - `excludedByDesign`: count of Stage B unresolved records for this source whose reason is + * one of `excluded_fund`, `composite_venue`, `ats_routing_venue`, or `forex_venue`. + * - `eligibleTotal = Math.max(0, total - excludedByDesign)` + * - `eligibleResolvedPct = eligibleTotal > 0 ? matched / eligibleTotal : null` + */ +export interface SourceResolutionSummary { + source: StageBSource; + total: number; + matched: number; + unresolved: number; + conflict: number; + excludedByDesign: number; + eligibleTotal: number; + resolvedPct: number | null; + eligibleResolvedPct: number | null; +} + +export interface CountryResolutionSummary { + country: string; + total: number; + matched: number; + unresolved: number; + conflict: number; + excludedByDesign: number; + eligibleTotal: number; + resolvedPct: number | null; + eligibleResolvedPct: number | null; +} + +export interface UnresolvedBreakdownRow { + source: string; + reason: string; + count: number; +} + +export interface UnresolvedBreakdown { + stageA: UnresolvedBreakdownRow[]; + stageB: UnresolvedBreakdownRow[]; +} + +export interface UnifiedConflictRow { + pass: MatchReportPass; + source: string | null; + sourceId: string | null; + conflictKind: string; + detail: Record; +} + +export interface ConflictCountRow { + pass: MatchReportPass; + conflictKind: string; + count: number; +} + +export interface PriceCrossCheckSummary { + pairsIn: number; + invalidPairs: number; + conflictsEmitted: number; + byVerdict: PriceCrossCheckVerdictCounts; +} + +export interface DelistingChainSummary { + totalInputListings: number; + processedListings: number; + continuitiesCreated: number; + conflictsDetected: number; + byOutcome: DelistingChainOutcomeStats; +} + +export interface MatchReportExitThresholds { + exchangesMapped100: boolean; + equitiesResolved95: boolean; +} + +export interface MatchReport { + minResolvedPct: number; + exchangeCoverage: ExchangeCoverageSummary | null; + resolutionBySource: SourceResolutionSummary[]; + resolutionByCountry: CountryResolutionSummary[]; + unresolvedByReason: UnresolvedBreakdown; + conflicts: UnifiedConflictRow[]; + conflictsByPassKind: ConflictCountRow[]; + priceCrossCheck: PriceCrossCheckSummary | null; + delistingChains: DelistingChainSummary | null; + meetsExitThresholds: MatchReportExitThresholds; +} + +export interface RenderMatchReportMarkdownOptions { + readonly maxConflictRows?: number; +} + +export interface OverrideSeedRow { + readonly source: string; + readonly sourceId: string; + readonly validFrom?: string; + readonly validTo?: string | null; + readonly primaryIsin: string; + readonly mic: string; + readonly tickerRoot: string; + readonly classSuffix: string; + readonly currency: string; + readonly reason: string; + readonly createdBy: string; +} + +interface NormalizedOverrideSeedRow { + readonly source: string; + readonly sourceId: string; + readonly validFrom: string; + readonly validTo: string | null; + readonly primaryIsin: string; + readonly mic: string; + readonly tickerRoot: string; + readonly classSuffix: string; + readonly currency: string; + readonly reason: string; + readonly createdBy: string; +} + +interface CountryAccumulator { + total: number; + matched: number; + unresolved: number; + conflict: number; + excludedByDesign: number; +} + +interface SortableUnifiedConflict { + readonly row: UnifiedConflictRow; + readonly canonicalDetailJson: string; +} + +const EXCLUDED_BY_DESIGN_SET: ReadonlySet = new Set(EXCLUDED_BY_DESIGN_STAGE_B_REASONS); +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +const MAX_OVERRIDE_SOURCE_LENGTH = 16; +const MAX_OVERRIDE_SOURCE_ID_LENGTH = 64; +const MAX_PRIMARY_ISIN_LENGTH = 12; +const MAX_MIC_LENGTH = 10; +const MAX_TICKER_ROOT_LENGTH = 24; +const MAX_CLASS_SUFFIX_LENGTH = 12; +const MAX_CURRENCY_LENGTH = 3; + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +/** + * Pure-integer Gregorian calendar validator for exact `YYYY-MM-DD` strings (years 0001..9999). + * Rejects timestamps, whitespace padding, and impossible dates such as `2024-02-30` or `2023-02-29`. + */ +function isValidExactYmd(value: unknown): value is string { + if (typeof value !== 'string' || !EXACT_YMD_PATTERN.test(value)) { + return false; + } + const year = + (value.charCodeAt(0) - 48) * 1000 + + (value.charCodeAt(1) - 48) * 100 + + (value.charCodeAt(2) - 48) * 10 + + (value.charCodeAt(3) - 48); + if (year < 1) { + return false; + } + const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); + if (month < 1 || month > 12) { + return false; + } + const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); + const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); + return day >= 1 && day <= maxDay; +} + +function canonicalizeJsonValue(value: unknown): unknown { + if (value === null || typeof value !== 'object') { + if (typeof value === 'number' && Object.is(value, -0)) { + return 0; + } + return value; + } + if (Array.isArray(value)) { + return value.map(item => canonicalizeJsonValue(item)); + } + const sourceObj = value as Record; + const sortedKeys = Object.keys(sourceObj).sort(compareAscii); + const result: Record = {}; + for (const key of sortedKeys) { + const entry = sourceObj[key]; + if (entry !== undefined) { + result[key] = canonicalizeJsonValue(entry); + } + } + return result; +} + +function canonicalizeDetailObject(value: unknown): Record { + const canonical = canonicalizeJsonValue(value); + if (canonical !== null && typeof canonical === 'object' && !Array.isArray(canonical)) { + return canonical as Record; + } + return {}; +} + +function stableJsonStringify(value: unknown): string { + return JSON.stringify(canonicalizeJsonValue(value)); +} + +function compareNullableAscii(a: string | null, b: string | null): number { + if (a === b) { + return 0; + } + if (a === null) { + return -1; + } + if (b === null) { + return 1; + } + return compareAscii(a, b); +} + +function sortUnifiedConflicts(rows: readonly UnifiedConflictRow[]): UnifiedConflictRow[] { + const decorated: SortableUnifiedConflict[] = rows.map(row => ({ + row, + canonicalDetailJson: stableJsonStringify(row.detail), + })); + decorated.sort( + (a, b) => + compareAscii(a.row.pass, b.row.pass) || + compareAscii(a.row.conflictKind, b.row.conflictKind) || + compareNullableAscii(a.row.source, b.row.source) || + compareNullableAscii(a.row.sourceId, b.row.sourceId) || + compareAscii(a.canonicalDetailJson, b.canonicalDetailJson) + ); + return decorated.map(entry => entry.row); +} + +function escapeMarkdownCell(value: string | null | undefined): string { + if (value === null || value === undefined || value.length === 0) { + return ''; + } + return value.replaceAll('\\', '\\\\').replaceAll('|', '\\|').replaceAll(/\r\n|\r|\n/g, ' '); +} + +function escapeCsvField(value: string): string { + if ( + value.includes(',') || + value.includes('"') || + value.includes('\r') || + value.includes('\n') + ) { + return `"${value.replaceAll('"', '""')}"`; + } + return value; +} + +export function sourceCountryKey(source: string, sourceId: string): string { + return `${source}:${sourceId}`; +} + +function lookupSourceCountry( + lookup: SourceCountryLookup | undefined, + source: string, + sourceId: string +): string | null { + if (!lookup) { + return null; + } + const primaryKey = sourceCountryKey(source, sourceId); + const fallbackKey = `${source}\u0000${sourceId}`; + + let raw: string | undefined; + if (lookup instanceof Map) { + raw = lookup.get(primaryKey) ?? lookup.get(fallbackKey); + } else { + const record = lookup as Readonly>; + if (Object.prototype.hasOwnProperty.call(record, primaryKey)) { + raw = record[primaryKey]; + } else if (Object.prototype.hasOwnProperty.call(record, fallbackKey)) { + raw = record[fallbackKey]; + } + } + if (typeof raw !== 'string') { + return null; + } + const normalized = raw.trim().toUpperCase(); + return normalized.length > 0 ? normalized : null; +} + +function buildUnresolvedBreakdown( + records: readonly { readonly source: string; readonly reason: string }[] +): UnresolvedBreakdownRow[] { + const counts = new Map(); + for (const record of records) { + const key = `${record.source}\u0000${record.reason}`; + const existing = counts.get(key); + if (existing) { + existing.count += 1; + } else { + counts.set(key, { + source: record.source, + reason: record.reason, + count: 1, + }); + } + } + return Array.from(counts.values()).sort( + (a, b) => compareAscii(a.source, b.source) || compareAscii(a.reason, b.reason) + ); +} + +function buildConflictCounts(conflicts: readonly UnifiedConflictRow[]): ConflictCountRow[] { + const counts = new Map(); + for (const row of conflicts) { + const key = `${row.pass}\u0000${row.conflictKind}`; + const existing = counts.get(key); + if (existing) { + existing.count += 1; + } else { + counts.set(key, { + pass: row.pass, + conflictKind: row.conflictKind, + count: 1, + }); + } + } + return Array.from(counts.values()).sort( + (a, b) => compareAscii(a.pass, b.pass) || compareAscii(a.conflictKind, b.conflictKind) + ); +} + +function buildCountryResolution( + stageB: StageBMatchResult, + sourceCountries: SourceCountryLookup | undefined +): CountryResolutionSummary[] { + if (!sourceCountries) { + return []; + } + + const byCountry = new Map(); + const getOrCreate = (country: string): CountryAccumulator => { + let acc = byCountry.get(country); + if (!acc) { + acc = { total: 0, matched: 0, unresolved: 0, conflict: 0, excludedByDesign: 0 }; + byCountry.set(country, acc); + } + return acc; + }; + + for (const mapping of stageB.providerMappings) { + const country = lookupSourceCountry(sourceCountries, mapping.source, mapping.sourceId); + if (country !== null) { + const acc = getOrCreate(country); + acc.total += 1; + acc.matched += 1; + } + } + + for (const record of stageB.unresolved) { + const country = lookupSourceCountry(sourceCountries, record.source, record.sourceId); + if (country !== null) { + const acc = getOrCreate(country); + acc.total += 1; + acc.unresolved += 1; + if (EXCLUDED_BY_DESIGN_SET.has(record.reason)) { + acc.excludedByDesign += 1; + } + } + } + + for (const conflict of stageB.conflicts) { + const country = lookupSourceCountry(sourceCountries, conflict.source, conflict.sourceId); + if (country !== null) { + const acc = getOrCreate(country); + acc.total += 1; + acc.conflict += 1; + } + } + + return Array.from(byCountry.entries()) + .sort((a, b) => compareAscii(a[0], b[0])) + .map(([country, acc]) => { + const eligibleTotal = Math.max(0, acc.total - acc.excludedByDesign); + return { + country, + total: acc.total, + matched: acc.matched, + unresolved: acc.unresolved, + conflict: acc.conflict, + excludedByDesign: acc.excludedByDesign, + eligibleTotal, + resolvedPct: acc.total > 0 ? acc.matched / acc.total : null, + eligibleResolvedPct: eligibleTotal > 0 ? acc.matched / eligibleTotal : null, + }; + }); +} + +/** + * Pure in-memory aggregator for Security Master Passes 1, 3A, 3B, 4, and 6. + * + * Resolution percentage formulas: + * - `resolvedPct = total > 0 ? matched / total : null` + * - `eligibleTotal = Math.max(0, total - excludedByDesign)` where `excludedByDesign` + * counts Stage B unresolved rows with reason in + * `['excluded_fund', 'composite_venue', 'ats_routing_venue', 'forex_venue']`. + * - `eligibleResolvedPct = eligibleTotal > 0 ? matched / eligibleTotal : null` + * Zero denominators always produce `null`, never `NaN` or `Infinity`. + */ +export function buildMatchReport( + input: MatchReportInput, + options?: BuildMatchReportOptions +): MatchReport { + const minResolvedPct = options?.minResolvedPct ?? DEFAULT_MIN_RESOLVED_PCT; + if ( + typeof minResolvedPct !== 'number' || + !Number.isFinite(minResolvedPct) || + minResolvedPct < 0 || + minResolvedPct > 1 + ) { + throw new Error( + `Invalid minResolvedPct (${String(minResolvedPct)}): must be a finite number in [0, 1]` + ); + } + + const exchangeCoverage: ExchangeCoverageSummary | null = input.exchanges + ? (() => { + const mapped = input.exchanges.mapped.length; + const unresolved = input.exchanges.unresolved.length; + const total = mapped + unresolved; + return { + mapped, + unresolved, + total, + mappedPct: total > 0 ? mapped / total : null, + }; + })() + : null; + + const excludedBySource: Record = { + eod: 0, + ib: 0, + qm: 0, + ceo: 0, + }; + for (const record of input.stageB.unresolved) { + if (EXCLUDED_BY_DESIGN_SET.has(record.reason)) { + excludedBySource[record.source] += 1; + } + } + + const resolutionBySource: SourceResolutionSummary[] = STAGE_B_SOURCES.map(source => { + const stats = input.stageB.stats.bySource[source]; + const excludedByDesign = excludedBySource[source]; + const eligibleTotal = Math.max(0, stats.total - excludedByDesign); + return { + source, + total: stats.total, + matched: stats.matched, + unresolved: stats.unresolved, + conflict: stats.conflict, + excludedByDesign, + eligibleTotal, + resolvedPct: stats.total > 0 ? stats.matched / stats.total : null, + eligibleResolvedPct: eligibleTotal > 0 ? stats.matched / eligibleTotal : null, + }; + }); + + const resolutionByCountry = buildCountryResolution(input.stageB, input.sourceCountries); + + const unresolvedByReason: UnresolvedBreakdown = { + stageA: buildUnresolvedBreakdown(input.stageA.unresolved), + stageB: buildUnresolvedBreakdown(input.stageB.unresolved), + }; + + const rawConflicts: UnifiedConflictRow[] = []; + for (const conflict of input.stageA.conflicts) { + rawConflicts.push({ + pass: 'stage_a', + source: conflict.source, + sourceId: conflict.sourceId, + conflictKind: conflict.conflictKind, + detail: canonicalizeDetailObject(conflict.detail), + }); + } + for (const conflict of input.stageB.conflicts) { + rawConflicts.push({ + pass: 'stage_b', + source: conflict.source, + sourceId: conflict.sourceId, + conflictKind: conflict.conflictKind, + detail: canonicalizeDetailObject(conflict.detail), + }); + } + if (input.priceCrossCheck) { + for (const conflict of input.priceCrossCheck.conflicts) { + rawConflicts.push({ + pass: 'pass4', + source: conflict.source, + sourceId: conflict.sourceId, + conflictKind: conflict.conflictKind, + detail: canonicalizeDetailObject(conflict.detail), + }); + } + } + if (input.delistingChains) { + for (const conflict of input.delistingChains.conflicts) { + rawConflicts.push({ + pass: 'pass6', + source: null, + sourceId: null, + conflictKind: conflict.conflictKind, + detail: canonicalizeDetailObject(conflict.detail), + }); + } + } + + const conflicts = sortUnifiedConflicts(rawConflicts); + const conflictsByPassKind = buildConflictCounts(conflicts); + + const priceCrossCheck: PriceCrossCheckSummary | null = input.priceCrossCheck + ? { + pairsIn: input.priceCrossCheck.stats.pairsIn, + invalidPairs: input.priceCrossCheck.stats.invalidPairs, + conflictsEmitted: input.priceCrossCheck.stats.conflictsEmitted, + byVerdict: { ...input.priceCrossCheck.stats.byVerdict }, + } + : null; + + const delistingChains: DelistingChainSummary | null = input.delistingChains + ? { + totalInputListings: input.delistingChains.stats.totalInputListings, + processedListings: input.delistingChains.stats.processedListings, + continuitiesCreated: input.delistingChains.stats.continuitiesCreated, + conflictsDetected: input.delistingChains.stats.conflictsDetected, + byOutcome: { ...input.delistingChains.stats.byOutcome }, + } + : null; + + const eligibleSources = resolutionBySource.filter(row => row.total > 0 && row.eligibleTotal > 0); + const meetsExitThresholds: MatchReportExitThresholds = { + exchangesMapped100: + exchangeCoverage !== null && exchangeCoverage.mapped > 0 && exchangeCoverage.unresolved === 0, + equitiesResolved95: + eligibleSources.length > 0 && + eligibleSources.every( + row => row.eligibleResolvedPct !== null && row.eligibleResolvedPct >= minResolvedPct + ), + }; + + return { + minResolvedPct, + exchangeCoverage, + resolutionBySource, + resolutionByCountry, + unresolvedByReason, + conflicts, + conflictsByPassKind, + priceCrossCheck, + delistingChains, + meetsExitThresholds, + }; +} + +function formatPct(value: number | null): string { + if (value === null) { + return 'N/A'; + } + return `${(value * 100).toFixed(2)}%`; +} + +export function renderMatchReportMarkdown( + report: MatchReport, + options?: RenderMatchReportMarkdownOptions +): string { + const maxConflictRows = options?.maxConflictRows ?? DEFAULT_MAX_CONFLICT_ROWS; + if ( + typeof maxConflictRows !== 'number' || + !Number.isSafeInteger(maxConflictRows) || + maxConflictRows < 0 + ) { + throw new Error( + `Invalid maxConflictRows (${String(maxConflictRows)}): must be a non-negative safe integer` + ); + } + + const lines: string[] = [ + '# Security Master Match & Conflict Report', + '', + '## Exit Thresholds', + '', + '| Criterion | Status | Target |', + '| --- | --- | --- |', + `| Exchanges Mapped | ${report.meetsExitThresholds.exchangesMapped100 ? 'PASS' : 'FAIL'} | 100.00% |`, + `| Equities Resolved (Eligible) | ${report.meetsExitThresholds.equitiesResolved95 ? 'PASS' : 'FAIL'} | >= ${formatPct(report.minResolvedPct)} |`, + '', + '## Exchange Coverage', + '', + '| Mapped | Unresolved | Total | Mapped % |', + '| --- | --- | --- | --- |', + ]; + + if (report.exchangeCoverage) { + lines.push( + `| ${report.exchangeCoverage.mapped} | ${report.exchangeCoverage.unresolved} | ${report.exchangeCoverage.total} | ${formatPct(report.exchangeCoverage.mappedPct)} |` + ); + } else { + lines.push('| 0 | 0 | 0 | N/A |'); + } + + lines.push( + '', + '## Per-Source Resolution', + '', + '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |', + '| --- | --- | --- | --- | --- | --- | --- | --- | --- |' + ); + + for (const row of report.resolutionBySource) { + lines.push( + `| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |` + ); + } + + if (report.resolutionByCountry.length > 0) { + lines.push( + '', + '## Per-Country Resolution', + '', + '| Country | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |', + '| --- | --- | --- | --- | --- | --- | --- | --- | --- |' + ); + for (const row of report.resolutionByCountry) { + lines.push( + `| ${escapeMarkdownCell(row.country)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |` + ); + } + } + + lines.push( + '', + '## Unresolved by Reason', + '', + '### Stage A', + '', + '| Source | Reason | Count |', + '| --- | --- | --- |' + ); + + if (report.unresolvedByReason.stageA.length === 0) { + lines.push('| (none) | (none) | 0 |'); + } else { + const sortedStageA = [...report.unresolvedByReason.stageA].sort( + (a, b) => compareAscii(a.source, b.source) || compareAscii(a.reason, b.reason) + ); + for (const row of sortedStageA) { + lines.push( + `| ${escapeMarkdownCell(row.source)} | ${escapeMarkdownCell(row.reason)} | ${row.count} |` + ); + } + } + + lines.push('', '### Stage B', '', '| Source | Reason | Count |', '| --- | --- | --- |'); + + if (report.unresolvedByReason.stageB.length === 0) { + lines.push('| (none) | (none) | 0 |'); + } else { + const sortedStageB = [...report.unresolvedByReason.stageB].sort( + (a, b) => compareAscii(a.source, b.source) || compareAscii(a.reason, b.reason) + ); + for (const row of sortedStageB) { + lines.push( + `| ${escapeMarkdownCell(row.source)} | ${escapeMarkdownCell(row.reason)} | ${row.count} |` + ); + } + } + + lines.push( + '', + '## Conflicts by Pass & Kind', + '', + '| Pass | Conflict Kind | Count |', + '| --- | --- | --- |' + ); + + if (report.conflictsByPassKind.length === 0) { + lines.push('| (none) | (none) | 0 |'); + } else { + const sortedCounts = [...report.conflictsByPassKind].sort( + (a, b) => compareAscii(a.pass, b.pass) || compareAscii(a.conflictKind, b.conflictKind) + ); + for (const row of sortedCounts) { + lines.push( + `| ${escapeMarkdownCell(row.pass)} | ${escapeMarkdownCell(row.conflictKind)} | ${row.count} |` + ); + } + } + + lines.push('', '## Pass 4 Price Cross-Check Verdicts', ''); + if (report.priceCrossCheck === null) { + lines.push('- Status: skipped (no sample closes supplied)'); + } + lines.push( + `- Pairs In: ${report.priceCrossCheck?.pairsIn ?? 0}`, + `- Invalid Pairs: ${report.priceCrossCheck?.invalidPairs ?? 0}`, + `- Conflicts Emitted: ${report.priceCrossCheck?.conflictsEmitted ?? 0}`, + '', + '| Verdict | Count |', + '| --- | --- |' + ); + + for (const verdict of PRICE_CROSS_CHECK_VERDICTS) { + const count = report.priceCrossCheck?.byVerdict[verdict] ?? 0; + lines.push(`| ${escapeMarkdownCell(verdict)} | ${count} |`); + } + + lines.push( + '', + '## Pass 6 Delisting Chain Outcomes', + '', + `- Total Input Listings: ${report.delistingChains?.totalInputListings ?? 0}`, + `- Processed Listings: ${report.delistingChains?.processedListings ?? 0}`, + `- Continuities Created: ${report.delistingChains?.continuitiesCreated ?? 0}`, + `- Conflicts Detected: ${report.delistingChains?.conflictsDetected ?? 0}`, + '', + '| Outcome | Count |', + '| --- | --- |' + ); + + for (const outcome of DELIST_REASONS) { + const count = report.delistingChains?.byOutcome[outcome] ?? 0; + lines.push(`| ${escapeMarkdownCell(outcome)} | ${count} |`); + } + + const sortedConflicts = sortUnifiedConflicts(report.conflicts); + const sample = sortedConflicts.slice(0, maxConflictRows); + + lines.push('', '## Conflict Sample', ''); + + if (sortedConflicts.length === 0) { + lines.push('No open conflicts (0 total).'); + } else { + lines.push( + '| Pass | Source | Source ID | Conflict Kind | Detail |', + '| --- | --- | --- | --- | --- |' + ); + for (const row of sample) { + lines.push( + `| ${escapeMarkdownCell(row.pass)} | ${escapeMarkdownCell(row.source)} | ${escapeMarkdownCell(row.sourceId)} | ${escapeMarkdownCell(row.conflictKind)} | ${escapeMarkdownCell(stableJsonStringify(row.detail))} |` + ); + } + const remaining = sortedConflicts.length - sample.length; + lines.push(''); + if (remaining > 0) { + lines.push( + `Showing ${sample.length} of ${sortedConflicts.length} conflicts (${remaining} more in CSV).` + ); + } else { + lines.push(`Showing ${sample.length} of ${sortedConflicts.length} conflicts.`); + } + } + + lines.push(''); + return lines.join('\n'); +} + +export function renderConflictsCsv(report: MatchReport): string { + const sortedConflicts = sortUnifiedConflicts(report.conflicts); + const lines: string[] = ['pass,source,source_id,conflict_kind,detail_json']; + + for (const row of sortedConflicts) { + lines.push( + [ + escapeCsvField(row.pass), + escapeCsvField(row.source ?? ''), + escapeCsvField(row.sourceId ?? ''), + escapeCsvField(row.conflictKind), + escapeCsvField(stableJsonStringify(row.detail)), + ].join(',') + ); + } + + return `${lines.join('\r\n')}\r\n`; +} + +function assertNoNul(value: string, fieldName: string): void { + if (value.includes('\0')) { + throw new Error(`Invalid override row: ${fieldName} must not contain NUL bytes`); + } +} + +function validateRequiredStringField( + value: unknown, + fieldName: string, + maxLength?: number +): string { + if (typeof value !== 'string') { + throw new Error(`Invalid override row: ${fieldName} must be a string`); + } + assertNoNul(value, fieldName); + if (value.trim().length === 0) { + throw new Error(`Invalid override row: ${fieldName} must not be empty`); + } + if (maxLength !== undefined && value.length > maxLength) { + throw new Error( + `Invalid override row: ${fieldName} length (${value.length}) exceeds maximum of ${maxLength} characters` + ); + } + return value; +} + +function validateOptionalEmptyStringField( + value: unknown, + fieldName: string, + maxLength: number +): string { + if (typeof value !== 'string') { + throw new Error(`Invalid override row: ${fieldName} must be a string`); + } + assertNoNul(value, fieldName); + if (value.length > maxLength) { + throw new Error( + `Invalid override row: ${fieldName} length (${value.length}) exceeds maximum of ${maxLength} characters` + ); + } + return value; +} + +function validateOverrideRow(row: OverrideSeedRow): NormalizedOverrideSeedRow { + const source = validateRequiredStringField(row.source, 'source', MAX_OVERRIDE_SOURCE_LENGTH); + const sourceId = validateRequiredStringField( + row.sourceId, + 'sourceId', + MAX_OVERRIDE_SOURCE_ID_LENGTH + ); + const primaryIsin = validateRequiredStringField( + row.primaryIsin, + 'primaryIsin', + MAX_PRIMARY_ISIN_LENGTH + ); + const mic = validateRequiredStringField(row.mic, 'mic', MAX_MIC_LENGTH); + const tickerRoot = validateRequiredStringField( + row.tickerRoot, + 'tickerRoot', + MAX_TICKER_ROOT_LENGTH + ); + const classSuffix = validateOptionalEmptyStringField( + row.classSuffix, + 'classSuffix', + MAX_CLASS_SUFFIX_LENGTH + ); + const currency = validateRequiredStringField(row.currency, 'currency', MAX_CURRENCY_LENGTH); + const reason = validateRequiredStringField(row.reason, 'reason'); + const createdBy = validateRequiredStringField(row.createdBy, 'createdBy'); + + const rawValidFrom = row.validFrom ?? DEFAULT_OVERRIDE_VALID_FROM; + if (typeof rawValidFrom !== 'string') { + throw new Error('Invalid override row: validFrom must be a YYYY-MM-DD string'); + } + assertNoNul(rawValidFrom, 'validFrom'); + if (!isValidExactYmd(rawValidFrom)) { + throw new Error( + `Invalid override row: validFrom "${rawValidFrom}" must be a real YYYY-MM-DD calendar date` + ); + } + + let validTo: string | null = null; + if (row.validTo !== undefined && row.validTo !== null) { + if (typeof row.validTo !== 'string') { + throw new Error('Invalid override row: validTo must be a YYYY-MM-DD string or null'); + } + assertNoNul(row.validTo, 'validTo'); + if (!isValidExactYmd(row.validTo)) { + throw new Error( + `Invalid override row: validTo "${row.validTo}" must be a real YYYY-MM-DD calendar date` + ); + } + if (compareAscii(row.validTo, rawValidFrom) < 0) { + throw new Error( + `Invalid override row: validTo "${row.validTo}" must be >= validFrom "${rawValidFrom}"` + ); + } + validTo = row.validTo; + } + + return { + source, + sourceId, + validFrom: rawValidFrom, + validTo, + primaryIsin, + mic, + tickerRoot, + classSuffix, + currency, + reason, + createdBy, + }; +} + +function deduplicateOverrideRows(rows: readonly OverrideSeedRow[]): NormalizedOverrideSeedRow[] { + const byKey = new Map(); + for (const rawRow of rows) { + const row = validateOverrideRow(rawRow); + const key = `${row.source}\u0000${row.sourceId}\u0000${row.validFrom}`; + const existing = byKey.get(key); + if (!existing) { + byKey.set(key, row); + continue; + } + if ( + existing.validTo !== row.validTo || + existing.primaryIsin !== row.primaryIsin || + existing.mic !== row.mic || + existing.tickerRoot !== row.tickerRoot || + existing.classSuffix !== row.classSuffix || + existing.currency !== row.currency || + existing.reason !== row.reason || + existing.createdBy !== row.createdBy + ) { + throw new Error( + `Conflicting duplicate override row for (${row.source}, "${row.sourceId}", ${row.validFrom})` + ); + } + } + return Array.from(byKey.values()).sort( + (a, b) => + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.validFrom, b.validFrom) + ); +} + +export function generateOverrideSeedSql(rows: readonly OverrideSeedRow[]): string { + const normalized = deduplicateOverrideRows(rows); + + const sections: string[] = [ + [ + '-- Security master override seed (M1.1i)', + '-- Generated deterministically by apps/stock/data-pipeline/src/security-master/match-report.ts.', + '-- Resolves target listings by natural key (requires a unique match; 0 matches is a no-op, >1 match raises cardinality_violation); idempotent via ON CONFLICT DO NOTHING.', + ].join('\n'), + ]; + + for (const row of normalized) { + const validToSql = row.validTo === null ? 'NULL' : `DATE '${row.validTo}'`; + sections.push( + [ + 'INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)', + 'SELECT', + ` ${escapeSqlLiteral(row.source)},`, + ` ${escapeSqlLiteral(row.sourceId)},`, + ` DATE '${row.validFrom}',`, + ` ${validToSql},`, + ' matched.listing_id,', + ` ${escapeSqlLiteral(row.reason)},`, + ` ${escapeSqlLiteral(row.createdBy)}`, + 'FROM (', + ' SELECT (', + ' SELECT l.listing_id', + ' FROM listing l', + ' JOIN instrument i ON i.instrument_id = l.instrument_id', + ` WHERE i.primary_isin = ${escapeSqlLiteral(row.primaryIsin)}`, + ` AND l.mic = ${escapeSqlLiteral(row.mic)}`, + ` AND l.ticker_root = ${escapeSqlLiteral(row.tickerRoot)}`, + ` AND l.class_suffix = ${escapeSqlLiteral(row.classSuffix)}`, + ` AND l.currency = ${escapeSqlLiteral(row.currency)}`, + ' ) AS listing_id', + ') AS matched', + 'WHERE matched.listing_id IS NOT NULL', + 'ON CONFLICT (source, source_id, valid_from) DO NOTHING;', + ].join('\n') + ); + } + + return `${sections.join('\n\n')}\n`; +} + +function formatTemplateCommentValue(value: string): string { + return value + .replaceAll('\\', '\\\\') + .replaceAll('\0', '\\u0000') + .replaceAll('\r', '\\r') + .replaceAll('\n', '\\n'); +} + +function formatSingleLineSqlLiteral(value: string): string { + if (value.includes('\0')) { + throw new Error('SQL literal value must not contain NUL bytes'); + } + if (!value.includes('\r') && !value.includes('\n')) { + return escapeSqlLiteral(value); + } + const escaped = value + .replaceAll('\\', '\\\\') + .replaceAll("'", "''") + .replaceAll('\r', '\\r') + .replaceAll('\n', '\\n'); + return `E'${escaped}'`; +} + +function getUnstorableTemplateIdReasons(value: string, maxLength: number): string[] { + const reasons: string[] = []; + if (value.includes('\0')) { + reasons.push('contains NUL byte'); + } + if (value.trim().length === 0) { + reasons.push('is empty or whitespace-only'); + } + if (value.length > maxLength) { + reasons.push(`length (${value.length}) exceeds ${maxLength}-character limit`); + } + return reasons; +} + +function commentOutSqlBlock(lines: readonly string[]): string { + return lines + .flatMap(line => line.split(/\r\n|\r|\n/)) + .map(line => `-- ${line}`) + .join('\n'); +} + +export function generateOverrideTemplateSql(report: MatchReport): string { + const sortedConflicts = sortUnifiedConflicts(report.conflicts).filter( + (row): row is UnifiedConflictRow & { source: string; sourceId: string } => + row.source !== null && row.sourceId !== null + ); + + const sections: string[] = [ + [ + '-- Security master override review template (M1.1i)', + '-- Generated deterministically by apps/stock/data-pipeline/src/security-master/match-report.ts.', + '-- Review open conflicts below, uncomment a statement, and fill in the target listing natural key to apply.', + '-- Requires a unique natural-key match (0 matches is a no-op, >1 match raises cardinality_violation).', + '-- Nothing in this file is auto-applied.', + ].join('\n'), + ]; + + if (sortedConflicts.length === 0) { + sections.push('-- No source-attributed open conflicts.'); + return `${sections.join('\n\n')}\n`; + } + + for (const conflict of sortedConflicts) { + const commentSource = formatTemplateCommentValue(conflict.source); + const commentSourceId = formatTemplateCommentValue(conflict.sourceId); + const commentKind = formatTemplateCommentValue(conflict.conflictKind); + const commentPass = formatTemplateCommentValue(conflict.pass); + + const sourceIssues = getUnstorableTemplateIdReasons(conflict.source, MAX_OVERRIDE_SOURCE_LENGTH); + const sourceIdIssues = getUnstorableTemplateIdReasons( + conflict.sourceId, + MAX_OVERRIDE_SOURCE_ID_LENGTH + ); + + const sourceSqlLiteral = + sourceIssues.length === 0 + ? formatSingleLineSqlLiteral(conflict.source) + : 'NULL /* TODO: replace with valid source */'; + const sourceIdSqlLiteral = + sourceIdIssues.length === 0 + ? formatSingleLineSqlLiteral(conflict.sourceId) + : 'NULL /* TODO: replace with valid source_id */'; + + const blockLines: string[] = [ + `Conflict: pass=${commentPass} kind=${commentKind} source=${commentSource} source_id=${commentSourceId}`, + ]; + if (sourceIssues.length > 0) { + blockLines.push( + `WARNING: Cannot store raw source in PostgreSQL (${sourceIssues.join('; ')}); correct source before applying.` + ); + } + if (sourceIdIssues.length > 0) { + blockLines.push( + `WARNING: Cannot store raw source_id in PostgreSQL (${sourceIdIssues.join('; ')}); correct source_id before applying.` + ); + } + + blockLines.push( + 'INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)', + 'SELECT', + ` ${sourceSqlLiteral},`, + ` ${sourceIdSqlLiteral},`, + ` DATE '${DEFAULT_OVERRIDE_VALID_FROM}',`, + ' NULL,', + ' matched.listing_id,', + ` ${formatSingleLineSqlLiteral(`TODO: explain resolution for ${commentKind}`)},`, + ` ${escapeSqlLiteral('TODO: reviewer')}`, + 'FROM (', + ' SELECT (', + ' SELECT l.listing_id', + ' FROM listing l', + ' JOIN instrument i ON i.instrument_id = l.instrument_id', + " WHERE i.primary_isin = 'TODO_ISIN_12'", + " AND l.mic = 'TODO_MIC'", + " AND l.ticker_root = 'TODO_TICKER'", + " AND l.class_suffix = ''", + " AND l.currency = 'USD'", + ' ) AS listing_id', + ') AS matched', + 'WHERE matched.listing_id IS NOT NULL', + 'ON CONFLICT (source, source_id, valid_from) DO NOTHING;' + ); + + sections.push(commentOutSqlBlock(blockLines)); + } + + return `${sections.join('\n\n')}\n`; +} diff --git a/apps/stock/data-pipeline/src/security-master/persist.ts b/apps/stock/data-pipeline/src/security-master/persist.ts new file mode 100644 index 00000000..5981f7f7 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/persist.ts @@ -0,0 +1,1758 @@ +/** + * Idempotent, single-transaction PostgreSQL loader for Pass 3 (Stage A/B), Pass 5 + * (`resolution_conflict`), and Pass 6 (`delisting-chains`) security-master outputs. + * + * Recorded local benchmark baseline (`2026-11-28`, host PostgreSQL isolated `stock_bot_safety_*` + * schema, default `chunkSize = 5000`): + * - Command: `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts` + * - Workload: 20,000 instruments, 20,000 listings, 60,000 mappings (100,000 core rows; 140,000 total rows). + * - Observed end-to-end test wall time: 2.20s (2200.02ms, including schema setup, fixture generation, + * persistence, and COUNT(*) verification because `test/setup.ts` suppresses `console.info`). + * - Throughput (lower bound over full test wall time): 45,454 core rows/s, 63,636 total rows/s. + */ +import type { + DelistingChainResult, + ListingDelistOutcome, + Pass6DelistReason, +} from './delisting-chains'; +import { compareAscii } from './exchange-pass1'; +import type { + StageAInstrumentCandidate, + StageAInstrumentMember, + StageAMatchResult, + StageASource, +} from './instrument-stage-a'; +import type { + ListingNaturalKey, + StageBListingCandidate, + StageBMatchMethod, + StageBMatchResult, + StageBProviderMappingCandidate, +} from './listing-stage-b'; +import type { PriceCrossCheckResult } from './price-cross-check'; + +export const SECURITY_TYPES = [ + 'common', + 'preferred', + 'unit', + 'warrant', + 'right', + 'etf', + 'cdr', + 'fx', +] as const; + +export type SecurityType = (typeof SECURITY_TYPES)[number]; + +export const DEFAULT_VALID_FROM = '1900-01-01' as const; + +export const DEFAULT_PERSIST_CHUNK_SIZE = 5000; +export const MAX_PERSIST_CHUNK_SIZE = 5000; + +/** + * Transaction-scoped PostgreSQL advisory lock namespace (`'SMPS'` = Security Master PerSist). + * Paired with `hashtext(current_schema())` so concurrent runs against the same schema serialize + * while isolated schemas (e.g. parallel `stock_bot_safety_*` tests) never contend. + */ +export const SECURITY_MASTER_PERSIST_LOCK_NAMESPACE = 0x534d5053; + +const activePersistClients = new WeakSet(); + +/** + * Fixed confidence scores written to `provider_mapping.confidence` (`NUMERIC(4, 3)`). + * `design/DATA-CONTRACTS.md` does not specify numeric values for `tier1_isin` / `tier2_cusip` / + * `tier3_ticker_span`; these constants are this module's deterministic interpretation, while + * `override` is always forced to `1.000`. + */ +export const PROVIDER_MAPPING_CONFIDENCE = { + tier1_isin: 0.99, + tier2_cusip: 0.95, + tier3_ticker_span: 0.8, + override: 1.0, +} as const satisfies Record; + +export interface SecurityMasterQueryResult> { + readonly rows: readonly Row[]; + readonly rowCount?: number | null; +} + +/** + * Structural `pg.PoolClient`-like interface so `persistSecurityMaster` has zero runtime dependency + * on `pg` and accepts any dedicated single-session PostgreSQL client. + */ +export interface SecurityMasterQueryable { + query>( + text: string, + values?: readonly unknown[] + ): Promise>; + release?: (...args: unknown[]) => unknown; +} + +export interface PersistSecurityMasterInput { + readonly stageA: StageAMatchResult; + readonly stageB: StageBMatchResult; + readonly pass4?: PriceCrossCheckResult; + readonly pass6?: DelistingChainResult; + readonly securityTypeByIsin: ReadonlyMap; +} + +export interface PersistSecurityMasterOptions { + readonly chunkSize?: number; +} + +export interface PersistSecurityMasterSkippedByReason { + readonly instruments: { + readonly missing_canonical_name: number; + readonly missing_security_type: number; + }; + readonly listings: { + readonly skipped_instrument: number; + readonly missing_instrument: number; + readonly unknown_mic: number; + }; + readonly providerMappings: { + readonly missing_listing: number; + }; + readonly pass6Outcomes: { + readonly missing_listing: number; + }; + readonly continuities: { + readonly missing_from_listing: number; + readonly missing_to_listing: number; + readonly missing_both_listings: number; + }; +} + +export interface PersistSecurityMasterResult { + readonly instrumentsInserted: number; + readonly instrumentsUpdated: number; + readonly instrumentsUnchanged: number; + readonly instrumentsSkipped: number; + + readonly identifierHistoryInserted: number; + readonly identifierHistoryUnchanged: number; + + readonly listingsInserted: number; + readonly listingsUpdated: number; + readonly listingsUnchanged: number; + readonly listingsSkipped: number; + + readonly listingSymbolHistoryInserted: number; + readonly listingSymbolHistoryUpdated: number; + readonly listingSymbolHistoryUnchanged: number; + + readonly providerMappingsInserted: number; + readonly providerMappingsUpdated: number; + readonly providerMappingsUnchanged: number; + readonly providerMappingsSkipped: number; + readonly providerMappingsDeletedStaleFallback: number; + + readonly overridesApplied: number; + + readonly conflictsInserted: number; + readonly conflictsUnchanged: number; + readonly conflictsDeduplicated: number; + + readonly pass6OutcomesApplied: number; + readonly pass6OutcomesSkipped: number; + + readonly continuitiesInserted: number; + readonly continuitiesUpdated: number; + readonly continuitiesUnchanged: number; + readonly continuitiesSkipped: number; + + readonly skippedByReason: PersistSecurityMasterSkippedByReason; + readonly instrumentIdByIsin: ReadonlyMap; + readonly listingIdByKey: ReadonlyMap; +} + +interface ExistingInstrumentRow { + instrument_id: number; + primary_isin: string; + primary_cusip: string | null; + canonical_name: string; + security_type: string; + issuer_country: string | null; +} + +interface InsertedInstrumentRow { + instrument_id: number; + primary_isin: string; +} + +interface ExistingListingRow { + listing_id: number; + instrument_id: number; + mic: string; + ticker_root: string; + class_suffix: string; + currency: string; + ib_conid: number | string | null; + ib_primary_exchange: string | null; + listed_from: string | null; + listed_to: string | null; + delist_reason: string | null; + terminal_return: number | string | null; +} + +interface InsertedListingRow { + listing_id: number; + instrument_id: number; + mic: string; + ticker_root: string; + class_suffix: string; + currency: string; +} + +interface UpsertFlagRow { + inserted: boolean; +} + +interface SymbolHistoryUpsertCountsRow { + inserted_count: number; + updated_count: number; +} + +interface ProviderMappingUpsertRow { + source: string; + source_id: string; + valid_from: string; + inserted: boolean; +} + +interface StaleFallbackDeleteCountRow { + deleted_count: number; +} + +interface OverrideEnforceRow { + source: string; + source_id: string; + valid_from: string; + inserted: boolean | null; +} + +interface ExistingConflictRow { + source: string; + source_id: string; + conflict_kind: string; +} + +interface ExistingPass4ConflictRow { + row_idx: number; +} + +interface PreparedInstrument { + readonly primaryIsin: string; + readonly primaryCusip: string | null; + readonly canonicalName: string; + readonly securityType: SecurityType; + readonly issuerCountry: string; + readonly bestSource: StageASource; +} + +interface PreparedListing { + readonly naturalKey: string; + readonly dbNaturalKey: string; + readonly instrumentId: number; + readonly mic: string; + readonly tickerRoot: string; + readonly classSuffix: string; + readonly currency: string; + readonly ibConid: number | null; + readonly ibPrimaryExchange: string | null; + readonly listedFrom: string | null; + readonly listedTo: string | null; + readonly outcome: ListingDelistOutcome | undefined; +} + +interface ListingUpdatePayload { + readonly listingId: number; + readonly ibConid: number | null; + readonly ibPrimaryExchange: string | null; + readonly listedFrom: string | null; + readonly listedTo: string | null; + readonly delistReason: Pass6DelistReason | string | null; + readonly terminalReturn: string | null; +} + +interface PreparedSymbolHistoryRow { + readonly listingId: number; + readonly ticker: string; + readonly validFrom: string; + readonly validTo: string | null; + readonly source: string; + readonly previousValidFrom: string | null; +} + +interface PreparedProviderMapping { + readonly source: string; + readonly sourceId: string; + readonly validFrom: string; + readonly validTo: string | null; + readonly listingId: number; + readonly method: StageBMatchMethod; + readonly confidence: string; +} + +interface PreparedConflict { + readonly key: string; + readonly source: string; + readonly sourceId: string; + readonly conflictKind: string; + readonly detailJson: string; + readonly isPass4: boolean; +} + +interface PreparedContinuity { + readonly fromListingId: number; + readonly toListingId: number; + readonly effectiveDate: string; + readonly kind: string; +} + +/** + * Formats a `ListingNaturalKey` using NUL separators, matching `listing-stage-b.ts` and + * `delisting-chains.ts` so callers can look up permanent `listing_id`s from `listingIdByKey`. + */ +export function formatListingNaturalKey(key: Readonly): string { + return `${key.primaryIsin}\u0000${key.mic}\u0000${key.tickerRoot}\u0000${key.classSuffix}\u0000${key.currency}`; +} + +function formatDbListingNaturalKey( + instrumentId: number, + mic: string, + tickerRoot: string, + classSuffix: string, + currency: string +): string { + return `${instrumentId}\u0000${mic}\u0000${tickerRoot}\u0000${classSuffix}\u0000${currency}`; +} + +/** + * Recursively produces a JSON-compatible value with ASCII-sorted object keys so `detail` JSONB + * payloads are byte-for-byte deterministic regardless of JS property insertion order. + */ +export function canonicalizeJsonValue(value: unknown): unknown { + if (value === null || typeof value === 'boolean' || typeof value === 'string') { + return value; + } + if (typeof value === 'number') { + return Number.isFinite(value) ? value : null; + } + if (Array.isArray(value)) { + return value.map(item => (item === undefined ? null : canonicalizeJsonValue(item))); + } + if (typeof value === 'object') { + const record = value as Record; + const keys = Object.keys(record).sort(compareAscii); + const out: Record = {}; + for (const key of keys) { + const prop = record[key]; + if (prop !== undefined) { + out[key] = canonicalizeJsonValue(prop); + } + } + return out; + } + return null; +} + +export function stableJsonStringify(value: unknown): string { + return JSON.stringify(canonicalizeJsonValue(value)); +} + +function assertDedicatedQueryable(client: SecurityMasterQueryable): void { + if ( + client === null || + client === undefined || + typeof client !== 'object' || + typeof client.query !== 'function' + ) { + throw new TypeError( + 'persistSecurityMaster requires a PoolClient-like queryable with a query() method' + ); + } + const candidate = client as unknown as Record; + const looksLikePool = + typeof candidate.totalCount === 'number' && + typeof candidate.idleCount === 'number' && + typeof candidate.release !== 'function'; + if (looksLikePool) { + throw new TypeError( + 'persistSecurityMaster requires a dedicated PoolClient connection, not a pg.Pool (BEGIN/COMMIT must stay on one session)' + ); + } +} + +function validateChunkSize(chunkSize: number | undefined): number { + const resolved = chunkSize ?? DEFAULT_PERSIST_CHUNK_SIZE; + if (!Number.isInteger(resolved) || resolved < 1 || resolved > MAX_PERSIST_CHUNK_SIZE) { + throw new RangeError( + `chunkSize must be an integer between 1 and ${MAX_PERSIST_CHUNK_SIZE}, got ${String(resolved)}` + ); + } + return resolved; +} + +function selectBestMemberSource(members: readonly StageAInstrumentMember[]): StageASource { + let bestSource: StageASource = 'eod'; + let bestRank = Number.POSITIVE_INFINITY; + for (const member of members) { + const methodRank = member.method === 'tier1_isin' ? 0 : 2; + const sourceRank = member.source === 'ib' ? 0 : 1; + const rank = methodRank + sourceRank; + if (rank < bestRank) { + bestRank = rank; + bestSource = member.source; + if (bestRank === 0) { + break; + } + } + } + return bestSource; +} + +function normalizeNullableBigInt(value: number | string | null | undefined): number | null { + if (value === null || value === undefined) { + return null; + } + return Number(value); +} + +function normalizeNullableNumeric6(value: number | string | null | undefined): string | null { + if (value === null || value === undefined) { + return null; + } + const parsed = typeof value === 'number' ? value : Number(value); + return parsed.toFixed(6); +} + +function validateInputsAndIndexPass6(input: PersistSecurityMasterInput): { + outcomeByListingKey: Map; +} { + if (input === null || input === undefined || typeof input !== 'object') { + throw new TypeError('persistSecurityMaster requires an input object'); + } + if (!input.stageA || !Array.isArray(input.stageA.instruments)) { + throw new TypeError('persistSecurityMaster requires stageA.instruments'); + } + if (!input.stageB || !Array.isArray(input.stageB.listings)) { + throw new TypeError('persistSecurityMaster requires stageB.listings'); + } + if (!(input.securityTypeByIsin instanceof Map) && typeof input.securityTypeByIsin?.get !== 'function') { + throw new TypeError('persistSecurityMaster requires a securityTypeByIsin Map'); + } + if (input.pass4 !== undefined) { + if ( + input.pass4 === null || + typeof input.pass4 !== 'object' || + !Array.isArray(input.pass4.conflicts) + ) { + throw new TypeError('persistSecurityMaster requires pass4.conflicts to be an array'); + } + } + + const seenIsins = new Set(); + for (const inst of input.stageA.instruments) { + if (seenIsins.has(inst.primaryIsin)) { + throw new Error(`Duplicate primaryIsin in stageA.instruments: "${inst.primaryIsin}"`); + } + seenIsins.add(inst.primaryIsin); + } + + const seenListingKeys = new Set(); + for (const listing of input.stageB.listings) { + const key = formatListingNaturalKey(listing); + if (seenListingKeys.has(key)) { + throw new Error( + `Duplicate listing natural key in stageB.listings: ${listing.primaryIsin}/${listing.mic}/${listing.tickerRoot}/${listing.classSuffix}/${listing.currency}` + ); + } + seenListingKeys.add(key); + } + + const seenMappingKeys = new Set(); + for (const mapping of input.stageB.providerMappings) { + const validFrom = mapping.validFrom ?? DEFAULT_VALID_FROM; + const pk = `${mapping.source}\u0000${mapping.sourceId}\u0000${validFrom}`; + if (seenMappingKeys.has(pk)) { + throw new Error( + `Duplicate provider_mapping primary key in stageB.providerMappings: (${mapping.source}, ${mapping.sourceId}, ${validFrom})` + ); + } + seenMappingKeys.add(pk); + } + + const outcomeByListingKey = new Map(); + if (input.pass6 !== undefined) { + for (const outcome of input.pass6.listingOutcomes) { + const key = formatListingNaturalKey(outcome.listingKey); + if (outcomeByListingKey.has(key)) { + throw new Error( + `Duplicate listing outcome key in pass6.listingOutcomes: ${outcome.listingKey.primaryIsin}/${outcome.listingKey.mic}/${outcome.listingKey.tickerRoot}/${outcome.listingKey.classSuffix}/${outcome.listingKey.currency}` + ); + } + outcomeByListingKey.set(key, outcome); + } + + const seenContinuityKeys = new Set(); + for (const continuity of input.pass6.continuities) { + const pk = `${formatListingNaturalKey(continuity.fromListingKey)}\u0000${continuity.effectiveDate}`; + if (seenContinuityKeys.has(pk)) { + throw new Error( + `Duplicate corporate_action_continuity key in pass6.continuities: ${continuity.fromListingKey.primaryIsin}/${continuity.fromListingKey.mic}/${continuity.fromListingKey.tickerRoot} @ ${continuity.effectiveDate}` + ); + } + seenContinuityKeys.add(pk); + } + } + + return { outcomeByListingKey }; +} + +function collectAndDeduplicateConflicts(input: PersistSecurityMasterInput): { + uniqueConflicts: PreparedConflict[]; + deduplicatedCount: number; +} { + const raw: PreparedConflict[] = []; + + for (const c of input.stageA.conflicts) { + raw.push({ + key: `${c.source}\u0000${c.sourceId}\u0000${c.conflictKind}`, + source: c.source, + sourceId: c.sourceId, + conflictKind: c.conflictKind, + detailJson: stableJsonStringify(c.detail), + isPass4: false, + }); + } + + for (const c of input.stageB.conflicts) { + raw.push({ + key: `${c.source}\u0000${c.sourceId}\u0000${c.conflictKind}`, + source: c.source, + sourceId: c.sourceId, + conflictKind: c.conflictKind, + detailJson: stableJsonStringify(c.detail), + isPass4: false, + }); + } + + if (input.pass4 !== undefined) { + for (const c of input.pass4.conflicts) { + raw.push({ + key: `${c.source}\u0000${c.sourceId}\u0000${c.conflictKind}\u0000${c.detail.right.source}\u0000${c.detail.right.sourceId}`, + source: c.source, + sourceId: c.sourceId, + conflictKind: c.conflictKind, + detailJson: stableJsonStringify(c.detail), + isPass4: true, + }); + } + } + + if (input.pass6 !== undefined) { + for (const c of input.pass6.conflicts) { + const sourceId = c.detail.primaryIsin; + raw.push({ + key: `pass6\u0000${sourceId}\u0000${c.conflictKind}`, + source: 'pass6', + sourceId, + conflictKind: c.conflictKind, + detailJson: stableJsonStringify(c.detail), + isPass4: false, + }); + } + } + + if (raw.length === 0) { + return { uniqueConflicts: [], deduplicatedCount: 0 }; + } + + raw.sort( + (a, b) => + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.conflictKind, b.conflictKind) || + compareAscii(a.detailJson, b.detailJson) + ); + + const uniqueConflicts: PreparedConflict[] = []; + const seen = new Set(); + let deduplicatedCount = 0; + + for (const item of raw) { + if (seen.has(item.key)) { + deduplicatedCount += 1; + continue; + } + seen.add(item.key); + uniqueConflicts.push(item); + } + + return { uniqueConflicts, deduplicatedCount }; +} + +async function persistWithinTransaction( + client: SecurityMasterQueryable, + input: PersistSecurityMasterInput, + chunkSize: number, + outcomeByListingKey: ReadonlyMap +): Promise { + let instrumentsInserted = 0; + let instrumentsUpdated = 0; + let instrumentsUnchanged = 0; + let skippedMissingCanonicalName = 0; + let skippedMissingSecurityType = 0; + + let identifierHistoryInserted = 0; + let identifierHistoryUnchanged = 0; + + let listingsInserted = 0; + let listingsUpdated = 0; + let listingsUnchanged = 0; + let skippedListingInstrument = 0; + let skippedListingMissingInstrument = 0; + let skippedListingUnknownMic = 0; + + let listingSymbolHistoryInserted = 0; + let listingSymbolHistoryUpdated = 0; + let listingSymbolHistoryUnchanged = 0; + + let providerMappingsInserted = 0; + let providerMappingsUpdated = 0; + let providerMappingsUnchanged = 0; + let skippedMappingMissingListing = 0; + let providerMappingsDeletedStaleFallback = 0; + + let conflictsInserted = 0; + let conflictsUnchanged = 0; + + let pass6OutcomesApplied = 0; + let pass6OutcomesSkippedMissingListing = 0; + + let continuitiesInserted = 0; + let continuitiesUpdated = 0; + let continuitiesUnchanged = 0; + let skippedContinuityMissingFrom = 0; + let skippedContinuityMissingTo = 0; + let skippedContinuityMissingBoth = 0; + + const instrumentIdByIsin = new Map(); + const listingIdByKey = new Map(); + const skippedInstrumentIsins = new Set(); + + // --------------------------------------------------------------------------- + // 1. Instruments + instrument_identifier_history + // --------------------------------------------------------------------------- + const preparedInstruments: PreparedInstrument[] = []; + for (const candidate of input.stageA.instruments) { + const trimmedName = + typeof candidate.canonicalName === 'string' ? candidate.canonicalName.trim() : ''; + if (trimmedName.length === 0) { + skippedMissingCanonicalName += 1; + skippedInstrumentIsins.add(candidate.primaryIsin); + continue; + } + const securityType = input.securityTypeByIsin.get(candidate.primaryIsin); + if (securityType === undefined) { + skippedMissingSecurityType += 1; + skippedInstrumentIsins.add(candidate.primaryIsin); + continue; + } + preparedInstruments.push({ + primaryIsin: candidate.primaryIsin, + primaryCusip: candidate.primaryCusip, + canonicalName: trimmedName, + securityType, + issuerCountry: candidate.issuerCountry, + bestSource: selectBestMemberSource(candidate.members), + }); + } + + if (preparedInstruments.length > 0) { + const existingByIsin = new Map(); + for (let offset = 0; offset < preparedInstruments.length; offset += chunkSize) { + const slice = preparedInstruments.slice(offset, offset + chunkSize); + const isins = slice.map(item => item.primaryIsin); + const res = await client.query( + `SELECT + instrument_id, + btrim(primary_isin) AS primary_isin, + btrim(primary_cusip) AS primary_cusip, + canonical_name, + security_type, + btrim(issuer_country) AS issuer_country + FROM instrument + WHERE primary_isin = ANY($1::bpchar[])`, + [isins] + ); + for (const row of res.rows) { + existingByIsin.set(row.primary_isin, row); + } + } + + const toInsert: PreparedInstrument[] = []; + const toUpdate: Array<{ instrumentId: number; item: PreparedInstrument }> = []; + + for (const item of preparedInstruments) { + const existing = existingByIsin.get(item.primaryIsin); + if (existing === undefined) { + toInsert.push(item); + continue; + } + instrumentIdByIsin.set(item.primaryIsin, existing.instrument_id); + const changed = + existing.primary_cusip !== item.primaryCusip || + existing.canonical_name !== item.canonicalName || + existing.security_type !== item.securityType || + existing.issuer_country !== item.issuerCountry; + if (changed) { + toUpdate.push({ instrumentId: existing.instrument_id, item }); + } else { + instrumentsUnchanged += 1; + } + } + + for (let offset = 0; offset < toInsert.length; offset += chunkSize) { + const slice = toInsert.slice(offset, offset + chunkSize); + const res = await client.query( + `INSERT INTO instrument ( + primary_isin, + primary_cusip, + canonical_name, + security_type, + issuer_country + ) + SELECT * + FROM UNNEST( + $1::bpchar[], + $2::bpchar[], + $3::text[], + $4::varchar[], + $5::bpchar[] + ) + RETURNING instrument_id, btrim(primary_isin) AS primary_isin`, + [ + slice.map(item => item.primaryIsin), + slice.map(item => item.primaryCusip), + slice.map(item => item.canonicalName), + slice.map(item => item.securityType), + slice.map(item => item.issuerCountry), + ] + ); + for (const row of res.rows) { + instrumentIdByIsin.set(row.primary_isin, row.instrument_id); + } + instrumentsInserted += res.rows.length; + } + + for (let offset = 0; offset < toUpdate.length; offset += chunkSize) { + const slice = toUpdate.slice(offset, offset + chunkSize); + await client.query( + `UPDATE instrument AS i + SET + primary_cusip = u.primary_cusip, + canonical_name = u.canonical_name, + security_type = u.security_type, + issuer_country = u.issuer_country + FROM UNNEST( + $1::int4[], + $2::bpchar[], + $3::text[], + $4::varchar[], + $5::bpchar[] + ) AS u(instrument_id, primary_cusip, canonical_name, security_type, issuer_country) + WHERE i.instrument_id = u.instrument_id`, + [ + slice.map(entry => entry.instrumentId), + slice.map(entry => entry.item.primaryCusip), + slice.map(entry => entry.item.canonicalName), + slice.map(entry => entry.item.securityType), + slice.map(entry => entry.item.issuerCountry), + ] + ); + instrumentsUpdated += slice.length; + } + + // Populate instrument_identifier_history for all persisted instruments + const idHistoryRows: Array<{ + instrumentId: number; + idType: 'ISIN' | 'CUSIP'; + idValue: string; + validFrom: string; + source: StageASource; + }> = []; + for (const item of preparedInstruments) { + const instrumentId = instrumentIdByIsin.get(item.primaryIsin); + if (instrumentId === undefined) { + continue; + } + idHistoryRows.push({ + instrumentId, + idType: 'ISIN', + idValue: item.primaryIsin, + validFrom: DEFAULT_VALID_FROM, + source: item.bestSource, + }); + if (item.primaryCusip !== null) { + idHistoryRows.push({ + instrumentId, + idType: 'CUSIP', + idValue: item.primaryCusip, + validFrom: DEFAULT_VALID_FROM, + source: item.bestSource, + }); + } + } + + for (let offset = 0; offset < idHistoryRows.length; offset += chunkSize) { + const slice = idHistoryRows.slice(offset, offset + chunkSize); + const res = await client.query<{ inserted: number }>( + `INSERT INTO instrument_identifier_history ( + instrument_id, + id_type, + id_value, + valid_from, + source + ) + SELECT * + FROM UNNEST( + $1::int4[], + $2::varchar[], + $3::varchar[], + $4::date[], + $5::varchar[] + ) + ON CONFLICT (id_type, id_value, valid_from) DO NOTHING + RETURNING 1 AS inserted`, + [ + slice.map(row => row.instrumentId), + slice.map(row => row.idType), + slice.map(row => row.idValue), + slice.map(row => row.validFrom), + slice.map(row => row.source), + ] + ); + identifierHistoryInserted += res.rows.length; + identifierHistoryUnchanged += slice.length - res.rows.length; + } + } + + // --------------------------------------------------------------------------- + // 2. Listings + Pass 6 outcome folding + listing_symbol_history + // --------------------------------------------------------------------------- + if (input.stageB.listings.length > 0) { + const exchangeRes = await client.query<{ mic: string }>('SELECT mic FROM exchange'); + const knownMics = new Set(exchangeRes.rows.map(row => row.mic)); + + const preparedListings: PreparedListing[] = []; + const uniqueInstrumentIds = new Set(); + + for (const listing of input.stageB.listings) { + const instrumentId = instrumentIdByIsin.get(listing.primaryIsin); + if (instrumentId === undefined) { + if (skippedInstrumentIsins.has(listing.primaryIsin)) { + skippedListingInstrument += 1; + } else { + skippedListingMissingInstrument += 1; + } + continue; + } + if (!knownMics.has(listing.mic)) { + skippedListingUnknownMic += 1; + continue; + } + + const naturalKey = formatListingNaturalKey(listing); + const dbNaturalKey = formatDbListingNaturalKey( + instrumentId, + listing.mic, + listing.tickerRoot, + listing.classSuffix, + listing.currency + ); + preparedListings.push({ + naturalKey, + dbNaturalKey, + instrumentId, + mic: listing.mic, + tickerRoot: listing.tickerRoot, + classSuffix: listing.classSuffix, + currency: listing.currency, + ibConid: listing.ibConid, + ibPrimaryExchange: listing.ibPrimaryExchange, + listedFrom: listing.listedFrom, + listedTo: listing.listedTo, + outcome: outcomeByListingKey.get(naturalKey), + }); + uniqueInstrumentIds.add(instrumentId); + } + + if (preparedListings.length > 0) { + const existingByDbKey = new Map(); + const duplicateDbKeys = new Set(); + const instrumentIdList = Array.from(uniqueInstrumentIds); + + for (let offset = 0; offset < instrumentIdList.length; offset += chunkSize) { + const slice = instrumentIdList.slice(offset, offset + chunkSize); + const res = await client.query( + `SELECT + listing_id, + instrument_id, + mic, + ticker_root, + class_suffix, + btrim(currency) AS currency, + ib_conid, + ib_primary_exchange, + to_char(listed_from, 'YYYY-MM-DD') AS listed_from, + to_char(listed_to, 'YYYY-MM-DD') AS listed_to, + delist_reason, + terminal_return + FROM listing + WHERE instrument_id = ANY($1::int4[])`, + [slice] + ); + for (const row of res.rows) { + const dbKey = formatDbListingNaturalKey( + row.instrument_id, + row.mic, + row.ticker_root, + row.class_suffix, + row.currency + ); + if (existingByDbKey.has(dbKey)) { + duplicateDbKeys.add(dbKey); + } else { + existingByDbKey.set(dbKey, row); + } + } + } + + const toInsert: PreparedListing[] = []; + const toUpdate: ListingUpdatePayload[] = []; + const naturalKeyByDbKey = new Map(); + + for (const item of preparedListings) { + naturalKeyByDbKey.set(item.dbNaturalKey, item.naturalKey); + if (duplicateDbKeys.has(item.dbNaturalKey)) { + throw new Error( + `Existing listing table contains duplicate rows for natural key (instrument_id=${item.instrumentId}, mic=${item.mic}, ticker_root=${item.tickerRoot}, class_suffix=${item.classSuffix}, currency=${item.currency})` + ); + } + + const existing = existingByDbKey.get(item.dbNaturalKey); + if (existing === undefined) { + toInsert.push(item); + continue; + } + + listingIdByKey.set(item.naturalKey, existing.listing_id); + + const existingIbConid = normalizeNullableBigInt(existing.ib_conid); + const existingTerminalReturn = normalizeNullableNumeric6(existing.terminal_return); + const targetDelistReason = + item.outcome !== undefined ? item.outcome.delistReason : existing.delist_reason; + const targetTerminalReturn = + item.outcome !== undefined + ? normalizeNullableNumeric6(item.outcome.terminalReturn) + : existingTerminalReturn; + + const changed = + existingIbConid !== item.ibConid || + existing.ib_primary_exchange !== item.ibPrimaryExchange || + existing.listed_from !== item.listedFrom || + existing.listed_to !== item.listedTo || + existing.delist_reason !== targetDelistReason || + existingTerminalReturn !== targetTerminalReturn; + + if (changed) { + toUpdate.push({ + listingId: existing.listing_id, + ibConid: item.ibConid, + ibPrimaryExchange: item.ibPrimaryExchange, + listedFrom: item.listedFrom, + listedTo: item.listedTo, + delistReason: targetDelistReason, + terminalReturn: targetTerminalReturn, + }); + } else { + listingsUnchanged += 1; + } + } + + for (let offset = 0; offset < toInsert.length; offset += chunkSize) { + const slice = toInsert.slice(offset, offset + chunkSize); + const res = await client.query( + `INSERT INTO listing ( + instrument_id, + mic, + ticker_root, + class_suffix, + currency, + ib_conid, + ib_primary_exchange, + listed_from, + listed_to, + delist_reason, + terminal_return + ) + SELECT * + FROM UNNEST( + $1::int4[], + $2::varchar[], + $3::varchar[], + $4::varchar[], + $5::bpchar[], + $6::int8[], + $7::varchar[], + $8::date[], + $9::date[], + $10::varchar[], + $11::numeric[] + ) + RETURNING + listing_id, + instrument_id, + mic, + ticker_root, + class_suffix, + btrim(currency) AS currency`, + [ + slice.map(item => item.instrumentId), + slice.map(item => item.mic), + slice.map(item => item.tickerRoot), + slice.map(item => item.classSuffix), + slice.map(item => item.currency), + slice.map(item => item.ibConid), + slice.map(item => item.ibPrimaryExchange), + slice.map(item => item.listedFrom), + slice.map(item => item.listedTo), + slice.map(item => (item.outcome !== undefined ? item.outcome.delistReason : null)), + slice.map(item => + item.outcome !== undefined ? normalizeNullableNumeric6(item.outcome.terminalReturn) : null + ), + ] + ); + for (const row of res.rows) { + const dbKey = formatDbListingNaturalKey( + row.instrument_id, + row.mic, + row.ticker_root, + row.class_suffix, + row.currency + ); + const naturalKey = naturalKeyByDbKey.get(dbKey); + if (naturalKey !== undefined) { + listingIdByKey.set(naturalKey, row.listing_id); + } + } + listingsInserted += res.rows.length; + } + + for (let offset = 0; offset < toUpdate.length; offset += chunkSize) { + const slice = toUpdate.slice(offset, offset + chunkSize); + await client.query( + `UPDATE listing AS l + SET + ib_conid = u.ib_conid, + ib_primary_exchange = u.ib_primary_exchange, + listed_from = u.listed_from, + listed_to = u.listed_to, + delist_reason = u.delist_reason, + terminal_return = u.terminal_return + FROM UNNEST( + $1::int4[], + $2::int8[], + $3::varchar[], + $4::date[], + $5::date[], + $6::varchar[], + $7::numeric[] + ) AS u(listing_id, ib_conid, ib_primary_exchange, listed_from, listed_to, delist_reason, terminal_return) + WHERE l.listing_id = u.listing_id`, + [ + slice.map(entry => entry.listingId), + slice.map(entry => entry.ibConid), + slice.map(entry => entry.ibPrimaryExchange), + slice.map(entry => entry.listedFrom), + slice.map(entry => entry.listedTo), + slice.map(entry => entry.delistReason), + slice.map(entry => entry.terminalReturn), + ] + ); + listingsUpdated += slice.length; + } + + // listing_symbol_history for all persisted listings (replaces loader-generated interval + // when listed_from changes while preserving unrelated historical aliases). + const symbolHistoryRows: PreparedSymbolHistoryRow[] = []; + for (const item of preparedListings) { + const listingId = listingIdByKey.get(item.naturalKey); + if (listingId === undefined) { + continue; + } + const existing = existingByDbKey.get(item.dbNaturalKey); + const ticker = + item.classSuffix.length > 0 ? `${item.tickerRoot}.${item.classSuffix}` : item.tickerRoot; + symbolHistoryRows.push({ + listingId, + ticker, + validFrom: item.listedFrom ?? DEFAULT_VALID_FROM, + validTo: item.listedTo, + source: 'eod', + previousValidFrom: + existing !== undefined ? (existing.listed_from ?? DEFAULT_VALID_FROM) : null, + }); + } + + for (let offset = 0; offset < symbolHistoryRows.length; offset += chunkSize) { + const slice = symbolHistoryRows.slice(offset, offset + chunkSize); + const res = await client.query( + `WITH incoming AS ( + SELECT * + FROM UNNEST( + $1::int4[], + $2::varchar[], + $3::date[], + $4::date[], + $5::varchar[], + $6::date[] + ) AS u(listing_id, ticker, valid_from, valid_to, source, prev_valid_from) + ), + deleted_stale AS ( + DELETE FROM listing_symbol_history AS lsh + USING incoming AS i + WHERE lsh.listing_id = i.listing_id + AND lsh.ticker = i.ticker + AND lsh.source = i.source + AND i.prev_valid_from IS NOT NULL + AND lsh.valid_from = i.prev_valid_from + AND lsh.valid_from IS DISTINCT FROM i.valid_from + RETURNING lsh.listing_id, lsh.ticker + ), + upserted AS ( + INSERT INTO listing_symbol_history ( + listing_id, + ticker, + valid_from, + valid_to, + source + ) + SELECT + i.listing_id, + i.ticker, + i.valid_from, + i.valid_to, + i.source + FROM incoming AS i + ON CONFLICT (listing_id, ticker, valid_from) DO UPDATE SET + valid_to = EXCLUDED.valid_to + WHERE listing_symbol_history.valid_to IS DISTINCT FROM EXCLUDED.valid_to + RETURNING listing_id, ticker, (xmax = 0) AS inserted + ) + SELECT + ( + SELECT count(*)::int + FROM upserted u + WHERE u.inserted + AND NOT EXISTS ( + SELECT 1 + FROM deleted_stale d + WHERE d.listing_id = u.listing_id + AND d.ticker = u.ticker + ) + ) AS inserted_count, + ( + SELECT count(*)::int + FROM ( + SELECT listing_id, ticker FROM upserted WHERE NOT inserted + UNION + SELECT listing_id, ticker FROM deleted_stale + ) AS updated_keys + ) AS updated_count`, + [ + slice.map(row => row.listingId), + slice.map(row => row.ticker), + slice.map(row => row.validFrom), + slice.map(row => row.validTo), + slice.map(row => row.source), + slice.map(row => row.previousValidFrom), + ] + ); + const counts = res.rows[0]; + const chunkInserted = Number(counts?.inserted_count ?? 0); + const chunkUpdated = Number(counts?.updated_count ?? 0); + listingSymbolHistoryInserted += chunkInserted; + listingSymbolHistoryUpdated += chunkUpdated; + listingSymbolHistoryUnchanged += slice.length - chunkInserted - chunkUpdated; + } + } + } + + // Reconcile Pass 6 listing outcome counts + if (input.pass6 !== undefined) { + for (const outcome of input.pass6.listingOutcomes) { + const key = formatListingNaturalKey(outcome.listingKey); + if (listingIdByKey.has(key)) { + pass6OutcomesApplied += 1; + } else { + pass6OutcomesSkippedMissingListing += 1; + } + } + } + + // --------------------------------------------------------------------------- + // 3. provider_mapping upsert + override precedence + // --------------------------------------------------------------------------- + const preparedMappings: PreparedProviderMapping[] = []; + for (const candidate of input.stageB.providerMappings) { + const listingId = listingIdByKey.get(formatListingNaturalKey(candidate.listingKey)); + if (listingId === undefined) { + skippedMappingMissingListing += 1; + continue; + } + preparedMappings.push({ + source: candidate.source, + sourceId: candidate.sourceId, + validFrom: candidate.validFrom ?? DEFAULT_VALID_FROM, + validTo: candidate.validTo, + listingId, + method: candidate.method, + confidence: PROVIDER_MAPPING_CONFIDENCE[candidate.method].toFixed(3), + }); + } + + const mappingOutcomeByKey = new Map(); + for (const row of preparedMappings) { + mappingOutcomeByKey.set(`${row.source}\u0000${row.sourceId}\u0000${row.validFrom}`, 'unchanged'); + } + + for (let offset = 0; offset < preparedMappings.length; offset += chunkSize) { + const slice = preparedMappings.slice(offset, offset + chunkSize); + const res = await client.query( + `INSERT INTO provider_mapping ( + source, + source_id, + valid_from, + valid_to, + listing_id, + method, + confidence, + price_corr + ) + SELECT + u.source, + u.source_id, + u.valid_from, + u.valid_to, + u.listing_id, + u.method, + u.confidence, + NULL::numeric(5, 4) + FROM UNNEST( + $1::varchar[], + $2::varchar[], + $3::date[], + $4::date[], + $5::int4[], + $6::varchar[], + $7::numeric[] + ) AS u(source, source_id, valid_from, valid_to, listing_id, method, confidence) + ON CONFLICT (source, source_id, valid_from) DO UPDATE SET + valid_to = EXCLUDED.valid_to, + listing_id = EXCLUDED.listing_id, + method = EXCLUDED.method, + confidence = EXCLUDED.confidence, + price_corr = CASE + WHEN provider_mapping.listing_id = EXCLUDED.listing_id THEN provider_mapping.price_corr + ELSE NULL + END + WHERE NOT EXISTS ( + SELECT 1 + FROM override o + WHERE o.source = provider_mapping.source + AND o.source_id = provider_mapping.source_id + AND o.valid_from = provider_mapping.valid_from + ) + AND ( + provider_mapping.valid_to IS DISTINCT FROM EXCLUDED.valid_to + OR provider_mapping.listing_id IS DISTINCT FROM EXCLUDED.listing_id + OR provider_mapping.method IS DISTINCT FROM EXCLUDED.method + OR provider_mapping.confidence IS DISTINCT FROM EXCLUDED.confidence + ) + RETURNING + source, + source_id, + to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + (xmax = 0) AS inserted`, + [ + slice.map(row => row.source), + slice.map(row => row.sourceId), + slice.map(row => row.validFrom), + slice.map(row => row.validTo), + slice.map(row => row.listingId), + slice.map(row => row.method), + slice.map(row => row.confidence), + ] + ); + for (const row of res.rows) { + const key = `${row.source}\u0000${row.source_id}\u0000${row.valid_from}`; + mappingOutcomeByKey.set(key, row.inserted ? 'inserted' : 'updated'); + } + } + + // Remove stale open-ended DEFAULT_VALID_FROM ('1900-01-01') fallback rows for any + // (source, source_id) that now has only dated mappings in this run, while preserving + // override-protected rows and untouched source IDs. + const fallbackSourceKeys = new Set(); + for (const row of preparedMappings) { + if (row.validFrom === DEFAULT_VALID_FROM) { + fallbackSourceKeys.add(`${row.source}\u0000${row.sourceId}`); + } + } + const staleFallbackTargets: Array<{ source: string; sourceId: string }> = []; + const seenStaleFallbackKeys = new Set(); + for (const row of preparedMappings) { + const pairKey = `${row.source}\u0000${row.sourceId}`; + if (fallbackSourceKeys.has(pairKey) || seenStaleFallbackKeys.has(pairKey)) { + continue; + } + seenStaleFallbackKeys.add(pairKey); + staleFallbackTargets.push({ source: row.source, sourceId: row.sourceId }); + } + + for (let offset = 0; offset < staleFallbackTargets.length; offset += chunkSize) { + const slice = staleFallbackTargets.slice(offset, offset + chunkSize); + const deleteRes = await client.query( + `WITH deleted AS ( + DELETE FROM provider_mapping AS pm + USING UNNEST( + $1::varchar[], + $2::varchar[] + ) AS u(source, source_id) + WHERE pm.source = u.source + AND pm.source_id = u.source_id + AND pm.valid_from = $3::date + AND pm.method <> 'override' + AND NOT EXISTS ( + SELECT 1 + FROM override o + WHERE o.source = pm.source + AND o.source_id = pm.source_id + AND o.valid_from = pm.valid_from + ) + RETURNING 1 + ) + SELECT count(*)::int AS deleted_count FROM deleted`, + [ + slice.map(target => target.source), + slice.map(target => target.sourceId), + DEFAULT_VALID_FROM, + ] + ); + providerMappingsDeletedStaleFallback += Number(deleteRes.rows[0]?.deleted_count ?? 0); + } + + // Enforce override precedence unconditionally across all rows in `override` and count each + // mapping key once according to its final insert/update/unchanged outcome across matcher + override. + const overrideRes = await client.query( + `WITH enforced AS ( + INSERT INTO provider_mapping ( + source, + source_id, + valid_from, + valid_to, + listing_id, + method, + confidence, + price_corr + ) + SELECT + o.source, + o.source_id, + o.valid_from, + o.valid_to, + o.listing_id, + 'override', + 1.000, + NULL::numeric(5, 4) + FROM override o + ON CONFLICT (source, source_id, valid_from) DO UPDATE SET + listing_id = EXCLUDED.listing_id, + valid_to = EXCLUDED.valid_to, + method = 'override', + confidence = 1.000, + price_corr = NULL + WHERE provider_mapping.listing_id IS DISTINCT FROM EXCLUDED.listing_id + OR provider_mapping.valid_to IS DISTINCT FROM EXCLUDED.valid_to + OR provider_mapping.method IS DISTINCT FROM 'override' + OR provider_mapping.confidence IS DISTINCT FROM 1.000 + OR provider_mapping.price_corr IS NOT NULL + RETURNING + source, + source_id, + valid_from, + (xmax = 0) AS inserted + ) + SELECT + o.source, + o.source_id, + to_char(o.valid_from, 'YYYY-MM-DD') AS valid_from, + e.inserted + FROM override o + LEFT JOIN enforced e + ON e.source = o.source + AND e.source_id = o.source_id + AND e.valid_from = o.valid_from` + ); + const overridesApplied = overrideRes.rows.length; + for (const row of overrideRes.rows) { + const key = `${row.source}\u0000${row.source_id}\u0000${row.valid_from}`; + const prev = mappingOutcomeByKey.get(key); + if (row.inserted === true) { + mappingOutcomeByKey.set(key, 'inserted'); + } else if (row.inserted === false) { + if (prev !== 'inserted') { + mappingOutcomeByKey.set(key, 'updated'); + } + } else if (prev === undefined) { + mappingOutcomeByKey.set(key, 'unchanged'); + } + } + + for (const outcome of mappingOutcomeByKey.values()) { + if (outcome === 'inserted') { + providerMappingsInserted += 1; + } else if (outcome === 'updated') { + providerMappingsUpdated += 1; + } else { + providerMappingsUnchanged += 1; + } + } + + // --------------------------------------------------------------------------- + // 4. Pass 5 resolution_conflict (all statuses preserved; no duplicate open rows) + // --------------------------------------------------------------------------- + const { uniqueConflicts, deduplicatedCount: conflictsDeduplicated } = + collectAndDeduplicateConflicts(input); + + if (uniqueConflicts.length > 0) { + const nonPass4Conflicts: PreparedConflict[] = []; + const pass4Conflicts: PreparedConflict[] = []; + for (const conflict of uniqueConflicts) { + if (conflict.isPass4) { + pass4Conflicts.push(conflict); + } else { + nonPass4Conflicts.push(conflict); + } + } + + const existingConflictKeys = new Set(); + for (let offset = 0; offset < nonPass4Conflicts.length; offset += chunkSize) { + const slice = nonPass4Conflicts.slice(offset, offset + chunkSize); + const res = await client.query( + `SELECT DISTINCT + rc.source, + rc.source_id, + rc.conflict_kind + FROM resolution_conflict rc + INNER JOIN UNNEST( + $1::varchar[], + $2::varchar[], + $3::varchar[] + ) AS u(source, source_id, conflict_kind) + ON rc.source = u.source + AND rc.source_id = u.source_id + AND rc.conflict_kind = u.conflict_kind`, + [ + slice.map(c => c.source), + slice.map(c => c.sourceId), + slice.map(c => c.conflictKind), + ] + ); + for (const row of res.rows) { + existingConflictKeys.add(`${row.source}\u0000${row.source_id}\u0000${row.conflict_kind}`); + } + } + + const existingPass4ConflictKeys = new Set(); + for (let offset = 0; offset < pass4Conflicts.length; offset += chunkSize) { + const slice = pass4Conflicts.slice(offset, offset + chunkSize); + const res = await client.query( + `SELECT DISTINCT + u.row_idx + FROM resolution_conflict rc + INNER JOIN UNNEST( + $1::varchar[], + $2::varchar[], + $3::varchar[], + $4::jsonb[], + $5::int4[] + ) AS u(source, source_id, conflict_kind, detail, row_idx) + ON rc.source = u.source + AND rc.source_id = u.source_id + AND rc.conflict_kind = u.conflict_kind + AND rc.detail = u.detail`, + [ + slice.map(c => c.source), + slice.map(c => c.sourceId), + slice.map(c => c.conflictKind), + slice.map(c => c.detailJson), + slice.map((_, idx) => idx), + ] + ); + for (const row of res.rows) { + const matched = slice[row.row_idx]; + if (matched !== undefined) { + existingPass4ConflictKeys.add(matched.key); + } + } + } + + const toInsertConflicts: PreparedConflict[] = []; + for (const conflict of uniqueConflicts) { + const exists = conflict.isPass4 + ? existingPass4ConflictKeys.has(conflict.key) + : existingConflictKeys.has(conflict.key); + if (exists) { + conflictsUnchanged += 1; + } else { + toInsertConflicts.push(conflict); + } + } + + for (let offset = 0; offset < toInsertConflicts.length; offset += chunkSize) { + const slice = toInsertConflicts.slice(offset, offset + chunkSize); + await client.query( + `INSERT INTO resolution_conflict ( + source, + source_id, + conflict_kind, + detail, + status + ) + SELECT + u.source, + u.source_id, + u.conflict_kind, + u.detail, + 'open' + FROM UNNEST( + $1::varchar[], + $2::varchar[], + $3::varchar[], + $4::jsonb[] + ) AS u(source, source_id, conflict_kind, detail)`, + [ + slice.map(c => c.source), + slice.map(c => c.sourceId), + slice.map(c => c.conflictKind), + slice.map(c => c.detailJson), + ] + ); + conflictsInserted += slice.length; + } + } + + // --------------------------------------------------------------------------- + // 5. Pass 6 corporate_action_continuity + // --------------------------------------------------------------------------- + if (input.pass6 !== undefined && input.pass6.continuities.length > 0) { + const preparedContinuities: PreparedContinuity[] = []; + for (const continuity of input.pass6.continuities) { + const fromListingId = listingIdByKey.get(formatListingNaturalKey(continuity.fromListingKey)); + const toListingId = listingIdByKey.get(formatListingNaturalKey(continuity.toListingKey)); + if (fromListingId === undefined && toListingId === undefined) { + skippedContinuityMissingBoth += 1; + continue; + } + if (fromListingId === undefined) { + skippedContinuityMissingFrom += 1; + continue; + } + if (toListingId === undefined) { + skippedContinuityMissingTo += 1; + continue; + } + preparedContinuities.push({ + fromListingId, + toListingId, + effectiveDate: continuity.effectiveDate, + kind: continuity.kind, + }); + } + + for (let offset = 0; offset < preparedContinuities.length; offset += chunkSize) { + const slice = preparedContinuities.slice(offset, offset + chunkSize); + const res = await client.query( + `INSERT INTO corporate_action_continuity ( + from_listing_id, + to_listing_id, + effective_date, + kind + ) + SELECT * + FROM UNNEST( + $1::int4[], + $2::int4[], + $3::date[], + $4::varchar[] + ) + ON CONFLICT (from_listing_id, effective_date) DO UPDATE SET + to_listing_id = EXCLUDED.to_listing_id, + kind = EXCLUDED.kind + WHERE corporate_action_continuity.to_listing_id IS DISTINCT FROM EXCLUDED.to_listing_id + OR corporate_action_continuity.kind IS DISTINCT FROM EXCLUDED.kind + RETURNING (xmax = 0) AS inserted`, + [ + slice.map(row => row.fromListingId), + slice.map(row => row.toListingId), + slice.map(row => row.effectiveDate), + slice.map(row => row.kind), + ] + ); + let chunkInserted = 0; + let chunkUpdated = 0; + for (const row of res.rows) { + if (row.inserted) { + chunkInserted += 1; + } else { + chunkUpdated += 1; + } + } + continuitiesInserted += chunkInserted; + continuitiesUpdated += chunkUpdated; + continuitiesUnchanged += slice.length - chunkInserted - chunkUpdated; + } + } + + return { + instrumentsInserted, + instrumentsUpdated, + instrumentsUnchanged, + instrumentsSkipped: skippedMissingCanonicalName + skippedMissingSecurityType, + + identifierHistoryInserted, + identifierHistoryUnchanged, + + listingsInserted, + listingsUpdated, + listingsUnchanged, + listingsSkipped: + skippedListingInstrument + skippedListingMissingInstrument + skippedListingUnknownMic, + + listingSymbolHistoryInserted, + listingSymbolHistoryUpdated, + listingSymbolHistoryUnchanged, + + providerMappingsInserted, + providerMappingsUpdated, + providerMappingsUnchanged, + providerMappingsSkipped: skippedMappingMissingListing, + providerMappingsDeletedStaleFallback, + + overridesApplied, + + conflictsInserted, + conflictsUnchanged, + conflictsDeduplicated, + + pass6OutcomesApplied, + pass6OutcomesSkipped: pass6OutcomesSkippedMissingListing, + + continuitiesInserted, + continuitiesUpdated, + continuitiesUnchanged, + continuitiesSkipped: + skippedContinuityMissingFrom + skippedContinuityMissingTo + skippedContinuityMissingBoth, + + skippedByReason: { + instruments: { + missing_canonical_name: skippedMissingCanonicalName, + missing_security_type: skippedMissingSecurityType, + }, + listings: { + skipped_instrument: skippedListingInstrument, + missing_instrument: skippedListingMissingInstrument, + unknown_mic: skippedListingUnknownMic, + }, + providerMappings: { + missing_listing: skippedMappingMissingListing, + }, + pass6Outcomes: { + missing_listing: pass6OutcomesSkippedMissingListing, + }, + continuities: { + missing_from_listing: skippedContinuityMissingFrom, + missing_to_listing: skippedContinuityMissingTo, + missing_both_listings: skippedContinuityMissingBoth, + }, + }, + instrumentIdByIsin, + listingIdByKey, + }; +} + +/** + * Idempotently persists Pass 3 (Stage A/B), Pass 5 (`resolution_conflict`), and Pass 6 + * (`delisting-chains`) in-memory results into the PostgreSQL security master tables inside a + * single transaction guarded by a schema-scoped `pg_advisory_xact_lock`. + * + * Guarantees: + * - Permanent `instrument_id` and `listing_id` values across re-runs and incremental additions. + * - Unconditional `override` precedence (`method = 'override'`, `confidence = 1.000`). + * - Stale fallback cleanup: when a run supplies only dated `provider_mapping` rows for a + * `(source, source_id)`, any leftover `1900-01-01` (`DEFAULT_VALID_FROM`) non-override fallback + * row not protected by `override` is deleted inside the same transaction and counted in + * `providerMappingsDeletedStaleFallback`. + * - No guessing: instruments missing `canonicalName` or `securityTypeByIsin` and listings with + * unknown MICs are skipped and counted along with all dependent rows. + * - Batched `UNNEST` writes (default/max chunk size `5000`) using parameterised SQL only. + * + * Benchmark: run `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts` + * against an isolated `stock_bot_safety_*` schema to execute the fixed-seed 20,000-instrument / + * 20,000-listing / 60,000-mapping throughput benchmark. + */ +export async function persistSecurityMaster( + client: SecurityMasterQueryable, + input: PersistSecurityMasterInput, + options: PersistSecurityMasterOptions = {} +): Promise { + assertDedicatedQueryable(client); + const chunkSize = validateChunkSize(options.chunkSize); + const { outcomeByListingKey } = validateInputsAndIndexPass6(input); + + if (activePersistClients.has(client)) { + throw new Error( + 'persistSecurityMaster does not allow overlapping calls on the same client; use a dedicated PoolClient per concurrent call' + ); + } + activePersistClients.add(client); + + try { + await client.query('BEGIN'); + try { + await client.query( + 'SELECT pg_advisory_xact_lock($1::int4, hashtext(current_schema()))', + [SECURITY_MASTER_PERSIST_LOCK_NAMESPACE] + ); + const result = await persistWithinTransaction(client, input, chunkSize, outcomeByListingKey); + await client.query('COMMIT'); + return result; + } catch (error) { + try { + await client.query('ROLLBACK'); + } catch { + // Preserve the original failure when ROLLBACK itself errors on a broken session. + } + throw error; + } + } finally { + activePersistClients.delete(client); + } +} + +// Re-export type aliases used by callers without forcing extra imports. +export type { StageAInstrumentCandidate, StageBListingCandidate, StageBProviderMappingCandidate }; diff --git a/apps/stock/data-pipeline/src/security-master/run-security-master.ts b/apps/stock/data-pipeline/src/security-master/run-security-master.ts new file mode 100644 index 00000000..d8090a05 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/run-security-master.ts @@ -0,0 +1,677 @@ +import { mkdir, writeFile } from 'node:fs/promises'; +import { dirname, join } from 'node:path'; +import { getLogger } from '@stock-bot/logger'; +import { MongoDBClient } from '@stock-bot/mongodb'; +import { PostgreSQLClient } from '@stock-bot/postgres'; +import { + assertEnvironmentSafety, + initializeStockConfig, + type StockAppConfig, +} from '@stock-bot/stock-config'; +import { + computeBarSpans, + normalizeBarDate, + type BarSpanAggregateReader, + type ComputeBarSpansOptions, + type ComputeBarSpansResult, +} from '../normalization/bar-spans'; +import { + classifySourceExchanges, + compareAscii, + EXCHANGE_SOURCES, + ISO_EXCHANGE_SEEDS, + normalizeRawExchangeDoc, + type ExchangeClassificationResult, + type ExchangeSource, + type SourceExchangeRecord, +} from './exchange-pass1'; +import { + resolveReadOnlyMongoClientConfig, + SOURCE_EXCHANGE_COLLECTIONS, +} from './generate-exchange-seed'; +import { + canonicalizeJsonValue, + persistSecurityMaster, + type PersistSecurityMasterResult, + type SecurityMasterQueryable, + type SecurityMasterQueryResult, +} from './persist'; +import { composeSecurityMasterRun, type ComposeSecurityMasterRunResult } from './run'; +import { + createExchangeSourceLookup, + createReadOnlyMongoSourceSymbolReader, + readSecurityMasterSources, + type ExchangeSourceLookup, + type ReadOnlyMongoCollectionClient, + type SecurityMasterSourcesResult, +} from './source-symbol-readers'; + +export const SECURITY_MASTER_OUTPUT_FILES = Object.freeze({ + matchReport: 'match-report.md', + conflictsCsv: 'conflicts.csv', + overrideTemplateSql: 'override-template.sql', + runStatsJson: 'run-stats.json', +} as const); + +export const RUN_SECURITY_MASTER_USAGE = [ + 'Usage: bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts --as-of --out-dir [--persist] [--help]', + '', + 'Options:', + ' --as-of Required. Calendar reference date for Pass 6 delisting classification.', + ' --out-dir Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.', + ' --persist Optional. Persist security-master rows to isolated dev PostgreSQL after running safety guards (default: off).', + ' --help Show this help message and exit.', +].join('\n'); + +export type ParsedRunSecurityMasterArgs = + | { readonly help: true } + | { + readonly help: false; + readonly asOfDate: string; + readonly outDir: string; + readonly persist: boolean; + }; + +export interface SecurityMasterPostgresHandle { + readonly queryable: SecurityMasterQueryable; + close(): Promise | void; +} + +export interface RunSecurityMasterDeps { + readonly mongoCollectionClient: ReadOnlyMongoCollectionClient; + readonly barSpanReader: BarSpanAggregateReader; + readonly closeMongo?: () => Promise | void; + readonly exchangeClassification?: ExchangeClassificationResult; + readonly exchangeLookup?: ExchangeSourceLookup; + readonly assertSafety?: () => void; + readonly createPostgresClient?: () => + | Promise + | SecurityMasterPostgresHandle; + readonly persistFn?: typeof persistSecurityMaster; + readonly writeFile?: (filePath: string, content: string) => Promise | void; + readonly writeStdout?: (text: string) => void; +} + +export interface RunSecurityMasterOptions { + readonly asOfDate: string; + readonly outDir: string; + readonly persist?: boolean; + readonly countries?: readonly string[] | null; + readonly batchSize?: number; + readonly barSpans?: Omit; +} + +export interface RunSecurityMasterOutput { + readonly asOfDate: string; + readonly outDir: string; + readonly persist: boolean; + readonly filesWritten: readonly string[]; + readonly exchanges: ExchangeClassificationResult; + readonly exchangeCountsByCollection: Readonly>; + readonly sources: SecurityMasterSourcesResult; + readonly barSpans: ComputeBarSpansResult; + readonly composed: ComposeSecurityMasterRunResult; + readonly persistResult: PersistSecurityMasterResult | null; + readonly runStatsJson: string; + readonly summary: string; +} + +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; + +function isValidAsOfDate(value: string): boolean { + return EXACT_YMD_PATTERN.test(value) && normalizeBarDate(value) === value; +} + +function usageError(message: string): Error { + return new Error(`${message}\n\n${RUN_SECURITY_MASTER_USAGE}`); +} + +function wrapStepError(step: string, error: unknown): Error { + const detail = error instanceof Error ? error.message : String(error); + return new Error(`Security master step "${step}" failed: ${detail}`, { cause: error }); +} + +function collectSortedUniqueIds(ids: readonly string[]): string[] { + const unique = new Set(); + for (let i = 0; i < ids.length; i++) { + const id = ids[i]; + if (typeof id === 'string' && id.length > 0) { + unique.add(id); + } + } + return Array.from(unique).sort(compareAscii); +} + +async function defaultWriteFile(filePath: string, content: string): Promise { + await mkdir(dirname(filePath), { recursive: true }); + await writeFile(filePath, content, 'utf8'); +} + +export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSecurityMasterArgs { + let help = false; + let asOfDate: string | undefined; + let outDir: string | undefined; + let persist = false; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--help') { + help = true; + continue; + } + if (arg === '--persist') { + persist = true; + continue; + } + if (arg === '--as-of') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --as-of'); + } + asOfDate = value; + i += 1; + continue; + } + if (arg?.startsWith('--as-of=')) { + const value = arg.slice('--as-of='.length); + if (value.trim().length === 0) { + throw usageError('Missing value for --as-of'); + } + asOfDate = value; + continue; + } + if (arg === '--out-dir') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --out-dir'); + } + outDir = value; + i += 1; + continue; + } + if (arg?.startsWith('--out-dir=')) { + const value = arg.slice('--out-dir='.length); + if (value.trim().length === 0) { + throw usageError('Missing value for --out-dir'); + } + outDir = value; + continue; + } + throw usageError(`Unknown argument: ${String(arg)}`); + } + + if (help) { + return { help: true }; + } + + if (asOfDate === undefined) { + throw usageError('Missing required argument: --as-of '); + } + if (!isValidAsOfDate(asOfDate)) { + throw usageError( + `Invalid --as-of date "${asOfDate}": expected a valid calendar date in YYYY-MM-DD format` + ); + } + if (outDir === undefined || outDir.trim().length === 0) { + throw usageError('Missing required argument: --out-dir '); + } + + return { + help: false, + asOfDate, + outDir, + persist, + }; +} + +export function assertSecurityMasterPersistSafety( + config: StockAppConfig, + env: Record = process.env +): void { + const pg = config.database.postgres; + if (!pg.enabled) { + throw new Error('PostgreSQL is disabled in configuration; cannot run with --persist'); + } + + const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _stripped, ...safeEnv } = env; + assertEnvironmentSafety(config, 'dataPipeline', safeEnv); + + if (config.environment !== 'development') { + throw new Error( + `Security master --persist is restricted to NODE_ENV=development targeting isolated dev PostgreSQL ` + + `(got environment "${config.environment}", target ${pg.host}:${pg.port}/${pg.database}).` + ); + } + + if (pg.database === 'trading_bot' || pg.port === 5432) { + throw new Error( + `Security master --persist cannot target QA PostgreSQL (${pg.host}:${pg.port}/${pg.database}); ` + + 'configure isolated dev PostgreSQL (localhost:5433/trading_bot_dev).' + ); + } + + if (!pg.database.endsWith('_dev') && !pg.database.startsWith('stock_bot_safety')) { + throw new Error( + `Security master --persist requires an isolated dev PostgreSQL database ` + + `(ending in "_dev" or "stock_bot_safety*"), got "${pg.database}".` + ); + } +} + +export function formatRunSecurityMasterSummary( + params: Pick< + RunSecurityMasterOutput, + 'asOfDate' | 'outDir' | 'persist' | 'filesWritten' | 'composed' + > +): string { + const { asOfDate, outDir, persist, composed } = params; + const resolutionParts = composed.report.resolutionBySource.map(row => { + const pct = + row.eligibleResolvedPct === null + ? 'n/a' + : `${(row.eligibleResolvedPct * 100).toFixed(1)}%`; + return `${row.source}=${pct} (${row.matched}/${row.eligibleTotal})`; + }); + + const fileNames = [ + SECURITY_MASTER_OUTPUT_FILES.matchReport, + SECURITY_MASTER_OUTPUT_FILES.conflictsCsv, + SECURITY_MASTER_OUTPUT_FILES.overrideTemplateSql, + SECURITY_MASTER_OUTPUT_FILES.runStatsJson, + ]; + + const lines = [ + `Security master run complete (as-of ${asOfDate})`, + ` Instruments: ${composed.stageA.instruments.length} | Listings: ${composed.stageB.listings.length} | Conflicts: ${composed.report.conflicts.length}`, + ` Resolution (eligible): ${resolutionParts.length > 0 ? resolutionParts.join(', ') : 'none'}`, + ` Pass 4 price cross-check: ${composed.stats.pass4.status} (sample closes not yet wired)`, + ` Files written (${outDir}): ${fileNames.join(', ')}`, + ` Persisted: ${persist ? 'yes' : 'no (dry-run)'}`, + ]; + + return `${lines.join('\n')}\n`; +} + +export async function runSecurityMaster( + deps: RunSecurityMasterDeps, + options: RunSecurityMasterOptions +): Promise { + const persist = options.persist === true; + let mongoCloseError: unknown = null; + let output: RunSecurityMasterOutput; + + try { + if (!isValidAsOfDate(options.asOfDate)) { + throw wrapStepError( + 'validate-options', + new Error( + `Invalid asOfDate "${options.asOfDate}": expected a valid calendar date in YYYY-MM-DD format` + ) + ); + } + if (typeof options.outDir !== 'string' || options.outDir.trim().length === 0) { + throw wrapStepError('validate-options', new Error('outDir must be a non-empty string')); + } + + // Step 1: Environment safety check before opening PostgreSQL or reading Mongo when --persist is requested. + if (persist) { + try { + if (typeof deps.assertSafety !== 'function') { + throw new Error( + 'Persisting security master requires an assertSafety guard to be configured' + ); + } + if (typeof deps.createPostgresClient !== 'function') { + throw new Error( + 'Persisting security master requires a createPostgresClient factory to be configured' + ); + } + deps.assertSafety(); + } catch (error) { + throw wrapStepError('env-safety', error); + } + } + + // Step 2: Read-only exchange classification (Pass 1) and lookup construction. + let sourceReader: ReturnType; + let exchanges: ExchangeClassificationResult; + let exchangeLookup: ExchangeSourceLookup; + const exchangeCountsByCollection: Record = { + eod: 0, + ib: 0, + qm: 0, + ceo: 0, + }; + + try { + sourceReader = createReadOnlyMongoSourceSymbolReader(deps.mongoCollectionClient); + + if (deps.exchangeClassification !== undefined) { + exchanges = deps.exchangeClassification; + } else { + const normalizedRecords: SourceExchangeRecord[] = []; + for (const source of EXCHANGE_SOURCES) { + const collectionName = SOURCE_EXCHANGE_COLLECTIONS[source]; + const cursor = await sourceReader.find>(collectionName, {}); + let count = 0; + for await (const doc of cursor) { + count += 1; + normalizedRecords.push(normalizeRawExchangeDoc(source, doc)); + } + exchangeCountsByCollection[source] = count; + } + exchanges = classifySourceExchanges(normalizedRecords, { + knownExchanges: ISO_EXCHANGE_SEEDS, + }); + } + + exchangeLookup = deps.exchangeLookup ?? createExchangeSourceLookup(exchanges.mapped); + } catch (error) { + throw wrapStepError('read-exchanges', error); + } + + // Step 3: Stream read-only symbol collections into Stage A / Stage B inputs. + let sources: SecurityMasterSourcesResult; + try { + sources = await readSecurityMasterSources(sourceReader, { + exchangeLookup, + countries: options.countries, + batchSize: options.batchSize, + }); + } catch (error) { + throw wrapStepError('read-sources', error); + } + + // Step 4: Compute targeted observed bar spans for in-scope EOD and QM listings. + let barSpans: ComputeBarSpansResult; + try { + const eodIds = collectSortedUniqueIds( + sources.stageBInput.eodListings.map(entry => entry.sourceId) + ); + const qmIds = collectSortedUniqueIds( + sources.stageBInput.tickerSources + .filter(entry => entry.source === 'qm') + .map(entry => entry.sourceId) + ); + barSpans = await computeBarSpans(deps.barSpanReader, { + sources: ['eod', 'qm'], + ...options.barSpans, + sourceIdsBySource: { + eod: eodIds, + qm: qmIds, + }, + }); + } catch (error) { + throw wrapStepError('compute-bar-spans', error); + } + + // Step 5: Compose Stage A -> Stage B -> Pass 6 -> Report + PersistInput (Pass 4 omitted). + let composed: ComposeSecurityMasterRunResult; + try { + composed = composeSecurityMasterRun( + { + sources, + barSpans, + exchanges, + }, + { + asOfDate: options.asOfDate, + } + ); + } catch (error) { + throw wrapStepError('compose', error); + } + + // Step 6: Write deterministic artifacts into outDir. + const statsArtifact = { + asOfDate: options.asOfDate, + pass4Wired: false, + exchanges: { + countsByCollection: exchangeCountsByCollection, + mapped: exchanges.mapped.length, + unresolved: exchanges.unresolved.length, + total: exchanges.mapped.length + exchanges.unresolved.length, + }, + readers: sources.stats, + securityTypes: { + stats: sources.securityTypeStats, + loaderStats: sources.securityTypeLoaderStats, + unknownCount: sources.unknownSecurityTypes.length, + conflictCount: sources.securityTypeConflicts.length, + }, + barSpans: { + bySource: barSpans.bySource, + skipped: barSpans.skipped, + totalRowsRead: barSpans.totalRowsRead, + totalSpans: barSpans.totalSpans, + }, + compose: composed.stats, + reportSummary: { + instruments: composed.stageA.instruments.length, + listings: composed.stageB.listings.length, + providerMappings: composed.stageB.providerMappings.length, + conflicts: composed.report.conflicts.length, + exchangeCoverage: composed.report.exchangeCoverage, + resolutionBySource: composed.report.resolutionBySource, + resolutionByCountry: composed.report.resolutionByCountry, + meetsExitThresholds: composed.report.meetsExitThresholds, + }, + }; + const runStatsJson = `${JSON.stringify(canonicalizeJsonValue(statsArtifact), null, 2)}\n`; + + const writer = deps.writeFile ?? defaultWriteFile; + const filesToWrite: ReadonlyArray = [ + [join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.matchReport), composed.reportMarkdown], + [join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.conflictsCsv), composed.conflictsCsv], + [ + join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.overrideTemplateSql), + composed.overrideTemplateSql, + ], + [join(options.outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), runStatsJson], + ]; + const filesWritten = filesToWrite.map(([filePath]) => filePath); + + try { + for (const [filePath, content] of filesToWrite) { + await writer(filePath, content); + } + } catch (error) { + throw wrapStepError('write-files', error); + } + + // Step 7: Optional persistence to PostgreSQL (only when --persist is enabled). + let persistResult: PersistSecurityMasterResult | null = null; + if (persist) { + try { + const createPg = deps.createPostgresClient; + if (typeof createPg !== 'function') { + throw new Error( + 'Persisting security master requires a createPostgresClient factory to be configured' + ); + } + const pgHandle = await createPg(); + let pgCloseError: unknown = null; + try { + const persistFn = deps.persistFn ?? persistSecurityMaster; + persistResult = await persistFn(pgHandle.queryable, composed.persistInput); + } finally { + try { + await pgHandle.close(); + } catch (closeError) { + pgCloseError = closeError; + } + } + if (pgCloseError !== null) { + throw pgCloseError; + } + } catch (error) { + throw wrapStepError('persist', error); + } + } + + // Step 8: Build concise one-screen summary (emitted only after cleanup succeeds). + const summary = formatRunSecurityMasterSummary({ + asOfDate: options.asOfDate, + outDir: options.outDir, + persist, + filesWritten, + composed, + }); + + output = { + asOfDate: options.asOfDate, + outDir: options.outDir, + persist, + filesWritten, + exchanges, + exchangeCountsByCollection, + sources, + barSpans, + composed, + persistResult, + runStatsJson, + summary, + }; + } finally { + if (deps.closeMongo) { + try { + await deps.closeMongo(); + } catch (closeError) { + mongoCloseError = closeError; + } + } + } + + if (mongoCloseError !== null) { + throw wrapStepError('close-mongo', mongoCloseError); + } + + const writeStdout = + deps.writeStdout ?? + ((text: string) => { + process.stdout.write(text); + }); + writeStdout(output.summary); + + return output; +} + +export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise { + const parsed = parseRunSecurityMasterArgs(argv); + if (parsed.help) { + process.stdout.write(`${RUN_SECURITY_MASTER_USAGE}\n`); + return; + } + + const logger = getLogger('security-master-run-cli'); + const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); + const mongoConfig = resolveReadOnlyMongoClientConfig(config); + const mongo = new MongoDBClient(mongoConfig, logger); + + await mongo.connect(); + + const assertSafety = (): void => { + assertSecurityMasterPersistSafety(config, process.env); + }; + + const createPostgresClient = async (): Promise => { + const pg = config.database.postgres; + const pgClient = new PostgreSQLClient( + { + host: pg.host, + port: pg.port, + database: pg.database, + username: pg.user, + password: pg.password, + poolSettings: { + min: 1, + max: Math.max(1, pg.poolSize), + idleTimeoutMillis: pg.idleTimeout, + }, + ssl: { + enabled: pg.ssl, + rejectUnauthorized: true, + }, + timeouts: { + connection: pg.connectionTimeout, + }, + }, + logger + ); + + await pgClient.connect(); + try { + const pool = pgClient.connectionPool; + if (!pool) { + throw new Error('PostgreSQL connection pool was not initialized after connect()'); + } + const poolClient = await pool.connect(); + const queryable: SecurityMasterQueryable = { + query>( + text: string, + values?: readonly unknown[] + ): Promise> { + return poolClient.query( + text, + values === undefined ? undefined : [...values] + ) as unknown as Promise>; + }, + release: () => { + poolClient.release(); + }, + }; + let closed = false; + return { + queryable, + async close(): Promise { + if (closed) { + return; + } + closed = true; + let releaseError: unknown = null; + try { + poolClient.release(); + } catch (error) { + releaseError = error; + } + try { + await pgClient.disconnect(); + } catch (disconnectError) { + if (releaseError === null) { + throw disconnectError; + } + } + if (releaseError !== null) { + throw releaseError; + } + }, + }; + } catch (error) { + await pgClient.disconnect().catch(() => {}); + throw error; + } + }; + + await runSecurityMaster( + { + mongoCollectionClient: mongo, + barSpanReader: mongo, + closeMongo: () => mongo.disconnect(), + assertSafety, + createPostgresClient, + }, + { + asOfDate: parsed.asOfDate, + outDir: parsed.outDir, + persist: parsed.persist, + } + ); +} + +if (import.meta.main) { + runCli().catch(error => { + const message = error instanceof Error ? error.message : String(error); + process.stderr.write(`Error: ${message}\n`); + process.exit(1); + }); +} diff --git a/apps/stock/data-pipeline/src/security-master/run.ts b/apps/stock/data-pipeline/src/security-master/run.ts new file mode 100644 index 00000000..182ca474 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/run.ts @@ -0,0 +1,1345 @@ +import { + BarSpanIndex, + normalizeBarDate, + type BarSpan, + type ComputeBarSpansResult, + type SpanDateRange, +} from '../normalization/bar-spans'; +import { parseTickerDetailed } from '../normalization/ticker'; +import { + DEFAULT_OTC_MICS, + linkDelistingChains, + type DelistingChainResult, + type LinkDelistingChainsOptions, +} from './delisting-chains'; +import { + compareAscii, + ISO_EXCHANGE_SEEDS, + type ExchangeClassificationResult, + type ExchangeRole, +} from './exchange-pass1'; +import { + isStageASource, + matchInstrumentsStageA, + STAGE_A_SOURCES, + type MatchInstrumentsStageAOptions, + type StageAMatchResult, + type StageASourceRecord, +} from './instrument-stage-a'; +import { + matchListingsStageB, + MAX_TICKER_ROOT_LENGTH, + STAGE_B_SOURCES, + type MatchListingsStageBOptions, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBMatchResult, + type StageBProviderMappingCandidate, + type StageBSymbolChangeInput, + type StageBTickerSourceInput, +} from './listing-stage-b'; +import { + buildMatchReport, + generateOverrideTemplateSql, + renderConflictsCsv, + renderMatchReportMarkdown, + sourceCountryKey, + type BuildMatchReportOptions, + type CountryResolutionSummary, + type MatchReport, + type RenderMatchReportMarkdownOptions, + type SourceCountryLookup, + type SourceResolutionSummary, +} from './match-report'; +import { + formatListingNaturalKey, + type PersistSecurityMasterInput, + type SecurityType, +} from './persist'; +import { + crossCheckPrices, + type CrossCheckPricesOptions, + type FxRateByDateRecord, + type PriceCrossCheckPair, + type PriceCrossCheckResult, + type PriceSeriesEndpoint, + type SampleCloseRecord, +} from './price-cross-check'; +import { + normalizeCountryIso2, + type SecurityMasterSourcesResult, + type SecurityMasterStageBSourceInput, +} from './source-symbol-readers'; + +export type ObservedBarSpansInput = + | readonly BarSpan[] + | ComputeBarSpansResult + | BarSpanIndex; + +export interface ComposeSecurityMasterPass6Options + extends Omit { + readonly otcMics?: ReadonlySet; +} + +export interface ComposeSecurityMasterRunInput { + readonly sources: SecurityMasterSourcesResult; + readonly barSpans?: ObservedBarSpansInput | null; + readonly exchanges?: ExchangeClassificationResult; + readonly sampleCloses?: readonly SampleCloseRecord[]; + readonly fxRates?: readonly FxRateByDateRecord[]; + readonly sourceCountries?: SourceCountryLookup; +} + +export interface ComposeSecurityMasterRunOptions { + readonly asOfDate: string; + readonly stageA?: MatchInstrumentsStageAOptions; + readonly stageB?: MatchListingsStageBOptions; + readonly pass6?: ComposeSecurityMasterPass6Options; + readonly pass4?: CrossCheckPricesOptions; + readonly report?: BuildMatchReportOptions; + readonly markdown?: RenderMatchReportMarkdownOptions; +} + +export interface ReconcilingStepStats { + readonly recordsIn: number; + readonly resolved: number; + readonly unresolved: number; + readonly skipped: number; +} + +export interface BarSpansStepStats extends ReconcilingStepStats { + readonly indexedSpans: number; + readonly attachedEodListings: number; + readonly attachedQmTickerSources: number; +} + +export interface StageAComposeStepStats extends ReconcilingStepStats { + readonly conflicts: number; +} + +export interface StageBComposeStepStats extends ReconcilingStepStats { + readonly conflicts: number; +} + +export interface Pass6ComposeStepStats extends ReconcilingStepStats { + readonly continuitiesCreated: number; + readonly conflicts: number; +} + +export interface Pass4ComposeStepStats extends ReconcilingStepStats { + readonly status: 'executed' | 'skipped'; + readonly conflicts: number; +} + +export interface ComposeMalformedInputStats { + readonly stageARecords: number; + readonly eodListings: number; + readonly ibContracts: number; + readonly tickerSources: number; + readonly symbolChanges: number; + readonly barSpans: number; + readonly sampleCloses: number; + readonly fxRates: number; + readonly total: number; +} + +export interface ComposeConflictTotals { + readonly stageA: number; + readonly stageB: number; + readonly pass4: number; + readonly pass6: number; + readonly total: number; +} + +export interface ComposeSecurityMasterRunStats { + readonly barSpans: BarSpansStepStats; + readonly stageA: StageAComposeStepStats; + readonly stageB: StageBComposeStepStats; + readonly pass6: Pass6ComposeStepStats; + readonly pass4: Pass4ComposeStepStats; + readonly conflicts: ComposeConflictTotals; + readonly malformedInputs: ComposeMalformedInputStats; +} + +export interface AttachBarSpansMalformedCounts { + readonly barSpans: number; + readonly eodListings: number; + readonly ibContracts: number; + readonly tickerSources: number; + readonly symbolChanges: number; +} + +export interface AttachBarSpansResult { + readonly stageBInput: SecurityMasterStageBSourceInput; + readonly stats: BarSpansStepStats; + readonly malformed: AttachBarSpansMalformedCounts; +} + +export interface ComposeSecurityMasterRunResult { + readonly stageA: StageAMatchResult; + readonly stageB: StageBMatchResult; + readonly pass6: DelistingChainResult; + readonly pass4: PriceCrossCheckResult | null; + readonly pass4CandidatePairs: readonly PriceCrossCheckPair[]; + readonly report: MatchReport; + readonly reportMarkdown: string; + readonly conflictsCsv: string; + readonly overrideTemplateSql: string; + readonly persistInput: PersistSecurityMasterInput; + readonly stats: ComposeSecurityMasterRunStats; +} + +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; + +const MIC_TO_COUNTRY: ReadonlyMap = (() => { + const map = new Map(); + for (const seed of ISO_EXCHANGE_SEEDS) { + map.set(seed.mic, seed.countryIso); + } + return map; +})(); + +function isExchangeRoleValue(value: unknown): value is ExchangeRole { + return ( + value === 'primary_venue' || + value === 'composite' || + value === 'ats_routing' || + value === 'forex' || + value === 'excluded_fund' + ); +} + +function isValidExactYmd(value: unknown): value is string { + return ( + typeof value === 'string' && + EXACT_YMD_PATTERN.test(value) && + normalizeBarDate(value) === value + ); +} + +function normalizeObservedBarSpans(barSpans: ObservedBarSpansInput | null | undefined): { + readonly lookup: BarSpanIndex | null; + readonly recordsIn: number; + readonly resolved: number; + readonly skipped: number; + readonly indexedSpans: number; +} { + if (barSpans === undefined || barSpans === null) { + return { lookup: null, recordsIn: 0, resolved: 0, skipped: 0, indexedSpans: 0 }; + } + + if (barSpans instanceof BarSpanIndex) { + return { + lookup: barSpans, + recordsIn: barSpans.size, + resolved: barSpans.size, + skipped: 0, + indexedSpans: barSpans.size, + }; + } + + if (Array.isArray(barSpans)) { + const index = new BarSpanIndex(); + let resolved = 0; + let skipped = 0; + + for (let i = 0; i < barSpans.length; i++) { + if (!(i in barSpans)) { + skipped += 1; + continue; + } + const entry = barSpans[i] as unknown; + if (entry === undefined || entry === null || typeof entry !== 'object') { + skipped += 1; + continue; + } + const rec = entry as Partial; + if (rec.source !== 'eod' && rec.source !== 'qm') { + skipped += 1; + continue; + } + if (typeof rec.sourceId !== 'string' || rec.sourceId.trim().length === 0) { + skipped += 1; + continue; + } + const firstBarDate = normalizeBarDate(rec.firstBarDate); + const lastBarDate = normalizeBarDate(rec.lastBarDate); + if (firstBarDate === null || lastBarDate === null || firstBarDate > lastBarDate) { + skipped += 1; + continue; + } + if ( + typeof rec.barCount !== 'number' || + !Number.isSafeInteger(rec.barCount) || + rec.barCount <= 0 + ) { + skipped += 1; + continue; + } + index.merge({ + source: rec.source, + sourceId: rec.sourceId, + firstBarDate, + lastBarDate, + barCount: rec.barCount, + }); + resolved += 1; + } + + return { + lookup: index, + recordsIn: barSpans.length, + resolved, + skipped, + indexedSpans: index.size, + }; + } + + if ( + typeof barSpans === 'object' && + 'index' in barSpans && + barSpans.index instanceof BarSpanIndex + ) { + const rawSkippedTotal = + typeof barSpans.skipped === 'object' && barSpans.skipped !== null + ? barSpans.skipped.total + : undefined; + const skipped = + typeof rawSkippedTotal === 'number' && + Number.isSafeInteger(rawSkippedTotal) && + rawSkippedTotal >= 0 + ? rawSkippedTotal + : 0; + const rawTotalRowsRead = barSpans.totalRowsRead; + const recordsIn = + typeof rawTotalRowsRead === 'number' && + Number.isSafeInteger(rawTotalRowsRead) && + rawTotalRowsRead >= skipped + ? rawTotalRowsRead + : barSpans.index.size + skipped; + const resolved = recordsIn - skipped; + return { + lookup: barSpans.index, + recordsIn, + resolved, + skipped, + indexedSpans: barSpans.index.size, + }; + } + + throw new TypeError( + 'barSpans must be a BarSpan[], ComputeBarSpansResult, BarSpanIndex, null, or undefined' + ); +} + +function sanitizeStageARecords(records: readonly StageASourceRecord[]): { + readonly sanitized: StageASourceRecord[]; + readonly malformed: number; +} { + if (!Array.isArray(records)) { + throw new TypeError('sources.stageARecords must be an array'); + } + const sanitized: StageASourceRecord[] = []; + let malformed = 0; + + for (let i = 0; i < records.length; i++) { + if (!(i in records)) { + malformed += 1; + continue; + } + const record = records[i] as unknown; + if (record === undefined || record === null || typeof record !== 'object') { + malformed += 1; + continue; + } + const candidate = record as StageASourceRecord; + if (!isStageASource(candidate.source)) { + malformed += 1; + continue; + } + if (typeof candidate.sourceId !== 'string' || candidate.sourceId.length === 0) { + malformed += 1; + continue; + } + sanitized.push(candidate); + } + + return { sanitized, malformed }; +} + +/** + * Pure adapter that normalizes observed bar spans (`BarSpan[]`, `ComputeBarSpansResult`, or + * `BarSpanIndex`), sanitizes Stage B source arrays against malformed/sparse entries that would + * throw inside `matchListingsStageB`, and attaches observed `eod`/`qm` spans onto shallow-cloned + * entries while preserving existing spans (including `ceo` spans) when absent from `barSpans`. + */ +export function attachBarSpansToStageBInput( + stageBInput: SecurityMasterStageBSourceInput, + barSpans?: ObservedBarSpansInput | null +): AttachBarSpansResult { + if (stageBInput === null || stageBInput === undefined || typeof stageBInput !== 'object') { + throw new TypeError('stageBInput must be an object'); + } + if (!Array.isArray(stageBInput.eodListings)) { + throw new TypeError('stageBInput.eodListings must be an array'); + } + if (!Array.isArray(stageBInput.ibContracts)) { + throw new TypeError('stageBInput.ibContracts must be an array'); + } + if (!Array.isArray(stageBInput.tickerSources)) { + throw new TypeError('stageBInput.tickerSources must be an array'); + } + if (!Array.isArray(stageBInput.symbolChanges)) { + throw new TypeError('stageBInput.symbolChanges must be an array'); + } + + const normalizedSpans = normalizeObservedBarSpans(barSpans); + const lookup = normalizedSpans.lookup; + + let malformedEodListings = 0; + let attachedEodListings = 0; + const eodListings: StageBEodListingInput[] = []; + for (let i = 0; i < stageBInput.eodListings.length; i++) { + if (!(i in stageBInput.eodListings)) { + malformedEodListings += 1; + continue; + } + const entry = stageBInput.eodListings[i] as unknown; + if (entry === undefined || entry === null || typeof entry !== 'object') { + malformedEodListings += 1; + continue; + } + const rec = entry as StageBEodListingInput; + if (typeof rec.sourceId !== 'string' || rec.sourceId.length === 0) { + malformedEodListings += 1; + continue; + } + if (rec.role !== null && rec.role !== undefined && !isExchangeRoleValue(rec.role)) { + malformedEodListings += 1; + continue; + } + const observed = lookup?.get('eod', rec.sourceId); + if (observed !== undefined && observed.barCount > 0) { + const span: SpanDateRange = { + firstBarDate: observed.firstBarDate, + lastBarDate: observed.lastBarDate, + }; + eodListings.push({ ...rec, span }); + attachedEodListings += 1; + } else { + eodListings.push({ ...rec }); + } + } + + let malformedIbContracts = 0; + const ibContracts: StageBIbContractInput[] = []; + for (let i = 0; i < stageBInput.ibContracts.length; i++) { + if (!(i in stageBInput.ibContracts)) { + malformedIbContracts += 1; + continue; + } + const entry = stageBInput.ibContracts[i] as unknown; + if (entry === undefined || entry === null || typeof entry !== 'object') { + malformedIbContracts += 1; + continue; + } + const rec = entry as StageBIbContractInput; + if (typeof rec.sourceId !== 'string' || rec.sourceId.length === 0) { + malformedIbContracts += 1; + continue; + } + ibContracts.push({ ...rec }); + } + + let malformedTickerSources = 0; + let attachedQmTickerSources = 0; + const tickerSources: StageBTickerSourceInput[] = []; + for (let i = 0; i < stageBInput.tickerSources.length; i++) { + if (!(i in stageBInput.tickerSources)) { + malformedTickerSources += 1; + continue; + } + const entry = stageBInput.tickerSources[i] as unknown; + if (entry === undefined || entry === null || typeof entry !== 'object') { + malformedTickerSources += 1; + continue; + } + const rec = entry as StageBTickerSourceInput; + if (rec.source !== 'qm' && rec.source !== 'ceo') { + malformedTickerSources += 1; + continue; + } + if (typeof rec.sourceId !== 'string' || rec.sourceId.length === 0) { + malformedTickerSources += 1; + continue; + } + if (rec.role !== null && rec.role !== undefined && !isExchangeRoleValue(rec.role)) { + malformedTickerSources += 1; + continue; + } + if (rec.source === 'qm') { + const observed = lookup?.get('qm', rec.sourceId); + if (observed !== undefined && observed.barCount > 0) { + const span: SpanDateRange = { + firstBarDate: observed.firstBarDate, + lastBarDate: observed.lastBarDate, + }; + tickerSources.push({ ...rec, span }); + attachedQmTickerSources += 1; + continue; + } + } + tickerSources.push({ ...rec }); + } + + let malformedSymbolChanges = 0; + const symbolChanges: StageBSymbolChangeInput[] = []; + for (let i = 0; i < stageBInput.symbolChanges.length; i++) { + if (!(i in stageBInput.symbolChanges)) { + malformedSymbolChanges += 1; + continue; + } + const entry = stageBInput.symbolChanges[i] as unknown; + if (entry === undefined || entry === null || typeof entry !== 'object') { + malformedSymbolChanges += 1; + continue; + } + const rec = entry as StageBSymbolChangeInput; + if (typeof rec.eodSourceId !== 'string' || rec.eodSourceId.length === 0) { + malformedSymbolChanges += 1; + continue; + } + if (typeof rec.oldTicker !== 'string') { + malformedSymbolChanges += 1; + continue; + } + const parsedOldTicker = parseTickerDetailed(rec.oldTicker, 'eod'); + if (!parsedOldTicker.ok || parsedOldTicker.tickerRoot.length > MAX_TICKER_ROOT_LENGTH) { + malformedSymbolChanges += 1; + continue; + } + if (!isValidExactYmd(rec.effectiveDate) || rec.effectiveDate === '0001-01-01') { + malformedSymbolChanges += 1; + continue; + } + if (rec.validFrom !== undefined && rec.validFrom !== null) { + if (!isValidExactYmd(rec.validFrom) || rec.validFrom >= rec.effectiveDate) { + malformedSymbolChanges += 1; + continue; + } + } + symbolChanges.push({ ...rec }); + } + + return { + stageBInput: { + eodListings, + ibContracts, + tickerSources, + symbolChanges, + }, + stats: { + recordsIn: normalizedSpans.recordsIn, + resolved: normalizedSpans.resolved, + unresolved: 0, + skipped: normalizedSpans.skipped, + indexedSpans: normalizedSpans.indexedSpans, + attachedEodListings, + attachedQmTickerSources, + }, + malformed: { + barSpans: normalizedSpans.skipped, + eodListings: malformedEodListings, + ibContracts: malformedIbContracts, + tickerSources: malformedTickerSources, + symbolChanges: malformedSymbolChanges, + }, + }; +} + +function comparePriceEndpoint(a: PriceSeriesEndpoint, b: PriceSeriesEndpoint): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.currency, b.currency) + ); +} + +function comparePricePair(a: PriceCrossCheckPair, b: PriceCrossCheckPair): number { + return comparePriceEndpoint(a.left, b.left) || comparePriceEndpoint(a.right, b.right); +} + +/** + * Pure adapter that derives deterministic Pass 4 candidate pairs from Stage B provider mappings + * sharing a listing natural key across distinct sources (`left.source !== right.source`). + */ +export function derivePass4CandidatePairs( + providerMappings: readonly StageBProviderMappingCandidate[] +): PriceCrossCheckPair[] { + if (!Array.isArray(providerMappings)) { + throw new TypeError('providerMappings must be an array'); + } + + const endpointsByListing = new Map>(); + for (let i = 0; i < providerMappings.length; i++) { + const mapping = providerMappings[i]; + if (mapping === undefined || mapping === null) { + continue; + } + const listingKey = formatListingNaturalKey(mapping.listingKey); + let endpointMap = endpointsByListing.get(listingKey); + if (endpointMap === undefined) { + endpointMap = new Map(); + endpointsByListing.set(listingKey, endpointMap); + } + const endpointKey = `${mapping.source}\u0000${mapping.sourceId}\u0000${mapping.listingKey.currency}`; + if (!endpointMap.has(endpointKey)) { + endpointMap.set(endpointKey, { + source: mapping.source, + sourceId: mapping.sourceId, + currency: mapping.listingKey.currency, + }); + } + } + + const seenPairKeys = new Set(); + const pairs: PriceCrossCheckPair[] = []; + + for (const endpointMap of endpointsByListing.values()) { + if (endpointMap.size < 2) { + continue; + } + const endpoints = Array.from(endpointMap.values()).sort(comparePriceEndpoint); + for (let i = 0; i < endpoints.length; i++) { + const left = endpoints[i]; + if (left === undefined) { + continue; + } + for (let j = i + 1; j < endpoints.length; j++) { + const right = endpoints[j]; + if (right === undefined || left.source === right.source) { + continue; + } + const pairKey = `${left.source}\u0000${left.sourceId}\u0000${left.currency}\u0000${right.source}\u0000${right.sourceId}\u0000${right.currency}`; + if (seenPairKeys.has(pairKey)) { + continue; + } + seenPairKeys.add(pairKey); + pairs.push({ left, right }); + } + } + } + + pairs.sort(comparePricePair); + return pairs; +} + +interface MappingValidityWindow { + readonly validFrom: string | null; + readonly validTo: string | null; +} + +/** + * Pure adapter that restricts valid `sampleCloses` to each provider mapping's Stage B + * `[validFrom, validTo]` window before Pass 4 price cross-checks. Malformed close records + * are passed through unchanged so `crossCheckPrices` continues to count them in + * `droppedInvalidCloses`. Because `crossCheckPrices` aligns dates present in both endpoints, + * filtering each endpoint to its own mapping window ensures every comparison only uses dates + * where both mappings are valid. + */ +export function filterSampleClosesByMappingBounds( + providerMappings: readonly StageBProviderMappingCandidate[], + sampleCloses: readonly SampleCloseRecord[] +): SampleCloseRecord[] { + if (!Array.isArray(providerMappings)) { + throw new TypeError('providerMappings must be an array'); + } + if (!Array.isArray(sampleCloses)) { + throw new TypeError('sampleCloses must be an array'); + } + + const windowsBySeries = new Map(); + for (let i = 0; i < providerMappings.length; i++) { + const mapping = providerMappings[i]; + if (mapping === undefined || mapping === null) { + continue; + } + const key = `${mapping.source}\u0000${mapping.sourceId}`; + let windows = windowsBySeries.get(key); + if (windows === undefined) { + windows = []; + windowsBySeries.set(key, windows); + } + windows.push({ + validFrom: mapping.validFrom, + validTo: mapping.validTo, + }); + } + + const filtered: SampleCloseRecord[] = []; + for (let i = 0; i < sampleCloses.length; i++) { + if (!(i in sampleCloses)) { + filtered.push(sampleCloses[i] as SampleCloseRecord); + continue; + } + const row = sampleCloses[i]; + if (row === undefined || row === null || typeof row !== 'object') { + filtered.push(row as SampleCloseRecord); + continue; + } + if ( + typeof row.source !== 'string' || + row.source.length === 0 || + typeof row.sourceId !== 'string' || + row.sourceId.length === 0 || + !isValidExactYmd(row.date) || + typeof row.close !== 'number' || + !Number.isFinite(row.close) || + row.close <= 0 + ) { + filtered.push(row); + continue; + } + + const windows = windowsBySeries.get(`${row.source}\u0000${row.sourceId}`); + if (windows === undefined) { + continue; + } + + let inAnyWindow = false; + for (let w = 0; w < windows.length; w++) { + const win = windows[w]; + if (win === undefined) { + continue; + } + if ( + (win.validFrom === null || row.date >= win.validFrom) && + (win.validTo === null || row.date <= win.validTo) + ) { + inAnyWindow = true; + break; + } + } + if (inAnyWindow) { + filtered.push(row); + } + } + + return filtered; +} + +function isExcludedByDesignRole(role: ExchangeRole | null | 'mixed' | undefined): boolean { + return ( + role === 'excluded_fund' || + role === 'composite' || + role === 'ats_routing' || + role === 'forex' + ); +} + +function lookupSourceCountryValue( + lookup: SourceCountryLookup | undefined, + source: string, + sourceId: string +): string | null { + if (!lookup) { + return null; + } + const primaryKey = sourceCountryKey(source, sourceId); + const fallbackKey = `${source}\u0000${sourceId}`; + + let raw: string | undefined; + if (lookup instanceof Map) { + raw = lookup.get(primaryKey) ?? lookup.get(fallbackKey); + } else { + const record = lookup as Readonly>; + if (Object.prototype.hasOwnProperty.call(record, primaryKey)) { + raw = record[primaryKey]; + } else if (Object.prototype.hasOwnProperty.call(record, fallbackKey)) { + raw = record[fallbackKey]; + } + } + if (typeof raw !== 'string') { + return null; + } + const normalized = raw.trim().toUpperCase(); + return normalized.length > 0 ? normalized : null; +} + +/** + * Folds Stage A unresolved/conflict failures that did not reach Stage B into end-to-end + * `resolutionBySource`, `resolutionByCountry`, and `meetsExitThresholds.equitiesResolved95` + * without double-counting any record already counted in Stage B. + */ +function applyEndToEndStageACoverage( + baseReport: MatchReport, + stageA: StageAMatchResult, + stageB: StageBMatchResult, + eodListings: readonly StageBEodListingInput[], + sourceCountries: SourceCountryLookup | undefined +): MatchReport { + if (stageA.unresolved.length === 0 && stageA.conflicts.length === 0) { + return baseReport; + } + + const eodRoleBySourceId = new Map(); + for (let i = 0; i < eodListings.length; i++) { + const entry = eodListings[i]; + if (entry === undefined) { + continue; + } + const role = entry.role ?? null; + if (!eodRoleBySourceId.has(entry.sourceId)) { + eodRoleBySourceId.set(entry.sourceId, role); + } else if (eodRoleBySourceId.get(entry.sourceId) !== role) { + eodRoleBySourceId.set(entry.sourceId, 'mixed'); + } + } + + const stageBCountedByKey = new Map(); + const recordStageBCount = (source: string, sourceId: string): void => { + if (source !== 'eod' && source !== 'ib') { + return; + } + const key = `${source}\u0000${sourceId}`; + stageBCountedByKey.set(key, (stageBCountedByKey.get(key) ?? 0) + 1); + }; + for (let i = 0; i < stageB.providerMappings.length; i++) { + const m = stageB.providerMappings[i]; + if (m !== undefined) { + recordStageBCount(m.source, m.sourceId); + } + } + for (let i = 0; i < stageB.unresolved.length; i++) { + const u = stageB.unresolved[i]; + if (u !== undefined) { + recordStageBCount(u.source, u.sourceId); + } + } + for (let i = 0; i < stageB.conflicts.length; i++) { + const c = stageB.conflicts[i]; + if (c !== undefined) { + recordStageBCount(c.source, c.sourceId); + } + } + + const deltaBySource: Record< + 'eod' | 'ib', + { total: number; unresolved: number; conflict: number; excludedByDesign: number } + > = { + eod: { total: 0, unresolved: 0, conflict: 0, excludedByDesign: 0 }, + ib: { total: 0, unresolved: 0, conflict: 0, excludedByDesign: 0 }, + }; + + const countryAccs = new Map< + string, + { total: number; matched: number; unresolved: number; conflict: number; excludedByDesign: number } + >(); + for (let i = 0; i < baseReport.resolutionByCountry.length; i++) { + const row = baseReport.resolutionByCountry[i]; + if (row !== undefined) { + countryAccs.set(row.country, { + total: row.total, + matched: row.matched, + unresolved: row.unresolved, + conflict: row.conflict, + excludedByDesign: row.excludedByDesign, + }); + } + } + + const getOrCreateCountry = (country: string) => { + let acc = countryAccs.get(country); + if (acc === undefined) { + acc = { total: 0, matched: 0, unresolved: 0, conflict: 0, excludedByDesign: 0 }; + countryAccs.set(country, acc); + } + return acc; + }; + + const consumeStageBCount = (source: 'eod' | 'ib', sourceId: string): boolean => { + const key = `${source}\u0000${sourceId}`; + const remaining = stageBCountedByKey.get(key) ?? 0; + if (remaining > 0) { + stageBCountedByKey.set(key, remaining - 1); + return true; + } + return false; + }; + + for (let i = 0; i < stageA.unresolved.length; i++) { + const rec = stageA.unresolved[i]; + if (rec === undefined || consumeStageBCount(rec.source, rec.sourceId)) { + continue; + } + const excluded = + rec.source === 'eod' && isExcludedByDesignRole(eodRoleBySourceId.get(rec.sourceId)); + const d = deltaBySource[rec.source]; + d.total += 1; + d.unresolved += 1; + if (excluded) { + d.excludedByDesign += 1; + } + + const country = lookupSourceCountryValue(sourceCountries, rec.source, rec.sourceId); + if (country !== null) { + const cAcc = getOrCreateCountry(country); + cAcc.total += 1; + cAcc.unresolved += 1; + if (excluded) { + cAcc.excludedByDesign += 1; + } + } + } + + for (let i = 0; i < stageA.conflicts.length; i++) { + const rec = stageA.conflicts[i]; + if (rec === undefined || consumeStageBCount(rec.source, rec.sourceId)) { + continue; + } + const excluded = + rec.source === 'eod' && isExcludedByDesignRole(eodRoleBySourceId.get(rec.sourceId)); + const d = deltaBySource[rec.source]; + d.total += 1; + d.conflict += 1; + if (excluded) { + d.excludedByDesign += 1; + } + + const country = lookupSourceCountryValue(sourceCountries, rec.source, rec.sourceId); + if (country !== null) { + const cAcc = getOrCreateCountry(country); + cAcc.total += 1; + cAcc.conflict += 1; + if (excluded) { + cAcc.excludedByDesign += 1; + } + } + } + + if (deltaBySource.eod.total === 0 && deltaBySource.ib.total === 0) { + return baseReport; + } + + const resolutionBySource: SourceResolutionSummary[] = baseReport.resolutionBySource.map(row => { + if (row.source !== 'eod' && row.source !== 'ib') { + return row; + } + const d = deltaBySource[row.source]; + if (d.total === 0) { + return row; + } + const total = row.total + d.total; + const unresolved = row.unresolved + d.unresolved; + const conflict = row.conflict + d.conflict; + const excludedByDesign = row.excludedByDesign + d.excludedByDesign; + const eligibleTotal = Math.max(0, total - excludedByDesign); + return { + source: row.source, + total, + matched: row.matched, + unresolved, + conflict, + excludedByDesign, + eligibleTotal, + resolvedPct: total > 0 ? row.matched / total : null, + eligibleResolvedPct: eligibleTotal > 0 ? row.matched / eligibleTotal : null, + }; + }); + + const resolutionByCountry: CountryResolutionSummary[] = sourceCountries + ? Array.from(countryAccs.entries()) + .sort((a, b) => compareAscii(a[0], b[0])) + .map(([country, acc]) => { + const eligibleTotal = Math.max(0, acc.total - acc.excludedByDesign); + return { + country, + total: acc.total, + matched: acc.matched, + unresolved: acc.unresolved, + conflict: acc.conflict, + excludedByDesign: acc.excludedByDesign, + eligibleTotal, + resolvedPct: acc.total > 0 ? acc.matched / acc.total : null, + eligibleResolvedPct: eligibleTotal > 0 ? acc.matched / eligibleTotal : null, + }; + }) + : baseReport.resolutionByCountry; + + const eligibleSources = resolutionBySource.filter(row => row.total > 0 && row.eligibleTotal > 0); + const equitiesResolved95 = + eligibleSources.length > 0 && + eligibleSources.every( + row => row.eligibleResolvedPct !== null && row.eligibleResolvedPct >= baseReport.minResolvedPct + ); + + return { + ...baseReport, + resolutionBySource, + resolutionByCountry, + meetsExitThresholds: { + ...baseReport.meetsExitThresholds, + equitiesResolved95, + }, + }; +} + +function recordCountryCandidate( + target: Map, + key: string, + country: string | undefined | null +): void { + if (typeof country !== 'string' || country.length === 0) { + return; + } + const existing = target.get(key); + if (existing === undefined || compareAscii(country, existing) < 0) { + target.set(key, country); + } +} + +/** + * Deterministically builds a `sourceCountryKey(source, sourceId) -> ISO-2 country` map for + * `buildMatchReport`'s `resolutionByCountry` summary, prioritizing resolved listing MICs, + * then Stage B input MICs, then Stage A issuer countries. + */ +export function deriveSourceCountries( + stageARecords: readonly StageASourceRecord[], + stageBInput: Pick, + stageB: Pick +): Map { + const fromResolvedMappings = new Map(); + for (let i = 0; i < stageB.providerMappings.length; i++) { + const mapping = stageB.providerMappings[i]; + if (mapping === undefined) { + continue; + } + const country = MIC_TO_COUNTRY.get(mapping.listingKey.mic); + recordCountryCandidate( + fromResolvedMappings, + sourceCountryKey(mapping.source, mapping.sourceId), + country + ); + } + + const fromStageBMics = new Map(); + for (let i = 0; i < stageBInput.eodListings.length; i++) { + const entry = stageBInput.eodListings[i]; + if (entry === undefined || entry.mic === null) { + continue; + } + recordCountryCandidate( + fromStageBMics, + sourceCountryKey('eod', entry.sourceId), + MIC_TO_COUNTRY.get(entry.mic) + ); + } + for (let i = 0; i < stageBInput.tickerSources.length; i++) { + const entry = stageBInput.tickerSources[i]; + if (entry === undefined || entry.mic === null) { + continue; + } + recordCountryCandidate( + fromStageBMics, + sourceCountryKey(entry.source, entry.sourceId), + MIC_TO_COUNTRY.get(entry.mic) + ); + } + + const fromStageA = new Map(); + for (let i = 0; i < stageARecords.length; i++) { + const record = stageARecords[i]; + if (record === undefined) { + continue; + } + const country = normalizeCountryIso2(record.country); + recordCountryCandidate( + fromStageA, + sourceCountryKey(record.source, record.sourceId), + country + ); + } + + const merged = new Map(); + for (const [k, v] of fromStageA.entries()) { + merged.set(k, v); + } + for (const [k, v] of fromStageBMics.entries()) { + merged.set(k, v); + } + for (const [k, v] of fromResolvedMappings.entries()) { + merged.set(k, v); + } + + const sorted = new Map(); + const keys = Array.from(merged.keys()).sort(compareAscii); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (key === undefined) { + continue; + } + const value = merged.get(key); + if (value !== undefined) { + sorted.set(key, value); + } + } + return sorted; +} + +/** + * Pure, in-memory security-master run composer wiring: + * `sources + barSpans -> Stage A -> Stage B -> Pass 6 -> optional Pass 4 -> MatchReport + PersistSecurityMasterInput`. + * + * Performs zero I/O, zero network/database calls, and zero wall-clock reads. + */ +export function composeSecurityMasterRun( + input: ComposeSecurityMasterRunInput, + options: ComposeSecurityMasterRunOptions +): ComposeSecurityMasterRunResult { + if (input === null || input === undefined || typeof input !== 'object') { + throw new TypeError('composeSecurityMasterRun requires an input object'); + } + if (input.sources === null || input.sources === undefined || typeof input.sources !== 'object') { + throw new TypeError('composeSecurityMasterRun requires input.sources'); + } + const rawSecurityTypes: unknown = input.sources.securityTypeByIsin; + if ( + !(rawSecurityTypes instanceof Map) && + (rawSecurityTypes === null || + rawSecurityTypes === undefined || + typeof (rawSecurityTypes as { entries?: unknown }).entries !== 'function' || + typeof (rawSecurityTypes as { get?: unknown }).get !== 'function') + ) { + throw new TypeError('composeSecurityMasterRun requires sources.securityTypeByIsin Map'); + } + if (options === null || options === undefined || typeof options !== 'object') { + throw new TypeError('composeSecurityMasterRun requires an options object'); + } + + // 1. Stage A (instrument matching) + const { sanitized: sanitizedStageARecords, malformed: malformedStageARecords } = + sanitizeStageARecords(input.sources.stageARecords); + const stageA = matchInstrumentsStageA(sanitizedStageARecords, options.stageA); + + // 2. Stage B (attach bar spans + listing matching) + const attached = attachBarSpansToStageBInput(input.sources.stageBInput, input.barSpans); + const stageB = matchListingsStageB( + { + instruments: stageA.instruments, + eodListings: attached.stageBInput.eodListings, + ibContracts: attached.stageBInput.ibContracts, + tickerSources: attached.stageBInput.tickerSources, + symbolChanges: attached.stageBInput.symbolChanges, + }, + options.stageB + ); + + // 3. Pass 6 (delisting chain linking) + const otcMics = options.pass6?.otcMics ?? DEFAULT_OTC_MICS; + const pass6Options: LinkDelistingChainsOptions = { + asOfDate: options.asOfDate, + ...(options.pass6?.activeGraceDays !== undefined + ? { activeGraceDays: options.pass6.activeGraceDays } + : {}), + ...(options.pass6?.maxTransferGapDays !== undefined + ? { maxTransferGapDays: options.pass6.maxTransferGapDays } + : {}), + ...(options.pass6?.overlapToleranceDays !== undefined + ? { overlapToleranceDays: options.pass6.overlapToleranceDays } + : {}), + }; + const pass6 = linkDelistingChains({ listings: stageB.listings, otcMics }, pass6Options); + + // 4. Optional Pass 4 (price cross-check over cross-source pairs sharing a listing, + // bounded to dates where both Stage B mappings are valid) + const pass4CandidatePairs = derivePass4CandidatePairs(stageB.providerMappings); + const hasSampleCloses = + input.sampleCloses !== undefined && + Array.isArray(input.sampleCloses) && + input.sampleCloses.length > 0; + const boundedSampleCloses = hasSampleCloses + ? filterSampleClosesByMappingBounds(stageB.providerMappings, input.sampleCloses) + : []; + const pass4: PriceCrossCheckResult | null = hasSampleCloses + ? crossCheckPrices( + { + pairs: pass4CandidatePairs, + closes: boundedSampleCloses, + usdCadByDate: input.fxRates ?? [], + }, + options.pass4 + ) + : null; + + // 5. Match report + rendered Markdown / CSV / override-template SQL + const sourceCountries = + input.sourceCountries ?? + deriveSourceCountries(sanitizedStageARecords, attached.stageBInput, stageB); + const baseReport = buildMatchReport( + { + ...(input.exchanges !== undefined ? { exchanges: input.exchanges } : {}), + stageA, + stageB, + ...(pass4 !== null ? { priceCrossCheck: pass4 } : {}), + delistingChains: pass6, + sourceCountries, + }, + options.report + ); + const report = applyEndToEndStageACoverage( + baseReport, + stageA, + stageB, + attached.stageBInput.eodListings, + sourceCountries + ); + const reportMarkdown = renderMatchReportMarkdown(report, options.markdown); + const conflictsCsv = renderConflictsCsv(report); + const overrideTemplateSql = generateOverrideTemplateSql(report); + + // 6. Deterministic PersistSecurityMasterInput (do not call persistSecurityMaster here) + const sortedSecurityTypeByIsin = new Map(); + const secTypeEntries = Array.from(input.sources.securityTypeByIsin.entries()).sort((a, b) => + compareAscii(a[0], b[0]) + ); + for (let i = 0; i < secTypeEntries.length; i++) { + const entry = secTypeEntries[i]; + if (entry !== undefined) { + sortedSecurityTypeByIsin.set(entry[0], entry[1]); + } + } + + const persistInput: PersistSecurityMasterInput = { + stageA, + stageB, + ...(pass4 !== null ? { pass4 } : {}), + pass6, + securityTypeByIsin: sortedSecurityTypeByIsin, + }; + + // 7. Reconciling per-step stats + let stageAResolved = 0; + let stageAUnresolved = 0; + for (const source of STAGE_A_SOURCES) { + const s = stageA.stats.bySource[source]; + stageAResolved += s.tier1Isin + s.tier2Cusip; + stageAUnresolved += s.unresolved + s.conflict; + } + const stageAStepStats: StageAComposeStepStats = { + recordsIn: input.sources.stageARecords.length, + resolved: stageAResolved, + unresolved: stageAUnresolved, + skipped: malformedStageARecords, + conflicts: stageA.conflicts.length, + }; + + let stageBTotalProcessed = 0; + let stageBResolved = 0; + let stageBUnresolved = 0; + for (const source of STAGE_B_SOURCES) { + const s = stageB.stats.bySource[source]; + stageBTotalProcessed += s.total; + stageBResolved += s.matched; + stageBUnresolved += s.unresolved + s.conflict; + } + const stageBStepStats: StageBComposeStepStats = { + recordsIn: stageBTotalProcessed + attached.malformed.tickerSources, + resolved: stageBResolved, + unresolved: stageBUnresolved, + skipped: attached.malformed.tickerSources, + conflicts: stageB.conflicts.length, + }; + + const pass6Skipped = + pass6.stats.skippedMalformedEntries + + pass6.stats.skippedInvalidDates + + pass6.stats.skippedDuplicateKeys; + const pass6StepStats: Pass6ComposeStepStats = { + recordsIn: pass6.stats.totalInputListings, + resolved: pass6.stats.processedListings, + unresolved: 0, + skipped: pass6Skipped, + continuitiesCreated: pass6.stats.continuitiesCreated, + conflicts: pass6.conflicts.length, + }; + + const pass4StepStats: Pass4ComposeStepStats = + pass4 === null + ? { + status: 'skipped', + recordsIn: pass4CandidatePairs.length, + resolved: 0, + unresolved: 0, + skipped: pass4CandidatePairs.length, + conflicts: 0, + } + : { + status: 'executed', + recordsIn: pass4.stats.pairsIn, + resolved: pass4.stats.byVerdict.confirmed, + unresolved: + pass4.stats.byVerdict.ratio_mismatch + + pass4.stats.byVerdict.low_correlation + + pass4.stats.byVerdict.insufficient_data + + pass4.stats.byVerdict.unsupported_currency_pair, + skipped: 0, + conflicts: pass4.conflicts.length, + }; + + const pass4ConflictsCount = pass4?.conflicts.length ?? 0; + const conflictTotals: ComposeConflictTotals = { + stageA: stageA.conflicts.length, + stageB: stageB.conflicts.length, + pass4: pass4ConflictsCount, + pass6: pass6.conflicts.length, + total: + stageA.conflicts.length + + stageB.conflicts.length + + pass4ConflictsCount + + pass6.conflicts.length, + }; + + const malformedSampleCloses = pass4?.stats.droppedInvalidCloses ?? 0; + const malformedFxRates = pass4?.stats.droppedInvalidFxRates ?? 0; + const malformedInputs: ComposeMalformedInputStats = { + stageARecords: malformedStageARecords, + eodListings: attached.malformed.eodListings, + ibContracts: attached.malformed.ibContracts, + tickerSources: attached.malformed.tickerSources, + symbolChanges: attached.malformed.symbolChanges, + barSpans: attached.malformed.barSpans, + sampleCloses: malformedSampleCloses, + fxRates: malformedFxRates, + total: + malformedStageARecords + + attached.malformed.eodListings + + attached.malformed.ibContracts + + attached.malformed.tickerSources + + attached.malformed.symbolChanges + + attached.malformed.barSpans + + malformedSampleCloses + + malformedFxRates, + }; + + return { + stageA, + stageB, + pass6, + pass4, + pass4CandidatePairs, + report, + reportMarkdown, + conflictsCsv, + overrideTemplateSql, + persistInput, + stats: { + barSpans: attached.stats, + stageA: stageAStepStats, + stageB: stageBStepStats, + pass6: pass6StepStats, + pass4: pass4StepStats, + conflicts: conflictTotals, + malformedInputs, + }, + }; +} diff --git a/apps/stock/data-pipeline/src/security-master/security-type.ts b/apps/stock/data-pipeline/src/security-master/security-type.ts new file mode 100644 index 00000000..583ad416 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/security-type.ts @@ -0,0 +1,325 @@ +/** + * Pure, deterministic EODHD `Type` -> `SecurityType` classifier for the security-master loader. + * + * Vocabulary note: QA MongoDB (`eodSymbols`) is unreachable from the sandbox, so + * `EOD_SECURITY_TYPE_MAP` reflects the published EODHD `Type` vocabulary. Non-equity-like values + * (`FUND`, `Mutual Fund`, `Bond`, `Notes`, `INDEX`, etc.) and any unmapped provider strings + * return `null` and are surfaced in `unknownRawTypes` for review rather than guessed from ticker + * suffixes or company names. + */ +import { compareAscii } from './exchange-pass1'; +import type { StageAInstrumentCandidate } from './instrument-stage-a'; +import type { SecurityType } from './persist'; + +export const DEFAULT_MAX_SECURITY_TYPE_CONFLICTS = 200; + +/** + * Published EODHD `Type` vocabulary mapped to the canonical PostgreSQL `instrument.security_type` + * enum (`SecurityType`). Keys are trimmed, whitespace-collapsed uppercase strings. + */ +export const EOD_SECURITY_TYPE_MAP: Readonly> = Object.freeze({ + 'COMMON STOCK': 'common', + 'PREFERRED STOCK': 'preferred', + ETF: 'etf', + UNIT: 'unit', + UNITS: 'unit', + WARRANT: 'warrant', + WARRANTS: 'warrant', + RIGHT: 'right', + RIGHTS: 'right', + CDR: 'cdr', + CURRENCY: 'fx', + FOREX: 'fx', + FX: 'fx', +}); + +// Backing Map avoids prototype-chain lookups (e.g. `toString`, `constructor`, `__proto__`). +const EOD_SECURITY_TYPE_LOOKUP: ReadonlyMap = new Map( + Object.entries(EOD_SECURITY_TYPE_MAP) +); + +const WHITESPACE_RUN_PATTERN = /\s+/g; + +export interface SecurityTypeInputRecord { + readonly isin: string | null; + readonly rawType: unknown; + readonly sourceId: string; +} + +export interface UnknownSecurityTypeCount { + readonly rawType: string; + readonly count: number; +} + +export interface SecurityTypeConflict { + readonly isin: string; + readonly types: readonly SecurityType[]; + readonly sourceIds: readonly string[]; + readonly recordCount: number; +} + +export interface SecurityTypeClassificationStats { + recordsIn: number; + classified: number; + missingIsin: number; + missingType: number; + unknownType: number; + distinctClassifiedIsins: number; + isinsMapped: number; + isinsConflicting: number; + conflictsTruncated: number; +} + +export interface BuildSecurityTypeByIsinOptions { + readonly maxConflicts?: number; +} + +export interface BuildSecurityTypeByIsinResult { + securityTypeByIsin: Map; + stats: SecurityTypeClassificationStats; + unknownRawTypes: UnknownSecurityTypeCount[]; + conflicts: SecurityTypeConflict[]; +} + +function normalizeRawTypeString(rawType: string): string { + const trimmed = rawType.trim(); + if (trimmed.length === 0) { + return ''; + } + return trimmed.replace(WHITESPACE_RUN_PATTERN, ' '); +} + +/** + * Maps an EODHD `Type` value (trimmed, case-insensitive, whitespace-collapsed) to the canonical + * `SecurityType` union. Returns `null` for non-strings, blanks, non-equity values (`FUND`, + * `Mutual Fund`, `Bond`, `Notes`, `INDEX`, etc.), and unmapped strings. Never guesses from + * ticker suffixes or names. + */ +export function classifyEodSecurityType(rawType: unknown): SecurityType | null { + if (typeof rawType !== 'string') { + return null; + } + const normalized = normalizeRawTypeString(rawType); + if (normalized.length === 0) { + return null; + } + return EOD_SECURITY_TYPE_LOOKUP.get(normalized.toUpperCase()) ?? null; +} + +interface ConflictAccumulator { + readonly types: Set; + readonly sourceIds: Set; + recordCount: number; +} + +/** + * Aggregates EODHD security-type records by ISIN into a deterministic `securityTypeByIsin` map + * for `persistSecurityMaster`, omitting any ISIN whose classified records disagree and reporting + * conflicts and unmapped raw `Type` values in deterministic order. + */ +export function buildSecurityTypeByIsin( + records: readonly SecurityTypeInputRecord[], + options: BuildSecurityTypeByIsinOptions = {} +): BuildSecurityTypeByIsinResult { + const maxConflicts = options.maxConflicts ?? DEFAULT_MAX_SECURITY_TYPE_CONFLICTS; + if (!Number.isInteger(maxConflicts) || maxConflicts < 0) { + throw new RangeError( + `buildSecurityTypeByIsin: maxConflicts must be a non-negative integer (received ${String(maxConflicts)})` + ); + } + + let classified = 0; + let missingIsin = 0; + let missingType = 0; + let unknownType = 0; + + const rawByIsin = new Map(); + const conflictingIsins = new Set(); + const unknownCounts = new Map(); + + for (let i = 0; i < records.length; i++) { + const record = records[i]; + if (record === undefined) { + continue; + } + + if (typeof record.isin !== 'string') { + missingIsin += 1; + continue; + } + const isin = record.isin.trim(); + if (isin.length === 0) { + missingIsin += 1; + continue; + } + + if (typeof record.rawType !== 'string') { + missingType += 1; + continue; + } + const displayRawType = normalizeRawTypeString(record.rawType); + if (displayRawType.length === 0) { + missingType += 1; + continue; + } + + const mapped = EOD_SECURITY_TYPE_LOOKUP.get(displayRawType.toUpperCase()); + if (mapped === undefined) { + unknownType += 1; + unknownCounts.set(displayRawType, (unknownCounts.get(displayRawType) ?? 0) + 1); + continue; + } + + classified += 1; + + if (conflictingIsins.has(isin)) { + continue; + } + + const existing = rawByIsin.get(isin); + if (existing === undefined) { + rawByIsin.set(isin, mapped); + } else if (existing !== mapped) { + rawByIsin.delete(isin); + conflictingIsins.add(isin); + } + } + + const conflicts: SecurityTypeConflict[] = []; + if (conflictingIsins.size > 0 && maxConflicts > 0) { + const sortedConflictingIsins = [...conflictingIsins].sort(compareAscii); + const sampleLimit = Math.min(sortedConflictingIsins.length, maxConflicts); + const accumulators = new Map(); + + for (let i = 0; i < sampleLimit; i++) { + const isin = sortedConflictingIsins[i]; + if (isin !== undefined) { + accumulators.set(isin, { + types: new Set(), + sourceIds: new Set(), + recordCount: 0, + }); + } + } + + // Pass 2 runs only when conflicts exist so the non-conflicting fast path allocates no wrappers. + for (let i = 0; i < records.length; i++) { + const record = records[i]; + if (record === undefined || typeof record.isin !== 'string') { + continue; + } + const isin = record.isin.trim(); + const acc = accumulators.get(isin); + if (acc === undefined) { + continue; + } + const mapped = classifyEodSecurityType(record.rawType); + if (mapped === null) { + continue; + } + acc.types.add(mapped); + acc.sourceIds.add(record.sourceId); + acc.recordCount += 1; + } + + for (let i = 0; i < sampleLimit; i++) { + const isin = sortedConflictingIsins[i]; + if (isin === undefined) { + continue; + } + const acc = accumulators.get(isin); + if (acc !== undefined) { + conflicts.push({ + isin, + types: [...acc.types].sort(compareAscii), + sourceIds: [...acc.sourceIds].sort(compareAscii), + recordCount: acc.recordCount, + }); + } + } + } + + const securityTypeByIsin = new Map(); + const sortedMappedIsins = [...rawByIsin.keys()].sort(compareAscii); + for (let i = 0; i < sortedMappedIsins.length; i++) { + const isin = sortedMappedIsins[i]; + if (isin !== undefined) { + const securityType = rawByIsin.get(isin); + if (securityType !== undefined) { + securityTypeByIsin.set(isin, securityType); + } + } + } + + const unknownRawTypes: UnknownSecurityTypeCount[] = []; + for (const [rawType, count] of unknownCounts.entries()) { + unknownRawTypes.push({ rawType, count }); + } + unknownRawTypes.sort((a, b) => b.count - a.count || compareAscii(a.rawType, b.rawType)); + + const isinsMapped = securityTypeByIsin.size; + const isinsConflicting = conflictingIsins.size; + + return { + securityTypeByIsin, + stats: { + recordsIn: records.length, + classified, + missingIsin, + missingType, + unknownType, + distinctClassifiedIsins: isinsMapped + isinsConflicting, + isinsMapped, + isinsConflicting, + conflictsTruncated: isinsConflicting - conflicts.length, + }, + unknownRawTypes, + conflicts, + }; +} + +/** + * Builds the loader-facing `securityTypeByIsin` map strictly from EOD rows accepted as Stage A + * instrument members (`member.source === 'eod'`), keyed by each instrument's `primaryIsin`. + * Stage A-quarantined rows (e.g. `isin_cusip_mismatch`, `duplicate_source_id`) and unresolved + * rows are excluded so they can neither supply nor veto a valid instrument's security type. + */ +export function buildSecurityTypeByIsinForStageA( + records: readonly SecurityTypeInputRecord[], + instruments: readonly StageAInstrumentCandidate[], + options: BuildSecurityTypeByIsinOptions = {} +): BuildSecurityTypeByIsinResult { + const acceptedIsinByEodSourceId = new Map(); + for (let i = 0; i < instruments.length; i++) { + const instrument = instruments[i]; + if (instrument === undefined) { + continue; + } + const members = instrument.members; + for (let j = 0; j < members.length; j++) { + const member = members[j]; + if (member !== undefined && member.source === 'eod') { + acceptedIsinByEodSourceId.set(member.sourceId, instrument.primaryIsin); + } + } + } + + const acceptedRecords: SecurityTypeInputRecord[] = []; + for (let i = 0; i < records.length; i++) { + const record = records[i]; + if (record === undefined) { + continue; + } + const primaryIsin = acceptedIsinByEodSourceId.get(record.sourceId); + if (primaryIsin === undefined) { + continue; + } + acceptedRecords.push({ + isin: primaryIsin, + rawType: record.rawType, + sourceId: record.sourceId, + }); + } + + return buildSecurityTypeByIsin(acceptedRecords, options); +} diff --git a/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts b/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts new file mode 100644 index 00000000..58b7ea6a --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts @@ -0,0 +1,1981 @@ +import type { MongoDBClient } from '@stock-bot/mongodb'; +import { + normalizeBarDate, + type BarSpanIndex, + type SpanDateRange, +} from '../normalization/bar-spans'; +import { cusipToIsin, isValidCusip, isValidIsin } from '../normalization/identifiers'; +import { normalizeProviderSymbol } from '../normalization/provider-symbol'; +import { parseTickerDetailed } from '../normalization/ticker'; +import { + compareAscii, + EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS, + ISO_EXCHANGE_SEEDS, + REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS, + type ExchangeRole, + type ExchangeSeedRow, + type ExchangeSource, + type ExchangeSourceMapRow, +} from './exchange-pass1'; +import { matchInstrumentsStageA, type StageASourceRecord } from './instrument-stage-a'; +import { + MAX_TICKER_ROOT_LENGTH, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBInput, + type StageBSymbolChangeInput, + type StageBTickerSourceInput, +} from './listing-stage-b'; +import type { SecurityType } from './persist'; +import { + buildSecurityTypeByIsin, + buildSecurityTypeByIsinForStageA, + type SecurityTypeClassificationStats, + type SecurityTypeConflict, + type SecurityTypeInputRecord, + type UnknownSecurityTypeCount, +} from './security-type'; + +export const SOURCE_SYMBOL_COLLECTIONS = Object.freeze({ + eod: 'eodSymbols', + ib: 'ibSymbols', + qm: 'qmSymbols', + ceo: 'ceoSymbols', + eodSymbolChange: 'eodSymbolChange', +} as const); + +export type SourceSymbolCollectionKey = keyof typeof SOURCE_SYMBOL_COLLECTIONS; +export type SourceSymbolCollectionName = + (typeof SOURCE_SYMBOL_COLLECTIONS)[SourceSymbolCollectionKey]; + +export const DEFAULT_SOURCE_COUNTRIES: readonly string[] = Object.freeze(['US', 'CA']); + +export interface SourceSymbolFindOptions { + projection?: Record; + batchSize?: number; +} + +/** + * Minimal cursor contract returned by a read-only MongoDB collection `find()`. + * Supports incremental async iteration without materializing the full result set. + */ +export interface ReadOnlySourceSymbolCursor< + T extends Record = Record, +> extends AsyncIterable { + close?(): Promise; +} + +/** + * Minimal read-only collection view exposing strictly `find()` returning an + * incremental async cursor. + */ +export interface ReadOnlySourceSymbolCollection { + find( + filter: Record, + options?: SourceSymbolFindOptions + ): ReadOnlySourceSymbolCursor>; +} + +/** + * Minimal structural slice of a read-only `MongoDBClient` required to construct + * a cursor-backed `ReadOnlySourceSymbolReader` via `createReadOnlyMongoSourceSymbolReader`. + */ +export interface ReadOnlyMongoCollectionClient { + isReadOnly(): boolean; + getCollection(name: string): ReadOnlySourceSymbolCollection; +} + +/** + * Narrow read-only MongoDB reader interface for source-symbol collections. + * Exposes strictly `isReadOnly()` and `find()` returning an incremental + * `AsyncIterable` — no write, index, drop, collection-mutation, or eager array + * buffering methods are reachable through this contract. + */ +export interface ReadOnlySourceSymbolReader { + isReadOnly(): boolean; + find = Record>( + collectionName: string, + filter?: Record, + options?: SourceSymbolFindOptions + ): Promise> | AsyncIterable; +} + +// Compile-time structural compatibility check (type-only, erased at runtime): +// ensures the real `MongoDBClient` satisfies `ReadOnlyMongoCollectionClient` +// so `createReadOnlyMongoSourceSymbolReader(client)` streams via `FindCursor` +// instead of `MongoDBClient.find()`'s `cursor.toArray()` buffering. +type AssertAssignable = true; +export type MongoDBClientSourceSymbolReaderCheck = AssertAssignable< + ReadOnlyMongoCollectionClient, + MongoDBClient +>; + +export interface ExchangeSourceLookupEntry { + readonly source: ExchangeSource; + readonly sourceCode: string; + readonly role: ExchangeRole; + readonly mic: string | null; + readonly countryIso: string | null; +} + +export interface ExchangeSourceLookup { + get(source: ExchangeSource, sourceCode: string): ExchangeSourceLookupEntry | undefined; + getCodesForCountries?(source: ExchangeSource, countries: readonly string[]): string[]; +} + +export interface CreateExchangeSourceLookupOptions { + readonly includeExplicitRules?: boolean; + readonly includeReviewedUsCaVenues?: boolean; +} + +export type SourceSymbolSkipReason = + | 'missingId' + | 'invalidFieldType' + | 'invalidIdentifier' + | 'excludedMutualFund' + | 'unmappedExchange' + | 'outOfScopeCountry'; + +export interface SourceSymbolSkipCounts { + missingId: number; + invalidFieldType: number; + invalidIdentifier: number; + excludedMutualFund: number; + unmappedExchange: number; + outOfScopeCountry: number; +} + +export interface SourceCollectionReadStats { + collection: SourceSymbolCollectionName; + docsRead: number; + emitted: number; + invalidIdentifiersNulled: number; + skips: SourceSymbolSkipCounts; +} + +export interface ReadSourceCollectionOptions { + readonly exchangeLookup: ExchangeSourceLookup; + readonly barSpans?: Pick | null; + readonly ceoSpans?: ReadonlyMap | null; + readonly countries?: readonly string[] | null; + readonly knownExchanges?: readonly ExchangeSeedRow[]; + readonly batchSize?: number; + readonly maxSecurityTypeConflicts?: number; +} + +export type ReadSecurityMasterSourcesOptions = ReadSourceCollectionOptions; + +export interface AdaptEodSymbolContext { + readonly exchangeLookup: ExchangeSourceLookup; + readonly barSpans?: Pick | null; + readonly allowedCountries: ReadonlySet | null; + readonly micCurrencyMap: ReadonlyMap; +} + +export interface AdaptIbSymbolContext { + readonly exchangeLookup: ExchangeSourceLookup; + readonly allowedCountries: ReadonlySet | null; +} + +export interface AdaptQmSymbolContext { + readonly exchangeLookup: ExchangeSourceLookup; + readonly barSpans?: Pick | null; + readonly allowedCountries: ReadonlySet | null; + readonly micCurrencyMap: ReadonlyMap; +} + +export interface AdaptCeoSymbolContext { + readonly exchangeLookup: ExchangeSourceLookup; + readonly ceoSpans?: ReadonlyMap | null; + readonly allowedCountries: ReadonlySet | null; + readonly micCurrencyMap: ReadonlyMap; +} + +export interface AdaptEodSymbolChangeContext { + readonly exchangeLookup: ExchangeSourceLookup; + readonly allowedCountries: ReadonlySet | null; +} + +export type AdaptEodSymbolResult = + | { + readonly ok: true; + readonly stageARecord: StageASourceRecord; + readonly eodListing: StageBEodListingInput; + readonly rawType: string | null; + readonly resolvedIsin: string | null; + readonly invalidIdentifiersNulled: number; + } + | { readonly ok: false; readonly skipReason: SourceSymbolSkipReason }; + +export type AdaptIbSymbolResult = + | { + readonly ok: true; + readonly stageARecord: StageASourceRecord; + readonly ibContract: StageBIbContractInput; + readonly invalidIdentifiersNulled: number; + } + | { readonly ok: false; readonly skipReason: SourceSymbolSkipReason }; + +export type AdaptTickerSourceResult = + | { + readonly ok: true; + readonly tickerSource: StageBTickerSourceInput; + } + | { readonly ok: false; readonly skipReason: SourceSymbolSkipReason }; + +export type AdaptEodSymbolChangeResult = + | { + readonly ok: true; + readonly symbolChange: StageBSymbolChangeInput; + } + | { readonly ok: false; readonly skipReason: SourceSymbolSkipReason }; + +export interface ReadEodSymbolsResult { + stageARecords: StageASourceRecord[]; + eodListings: StageBEodListingInput[]; + securityTypeRecords: SecurityTypeInputRecord[]; + securityTypeByIsin: Map; + securityTypeStats: SecurityTypeClassificationStats; + securityTypeLoaderStats: SecurityTypeClassificationStats; + unknownSecurityTypes: UnknownSecurityTypeCount[]; + securityTypeConflicts: SecurityTypeConflict[]; + stats: SourceCollectionReadStats; +} + +export interface ReadIbSymbolsResult { + stageARecords: StageASourceRecord[]; + ibContracts: StageBIbContractInput[]; + stats: SourceCollectionReadStats; +} + +export interface ReadTickerSourcesResult { + tickerSources: StageBTickerSourceInput[]; + stats: SourceCollectionReadStats; +} + +export interface ReadEodSymbolChangesResult { + symbolChanges: StageBSymbolChangeInput[]; + stats: SourceCollectionReadStats; +} + +export interface SecurityMasterStageBSourceInput + extends Omit { + eodListings: StageBEodListingInput[]; + ibContracts: StageBIbContractInput[]; + tickerSources: StageBTickerSourceInput[]; + symbolChanges: StageBSymbolChangeInput[]; +} + +export interface SecurityMasterSourcesStats { + eodSymbols: SourceCollectionReadStats; + ibSymbols: SourceCollectionReadStats; + qmSymbols: SourceCollectionReadStats; + ceoSymbols: SourceCollectionReadStats; + eodSymbolChange: SourceCollectionReadStats; +} + +export interface SecurityMasterSourcesResult { + stageARecords: StageASourceRecord[]; + stageBInput: SecurityMasterStageBSourceInput; + securityTypeRecords: SecurityTypeInputRecord[]; + securityTypeByIsin: Map; + securityTypeStats: SecurityTypeClassificationStats; + securityTypeLoaderStats: SecurityTypeClassificationStats; + unknownSecurityTypes: UnknownSecurityTypeCount[]; + securityTypeConflicts: SecurityTypeConflict[]; + stats: SecurityMasterSourcesStats; +} + +const ISO2_PATTERN = /^[A-Z]{2}$/; + +const COUNTRY_ISO2_ALIASES: Readonly> = Object.freeze({ + US: Object.freeze(['US', 'USA', 'U.S.', 'U.S.A.', 'United States', 'United States of America']), + CA: Object.freeze(['CA', 'CAN', 'Canada']), + GB: Object.freeze(['GB', 'GBR', 'UK', 'United Kingdom', 'Great Britain']), + DE: Object.freeze(['DE', 'DEU', 'Germany']), + FR: Object.freeze(['FR', 'FRA', 'France']), + AU: Object.freeze(['AU', 'AUS', 'Australia']), + JP: Object.freeze(['JP', 'JPN', 'Japan']), + CN: Object.freeze(['CN', 'CHN', 'China']), + HK: Object.freeze(['HK', 'HKG', 'Hong Kong']), + CH: Object.freeze(['CH', 'CHE', 'Switzerland']), + NL: Object.freeze(['NL', 'NLD', 'Netherlands']), + IT: Object.freeze(['IT', 'ITA', 'Italy']), + ES: Object.freeze(['ES', 'ESP', 'Spain']), + SE: Object.freeze(['SE', 'SWE', 'Sweden']), + NO: Object.freeze(['NO', 'NOR', 'Norway']), + DK: Object.freeze(['DK', 'DNK', 'Denmark']), + FI: Object.freeze(['FI', 'FIN', 'Finland']), + BE: Object.freeze(['BE', 'BEL', 'Belgium']), + AT: Object.freeze(['AT', 'AUT', 'Austria']), + IE: Object.freeze(['IE', 'IRL', 'Ireland']), + IN: Object.freeze(['IN', 'IND', 'India']), + BR: Object.freeze(['BR', 'BRA', 'Brazil']), + MX: Object.freeze(['MX', 'MEX', 'Mexico']), + KR: Object.freeze(['KR', 'KOR', 'South Korea', 'Korea']), + TW: Object.freeze(['TW', 'TWN', 'Taiwan']), + SG: Object.freeze(['SG', 'SGP', 'Singapore']), + NZ: Object.freeze(['NZ', 'NZL', 'New Zealand']), + IL: Object.freeze(['IL', 'ISR', 'Israel']), + ZA: Object.freeze(['ZA', 'ZAF', 'South Africa']), + PL: Object.freeze(['PL', 'POL', 'Poland']), + PT: Object.freeze(['PT', 'PRT', 'Portugal']), + GR: Object.freeze(['GR', 'GRC', 'Greece']), + TR: Object.freeze(['TR', 'TUR', 'Turkey']), + AR: Object.freeze(['AR', 'ARG', 'Argentina']), + CL: Object.freeze(['CL', 'CHL', 'Chile']), + ID: Object.freeze(['ID', 'IDN', 'Indonesia']), + MY: Object.freeze(['MY', 'MYS', 'Malaysia']), + TH: Object.freeze(['TH', 'THA', 'Thailand']), + VN: Object.freeze(['VN', 'VNM', 'Vietnam']), + PH: Object.freeze(['PH', 'PHL', 'Philippines']), + SA: Object.freeze(['SA', 'SAU', 'Saudi Arabia']), + AE: Object.freeze(['AE', 'ARE', 'UAE', 'United Arab Emirates']), +}); + +const COUNTRY_NAME_TO_ISO2: ReadonlyMap = (() => { + const map = new Map(); + for (const [iso, aliases] of Object.entries(COUNTRY_ISO2_ALIASES)) { + for (let i = 0; i < aliases.length; i++) { + const alias = aliases[i]; + if (alias !== undefined) { + map.set(alias.toUpperCase(), iso); + } + } + } + return map; +})(); + +const COUNTRY_ISO2_TO_FILTER_VALUES: ReadonlyMap = (() => { + const map = new Map(); + for (const [iso, aliases] of Object.entries(COUNTRY_ISO2_ALIASES)) { + const values = new Set(); + for (let i = 0; i < aliases.length; i++) { + const alias = aliases[i]; + if (alias !== undefined) { + values.add(alias); + values.add(alias.toUpperCase()); + } + } + map.set(iso, Object.freeze([...values].sort(compareAscii))); + } + return map; +})(); + +export const EOD_SYMBOLS_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + eodSearchCode: 1, + Code: 1, + code: 1, + symbol: 1, + Exchange: 1, + eodExchange: 1, + exchange: 1, + exchangeCode: 1, + Country: 1, + countryCode: 1, + Currency: 1, + currency: 1, + Isin: 1, + isin: 1, + Cusip: 1, + cusip: 1, + Name: 1, + name: 1, + companyName: 1, + Type: 1, + type: 1, + delisted: 1, +}); + +export const IB_SYMBOLS_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + conid: 1, + symbol: 1, + localSymbol: 1, + exchangeId: 1, + exchange: 1, + exchangeCode: 1, + primaryExchange: 1, + listingExchange: 1, + country: 1, + countryCode: 1, + currency: 1, + isin: 1, + cusip: 1, + description: 1, + name: 1, + companyName: 1, +}); + +export const QM_SYMBOLS_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + qmSearchCode: 1, + symbol: 1, + code: 1, + exchange: 1, + exchangeCode: 1, + countryCode: 1, + country: 1, + currency: 1, + name: 1, + companyName: 1, + active: 1, +}); + +export const CEO_SYMBOLS_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + ceoId: 1, + symbol: 1, + exchange: 1, + exchangeCode: 1, + countryCode: 1, + country: 1, + currency: 1, + name: 1, + lastSeen: 1, +}); + +export const EOD_SYMBOL_CHANGE_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + oldSymbol: 1, + newSymbol: 1, + exchange: 1, + eodExchange: 1, + eodSearchCode: 1, + effective: 1, + date: 1, + effectiveDate: 1, + validFrom: 1, + country: 1, + Country: 1, +}); + +/** + * Normalizes ISO-2 country codes and common provider country name spellings + * (e.g. EODHD `'USA'`, `'United States'`, `'Canada'`) to uppercase ISO-2. + */ +export function normalizeCountryIso2(value: string | null | undefined): string | null { + if (typeof value !== 'string') { + return null; + } + const trimmed = value.trim(); + if (trimmed.length === 0) { + return null; + } + const upper = trimmed.toUpperCase(); + const mapped = COUNTRY_NAME_TO_ISO2.get(upper); + if (mapped !== undefined) { + return mapped; + } + return ISO2_PATTERN.test(upper) ? upper : null; +} + +/** + * Builds an in-memory per-source lookup map from Pass 1 `exchange_source_map` rows. + * Seeds `EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS` and `REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS` + * by default with caller rows taking highest precedence. + */ +export function createExchangeSourceLookup( + rows: readonly ExchangeSourceMapRow[] = [], + options: CreateExchangeSourceLookupOptions = {} +): ExchangeSourceLookup { + const bySource: Readonly>> = { + eod: new Map(), + ib: new Map(), + qm: new Map(), + ceo: new Map(), + }; + + const insertRow = (row: ExchangeSourceMapRow): void => { + const code = row.sourceCode.trim().toUpperCase(); + if (code.length === 0) { + return; + } + const mic = row.mic === null ? null : row.mic.trim().toUpperCase() || null; + const countryIso = + row.countryIso === null + ? null + : (normalizeCountryIso2(row.countryIso) ?? (row.countryIso.trim().toUpperCase() || null)); + bySource[row.source].set(code, { + source: row.source, + sourceCode: code, + role: row.role, + mic, + countryIso, + }); + }; + + if (options.includeExplicitRules !== false) { + for (let i = 0; i < EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS.length; i++) { + const row = EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS[i]; + if (row !== undefined) { + insertRow(row); + } + } + } + + if (options.includeReviewedUsCaVenues !== false) { + for (let i = 0; i < REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS.length; i++) { + const row = REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS[i]; + if (row !== undefined) { + insertRow(row); + } + } + } + + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if (row !== undefined) { + insertRow(row); + } + } + + return { + get(source: ExchangeSource, sourceCode: string): ExchangeSourceLookupEntry | undefined { + const code = sourceCode.trim().toUpperCase(); + if (code.length === 0) { + return undefined; + } + return bySource[source].get(code); + }, + getCodesForCountries(source: ExchangeSource, countries: readonly string[]): string[] { + const allowed = new Set(); + for (let i = 0; i < countries.length; i++) { + const iso = normalizeCountryIso2(countries[i]); + if (iso !== null) { + allowed.add(iso); + } + } + if (allowed.size === 0) { + return []; + } + const codes: string[] = []; + for (const entry of bySource[source].values()) { + if (entry.countryIso !== null && allowed.has(entry.countryIso)) { + codes.push(entry.sourceCode); + } + } + codes.sort(compareAscii); + return codes; + }, + }; +} + +function buildMicCurrencyMap( + knownExchanges: readonly ExchangeSeedRow[] = ISO_EXCHANGE_SEEDS +): ReadonlyMap { + const map = new Map(); + for (let i = 0; i < knownExchanges.length; i++) { + const row = knownExchanges[i]; + if (row === undefined) { + continue; + } + const mic = row.mic.trim().toUpperCase(); + const currency = row.currency.trim().toUpperCase(); + if (mic.length > 0 && currency.length > 0) { + map.set(mic, currency); + } + } + return map; +} + +function resolveAllowedCountries(countries?: readonly string[] | null): { + set: ReadonlySet | null; + list: string[] | null; +} { + if (countries === null) { + return { set: null, list: null }; + } + const source = countries === undefined ? DEFAULT_SOURCE_COUNTRIES : countries; + const set = new Set(); + for (let i = 0; i < source.length; i++) { + const raw = source[i]; + const normalized = normalizeCountryIso2(raw); + if (normalized !== null) { + set.add(normalized); + } else if (typeof raw === 'string' && raw.trim().length > 0) { + set.add(raw.trim().toUpperCase()); + } + } + const list = [...set].sort(compareAscii); + return { set, list }; +} + +function createEmptySkipCounts(): SourceSymbolSkipCounts { + return { + missingId: 0, + invalidFieldType: 0, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 0, + outOfScopeCountry: 0, + }; +} + +function createCollectionStats( + collection: SourceSymbolCollectionName +): SourceCollectionReadStats { + return { + collection, + docsRead: 0, + emitted: 0, + invalidIdentifiersNulled: 0, + skips: createEmptySkipCounts(), + }; +} + +function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void { + if ( + reader === null || + reader === undefined || + typeof reader !== 'object' || + typeof reader.isReadOnly !== 'function' || + !reader.isReadOnly() + ) { + throw new Error( + 'Source symbol reader requires a read-only MongoDB client (isReadOnly() must be true)' + ); + } +} + +function isAsyncIterable(value: unknown): value is AsyncIterable { + return ( + value !== null && + (typeof value === 'object' || typeof value === 'function') && + typeof (value as Record)[Symbol.asyncIterator] === 'function' + ); +} + +/** + * Adapts a read-only `MongoDBClient` (or compatible `ReadOnlyMongoCollectionClient`) + * into a cursor-backed `ReadOnlySourceSymbolReader` that streams documents + * incrementally via `collection.find(filter, options)` without buffering the full + * collection through `cursor.toArray()`. + */ +export function createReadOnlyMongoSourceSymbolReader( + client: ReadOnlyMongoCollectionClient +): ReadOnlySourceSymbolReader { + if ( + client === null || + client === undefined || + typeof client !== 'object' || + typeof client.isReadOnly !== 'function' || + !client.isReadOnly() + ) { + throw new Error( + 'Source symbol reader requires a read-only MongoDB client (isReadOnly() must be true)' + ); + } + + return Object.freeze({ + isReadOnly(): boolean { + return client.isReadOnly(); + }, + find = Record>( + collectionName: string, + filter: Record = {}, + options?: SourceSymbolFindOptions + ): AsyncIterable { + if (!client.isReadOnly()) { + throw new Error( + 'Source symbol reader requires a read-only MongoDB client (isReadOnly() must be true)' + ); + } + const collection = client.getCollection(collectionName); + const cursor = collection.find(filter, options); + if (Array.isArray(cursor) || !isAsyncIterable>(cursor)) { + throw new TypeError( + `Collection "${collectionName}" find() must return an incremental async cursor (got buffered or non-async result)` + ); + } + return { + async *[Symbol.asyncIterator](): AsyncIterator { + try { + for await (const doc of cursor) { + yield doc as T; + } + } finally { + if (typeof cursor.close === 'function') { + await cursor.close(); + } + } + }, + }; + }, + }); +} + +async function streamCollection>( + reader: ReadOnlySourceSymbolReader, + collectionName: SourceSymbolCollectionName, + filter: Record, + options: SourceSymbolFindOptions, + onDoc: (doc: unknown) => void +): Promise { + assertReadOnlyReader(reader); + try { + const cursor = await reader.find(collectionName, filter, options); + if (Array.isArray(cursor) || !isAsyncIterable(cursor)) { + throw new TypeError( + `Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (use createReadOnlyMongoSourceSymbolReader for MongoDBClient)` + ); + } + for await (const doc of cursor) { + onDoc(doc); + } + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + const message = detail.includes(collectionName) + ? detail + : `Failed reading collection "${collectionName}": ${detail}`; + throw new Error(message, { cause: error }); + } +} + +type StringFieldResult = { readonly ok: true; readonly value: string | null } | { readonly ok: false }; + +function readOptionalString(doc: Record, key: string): StringFieldResult { + const raw = doc[key]; + if (raw === undefined || raw === null) { + return { ok: true, value: null }; + } + if (typeof raw !== 'string') { + return { ok: false }; + } + const trimmed = raw.trim(); + return { ok: true, value: trimmed.length > 0 ? trimmed : null }; +} + +function readFirstOptionalString( + doc: Record, + keys: readonly string[] +): StringFieldResult { + let found: string | null = null; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (key === undefined) { + continue; + } + const res = readOptionalString(doc, key); + if (!res.ok) { + return res; + } + if (found === null && res.value !== null) { + found = res.value; + } + } + return { ok: true, value: found }; +} + +function isPlainRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** + * Extracts raw EODHD `Type`/`type` without rejecting non-string values so a malformed `Type` + * never skips the symbol document. Non-string and blank values normalize to `null` so + * `securityTypeRecords` ordering is deterministic while still counting as `missingType`. + */ +function readRawSecurityType(doc: Record): string | null { + if (typeof doc.Type === 'string' && doc.Type.trim().length > 0) { + return doc.Type; + } + if (typeof doc.type === 'string' && doc.type.trim().length > 0) { + return doc.type; + } + return null; +} + +function isNorthAmericaIso(code: string | null): code is 'US' | 'CA' { + return code === 'US' || code === 'CA'; +} + +function countryFallbackCurrency(countryIso: string | null): string | null { + if (countryIso === 'US') { + return 'USD'; + } + if (countryIso === 'CA') { + return 'CAD'; + } + return null; +} + +function formatCanonicalTicker(tickerRoot: string, classSuffix: string): string { + return classSuffix.length > 0 ? `${tickerRoot}.${classSuffix}` : tickerRoot; +} + +/** + * Formats a parsed CEO ticker so Stage B's `parseTickerDetailed(ticker, 'ceo')` + * recovers the exact `(tickerRoot, classSuffix)` without double-stripping a + * share-class suffix that happens to be `TO` or `V`. + */ +function formatStageBSafeCeoTicker(tickerRoot: string, classSuffix: string): string { + if (classSuffix.length === 0) { + return tickerRoot; + } + if (classSuffix === 'TO' || classSuffix === 'V') { + return `${tickerRoot}-${classSuffix}`; + } + if (classSuffix.endsWith('.TO')) { + return `${tickerRoot}.${classSuffix.slice(0, -3)}-TO`; + } + if (classSuffix.endsWith('.V')) { + return `${tickerRoot}.${classSuffix.slice(0, -2)}-V`; + } + return `${tickerRoot}.${classSuffix}`; +} + +function toSpanDateRange(span: SpanDateRange | undefined | null): SpanDateRange | null { + if (span === undefined || span === null) { + return null; + } + return { + firstBarDate: span.firstBarDate, + lastBarDate: span.lastBarDate, + }; +} + +const EMPTY_MATCH_FILTER: Record = Object.freeze({ _id: { $in: [] } }); + +function expandCountryFilterValues(countries: readonly string[]): string[] { + const expanded = new Set(); + for (let i = 0; i < countries.length; i++) { + const raw = countries[i]; + if (raw === undefined) { + continue; + } + const iso = normalizeCountryIso2(raw) ?? raw.trim().toUpperCase(); + if (iso.length === 0) { + continue; + } + expanded.add(iso); + const aliases = COUNTRY_ISO2_TO_FILTER_VALUES.get(iso); + if (aliases !== undefined) { + for (let j = 0; j < aliases.length; j++) { + const alias = aliases[j]; + if (alias !== undefined) { + expanded.add(alias); + } + } + } + } + return [...expanded].sort(compareAscii); +} + +function buildOrFilter(clauses: readonly Record[]): Record { + const first = clauses[0]; + if (first === undefined) { + return { ...EMPTY_MATCH_FILTER }; + } + if (clauses.length === 1) { + return first; + } + return { $or: [...clauses] }; +} + +function buildEodCountryFilter( + exchangeLookup: ExchangeSourceLookup, + countries: readonly string[] | null +): Record { + if (countries === null) { + return {}; + } + const countryValues = expandCountryFilterValues(countries); + if (countryValues.length === 0) { + return { ...EMPTY_MATCH_FILTER }; + } + // When the lookup cannot enumerate in-scope venue codes, keep the query conservative + // so countryless documents that derive country from Exchange are not dropped before the adapter. + if (typeof exchangeLookup.getCodesForCountries !== 'function') { + return {}; + } + const exchangeCodes = exchangeLookup.getCodesForCountries('eod', countries); + + const clauses: Record[] = [ + { Country: { $in: countryValues } }, + { countryCode: { $in: countryValues } }, + ]; + if (exchangeCodes.length > 0) { + clauses.push({ Exchange: { $in: exchangeCodes } }); + clauses.push({ exchange: { $in: exchangeCodes } }); + clauses.push({ exchangeCode: { $in: exchangeCodes } }); + } + return buildOrFilter(clauses); +} + +function buildIbCountryFilter(countries: readonly string[] | null): Record { + if (countries === null) { + return {}; + } + const countryValues = expandCountryFilterValues(countries); + if (countryValues.length === 0) { + return { ...EMPTY_MATCH_FILTER }; + } + return buildOrFilter([ + { country: { $in: countryValues } }, + { countryCode: { $in: countryValues } }, + ]); +} + +function buildQmCountryFilter( + exchangeLookup: ExchangeSourceLookup, + countries: readonly string[] | null +): Record { + if (countries === null) { + return {}; + } + const countryValues = expandCountryFilterValues(countries); + if (countryValues.length === 0) { + return { ...EMPTY_MATCH_FILTER }; + } + if (typeof exchangeLookup.getCodesForCountries !== 'function') { + return {}; + } + const exchangeCodes = exchangeLookup.getCodesForCountries('qm', countries); + + const clauses: Record[] = [ + { countryCode: { $in: countryValues } }, + { country: { $in: countryValues } }, + ]; + if (exchangeCodes.length > 0) { + clauses.push({ exchange: { $in: exchangeCodes } }); + clauses.push({ exchangeCode: { $in: exchangeCodes } }); + } + return buildOrFilter(clauses); +} + +function buildCeoCountryFilter( + exchangeLookup: ExchangeSourceLookup, + countries: readonly string[] | null +): Record { + if (countries === null) { + return {}; + } + const countryValues = expandCountryFilterValues(countries); + if (countryValues.length === 0) { + return { ...EMPTY_MATCH_FILTER }; + } + if (typeof exchangeLookup.getCodesForCountries !== 'function') { + return {}; + } + const exchangeCodes = exchangeLookup.getCodesForCountries('ceo', countries); + + const clauses: Record[] = [ + { countryCode: { $in: countryValues } }, + { country: { $in: countryValues } }, + ]; + if (exchangeCodes.length > 0) { + clauses.push({ exchange: { $in: exchangeCodes } }); + clauses.push({ exchangeCode: { $in: exchangeCodes } }); + } + return buildOrFilter(clauses); +} + +function buildEodSymbolChangeFilter( + exchangeLookup: ExchangeSourceLookup, + countries: readonly string[] | null +): Record { + if (countries === null) { + return {}; + } + const countryValues = expandCountryFilterValues(countries); + if (countryValues.length === 0) { + return { ...EMPTY_MATCH_FILTER }; + } + if (typeof exchangeLookup.getCodesForCountries !== 'function') { + return {}; + } + const exchangeCodes = exchangeLookup.getCodesForCountries('eod', countries); + + const clauses: Record[] = [ + { country: { $in: countryValues } }, + { Country: { $in: countryValues } }, + ]; + if (exchangeCodes.length > 0) { + clauses.push({ exchange: { $in: exchangeCodes } }); + } + return buildOrFilter(clauses); +} + +function compareStageARecords(a: StageASourceRecord, b: StageASourceRecord): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.isin ?? '', b.isin ?? '') || + compareAscii(a.cusip ?? '', b.cusip ?? '') || + compareAscii(a.country ?? '', b.country ?? '') || + compareAscii(a.currency ?? '', b.currency ?? '') || + compareAscii(a.name ?? '', b.name ?? '') + ); +} + +function compareEodListings(a: StageBEodListingInput, b: StageBEodListingInput): number { + return ( + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.mic ?? '', b.mic ?? '') || + compareAscii(a.role ?? '', b.role ?? '') || + compareAscii(a.ticker ?? '', b.ticker ?? '') || + compareAscii(a.currency ?? '', b.currency ?? '') || + compareAscii(a.span?.firstBarDate ?? '', b.span?.firstBarDate ?? '') || + compareAscii(a.span?.lastBarDate ?? '', b.span?.lastBarDate ?? '') + ); +} + +function compareIbContracts(a: StageBIbContractInput, b: StageBIbContractInput): number { + return ( + compareAscii(a.sourceId, b.sourceId) || + (a.conid === b.conid ? 0 : a.conid < b.conid ? -1 : 1) || + compareAscii(a.currency ?? '', b.currency ?? '') || + compareAscii(a.primaryExchange ?? '', b.primaryExchange ?? '') + ); +} + +function compareTickerSources(a: StageBTickerSourceInput, b: StageBTickerSourceInput): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.mic ?? '', b.mic ?? '') || + compareAscii(a.role ?? '', b.role ?? '') || + compareAscii(a.ticker ?? '', b.ticker ?? '') || + compareAscii(a.currency ?? '', b.currency ?? '') || + compareAscii(a.span?.firstBarDate ?? '', b.span?.firstBarDate ?? '') || + compareAscii(a.span?.lastBarDate ?? '', b.span?.lastBarDate ?? '') + ); +} + +function compareSymbolChanges(a: StageBSymbolChangeInput, b: StageBSymbolChangeInput): number { + return ( + compareAscii(a.eodSourceId, b.eodSourceId) || + compareAscii(a.effectiveDate, b.effectiveDate) || + compareAscii(a.oldTicker, b.oldTicker) || + compareAscii(a.validFrom ?? '', b.validFrom ?? '') + ); +} + +function rawTypeSortKey(rawType: unknown): string { + return typeof rawType === 'string' ? `s:${rawType}` : 'n:null'; +} + +function compareSecurityTypeRecords( + a: SecurityTypeInputRecord, + b: SecurityTypeInputRecord +): number { + return ( + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.isin ?? '', b.isin ?? '') || + compareAscii(rawTypeSortKey(a.rawType), rawTypeSortKey(b.rawType)) + ); +} + +/** + * Pure adapter converting a raw `eodSymbols` document into a Stage A source record + * and Stage B EOD listing input. + */ +export function adaptEodSymbolDoc( + doc: unknown, + context: AdaptEodSymbolContext +): AdaptEodSymbolResult { + if (!isPlainRecord(doc)) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const sourceIdField = readOptionalString(doc, 'eodSearchCode'); + const tickerField = readFirstOptionalString(doc, ['Code', 'code', 'symbol']); + // Resolve listing venue from Exchange/exchange/exchangeCode — never from composite eodExchange="US". + const exchangeField = readFirstOptionalString(doc, ['Exchange', 'exchange', 'exchangeCode']); + const countryField = readFirstOptionalString(doc, ['Country', 'countryCode']); + const currencyField = readFirstOptionalString(doc, ['Currency', 'currency']); + const isinField = readFirstOptionalString(doc, ['Isin', 'isin']); + const cusipField = readFirstOptionalString(doc, ['Cusip', 'cusip']); + const nameField = readFirstOptionalString(doc, ['Name', 'name', 'companyName']); + + if ( + !sourceIdField.ok || + !tickerField.ok || + !exchangeField.ok || + !countryField.ok || + !currencyField.ok || + !isinField.ok || + !cusipField.ok || + !nameField.ok + ) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + if (sourceIdField.value === null) { + return { ok: false, skipReason: 'missingId' }; + } + + const sourceId = sourceIdField.value; + const rawExchange = exchangeField.value; + const exchangeEntry = + rawExchange !== null ? context.exchangeLookup.get('eod', rawExchange) : undefined; + + if (context.allowedCountries !== null) { + if (countryField.value !== null) { + const normalizedCountry = normalizeCountryIso2(countryField.value); + if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) { + if (!context.allowedCountries.has(exchangeEntry.countryIso)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } + } + + if (rawExchange !== null && rawExchange.toUpperCase() === 'NMFQS') { + return { ok: false, skipReason: 'excludedMutualFund' }; + } + if (exchangeEntry?.role === 'excluded_fund') { + return { ok: false, skipReason: 'excludedMutualFund' }; + } + + if (rawExchange === null || exchangeEntry === undefined) { + return { ok: false, skipReason: 'unmappedExchange' }; + } + + const normalized = normalizeProviderSymbol({ + Code: tickerField.value, + Exchange: rawExchange, + Name: nameField.value, + Country: countryField.value, + Currency: currencyField.value, + eodSearchCode: sourceId, + }); + + let invalidIdentifiersNulled = 0; + let validIsin: string | null = null; + if (isinField.value !== null) { + const candidate = isinField.value.toUpperCase(); + if (isValidIsin(candidate)) { + validIsin = candidate; + } else { + invalidIdentifiersNulled += 1; + } + } + + let validCusip: string | null = null; + if (cusipField.value !== null) { + const candidate = cusipField.value.toUpperCase(); + if (isValidCusip(candidate)) { + validCusip = candidate; + } else { + invalidIdentifiersNulled += 1; + } + } + + // Per T-55: Stage A country must be issuer country (from ISIN prefix), never listing Country. + let issuerCountry: string | null = null; + if (validIsin !== null) { + issuerCountry = validIsin.slice(0, 2); + } else if (validCusip !== null && isinField.value !== null && isinField.value.length >= 2) { + const rawPrefix = isinField.value.slice(0, 2).toUpperCase(); + if (isNorthAmericaIso(rawPrefix)) { + issuerCountry = rawPrefix; + } + } + + const rawCurrency = normalized?.currency ?? currencyField.value; + const currency = + rawCurrency !== null + ? rawCurrency.toUpperCase() + : exchangeEntry.mic !== null + ? context.micCurrencyMap.get(exchangeEntry.mic) ?? null + : null; + + const name = normalized?.companyName ?? nameField.value; + const ticker = normalized?.symbol ?? tickerField.value; + const span = toSpanDateRange(context.barSpans?.get('eod', sourceId)); + const rawType = readRawSecurityType(doc); + const resolvedIsin = + validIsin !== null + ? validIsin + : validCusip !== null && isNorthAmericaIso(issuerCountry) + ? cusipToIsin(validCusip, issuerCountry) + : null; + + return { + ok: true, + stageARecord: { + source: 'eod', + sourceId, + isin: validIsin, + cusip: validCusip, + country: issuerCountry, + currency, + name, + }, + eodListing: { + sourceId, + ticker, + mic: exchangeEntry.mic, + role: exchangeEntry.role, + currency, + span, + }, + rawType, + resolvedIsin, + invalidIdentifiersNulled, + }; +} + +/** + * Pure adapter converting a raw `ibSymbols` document into a Stage A source record + * and Stage B IB contract input. Never blocks on `exchangeId` or treats ATS venues + * (e.g. `AEQLIT`, `OTCLNKECN`) as listing MICs or primary exchanges. + */ +export function adaptIbSymbolDoc( + doc: unknown, + context: AdaptIbSymbolContext +): AdaptIbSymbolResult { + if (!isPlainRecord(doc)) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const rawConid = doc.conid; + if (rawConid === undefined || rawConid === null) { + return { ok: false, skipReason: 'missingId' }; + } + if (typeof rawConid !== 'number') { + return { ok: false, skipReason: 'invalidFieldType' }; + } + if (!Number.isSafeInteger(rawConid) || rawConid <= 0) { + return { ok: false, skipReason: 'invalidIdentifier' }; + } + + const symbolField = readFirstOptionalString(doc, ['symbol', 'localSymbol']); + const exchangeIdField = readFirstOptionalString(doc, ['exchangeId', 'exchange', 'exchangeCode']); + const explicitPrimaryExchangeField = readFirstOptionalString(doc, [ + 'primaryExchange', + 'listingExchange', + ]); + const countryField = readFirstOptionalString(doc, ['country', 'countryCode']); + const currencyField = readOptionalString(doc, 'currency'); + const isinField = readOptionalString(doc, 'isin'); + const cusipField = readOptionalString(doc, 'cusip'); + const nameField = readFirstOptionalString(doc, ['companyName', 'name', 'description']); + + if ( + !symbolField.ok || + !exchangeIdField.ok || + !explicitPrimaryExchangeField.ok || + !countryField.ok || + !currencyField.ok || + !isinField.ok || + !cusipField.ok || + !nameField.ok + ) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const normalizedDocCountry = + countryField.value !== null ? normalizeCountryIso2(countryField.value) : null; + if (context.allowedCountries !== null) { + if (normalizedDocCountry === null || !context.allowedCountries.has(normalizedDocCountry)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } + + const normalized = normalizeProviderSymbol({ + symbol: symbolField.value, + exchangeId: exchangeIdField.value, + description: nameField.value, + countryCode: countryField.value, + currency: currencyField.value, + }); + + let invalidIdentifiersNulled = 0; + let validIsin: string | null = null; + if (isinField.value !== null) { + const candidate = isinField.value.toUpperCase(); + if (isValidIsin(candidate)) { + validIsin = candidate; + } else { + invalidIdentifiersNulled += 1; + } + } + + let validCusip: string | null = null; + if (cusipField.value !== null) { + const candidate = cusipField.value.toUpperCase(); + if (isValidCusip(candidate)) { + validCusip = candidate; + } else { + invalidIdentifiersNulled += 1; + } + } + + // Derive Stage A issuer country without leaking listing country when valid ISIN is present. + let issuerCountry: string | null = null; + if (validIsin !== null) { + issuerCountry = validIsin.slice(0, 2); + } else if (validCusip !== null) { + const rawPrefix = + isinField.value !== null && isinField.value.length >= 2 + ? isinField.value.slice(0, 2).toUpperCase() + : null; + if (isNorthAmericaIso(rawPrefix)) { + issuerCountry = rawPrefix; + } else if (isNorthAmericaIso(normalizedDocCountry)) { + issuerCountry = normalizedDocCountry; + } + } + + let primaryExchange: string | null = null; + if (explicitPrimaryExchangeField.value !== null) { + primaryExchange = explicitPrimaryExchangeField.value.toUpperCase(); + } else if (exchangeIdField.value !== null) { + const entry = context.exchangeLookup.get('ib', exchangeIdField.value); + if (entry?.role === 'primary_venue') { + primaryExchange = exchangeIdField.value.toUpperCase(); + } + } + + const sourceId = String(rawConid); + const currency = currencyField.value !== null ? currencyField.value.toUpperCase() : null; + const name = normalized?.companyName ?? nameField.value; + + return { + ok: true, + stageARecord: { + source: 'ib', + sourceId, + isin: validIsin, + cusip: validCusip, + country: issuerCountry, + currency, + name, + }, + ibContract: { + sourceId, + conid: rawConid, + currency, + primaryExchange, + }, + invalidIdentifiersNulled, + }; +} + +/** + * Pure adapter converting a raw `qmSymbols` document into a Stage B ticker-source input. + * Preserves inactive (`active: false`) records and duplicate `(symbol, exchange)` pairs + * (such as `VOY:CNX` and `VOY:CC`) as distinct `qmSearchCode` `sourceId`s. + */ +export function adaptQmSymbolDoc( + doc: unknown, + context: AdaptQmSymbolContext +): AdaptTickerSourceResult { + if (!isPlainRecord(doc)) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const sourceIdField = readOptionalString(doc, 'qmSearchCode'); + const symbolField = readFirstOptionalString(doc, ['symbol', 'code']); + const exchangeField = readFirstOptionalString(doc, ['exchange', 'exchangeCode']); + const countryField = readFirstOptionalString(doc, ['countryCode', 'country']); + const currencyField = readOptionalString(doc, 'currency'); + + if ( + !sourceIdField.ok || + !symbolField.ok || + !exchangeField.ok || + !countryField.ok || + !currencyField.ok + ) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + if (sourceIdField.value === null) { + return { ok: false, skipReason: 'missingId' }; + } + + const sourceId = sourceIdField.value; + const rawExchange = exchangeField.value; + const exchangeEntry = + rawExchange !== null ? context.exchangeLookup.get('qm', rawExchange) : undefined; + + const normalizedCountry = + countryField.value !== null ? normalizeCountryIso2(countryField.value) : null; + + if (context.allowedCountries !== null) { + if (countryField.value !== null) { + if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) { + if (!context.allowedCountries.has(exchangeEntry.countryIso)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } + } + + if (exchangeEntry?.role === 'excluded_fund') { + return { ok: false, skipReason: 'excludedMutualFund' }; + } + + if (rawExchange === null || exchangeEntry === undefined) { + return { ok: false, skipReason: 'unmappedExchange' }; + } + + const parsedTicker = parseTickerDetailed(symbolField.value, 'qm'); + const ticker = parsedTicker.ok + ? formatCanonicalTicker(parsedTicker.tickerRoot, parsedTicker.classSuffix) + : symbolField.value; + + const effectiveCountry = normalizedCountry ?? exchangeEntry.countryIso; + const currency = + currencyField.value !== null + ? currencyField.value.toUpperCase() + : exchangeEntry.mic !== null + ? context.micCurrencyMap.get(exchangeEntry.mic) ?? countryFallbackCurrency(effectiveCountry) + : countryFallbackCurrency(effectiveCountry); + + const span = toSpanDateRange(context.barSpans?.get('qm', sourceId)); + + return { + ok: true, + tickerSource: { + source: 'qm', + sourceId, + ticker, + mic: exchangeEntry.mic, + role: exchangeEntry.role, + currency, + span, + }, + }; +} + +/** + * Pure adapter converting a raw `ceoSymbols` document into a Stage B ticker-source input. + * Maps `TSX`/`CDX`/`CNQ`/`AQL` through `exchangeLookup` and parses embedded `.TO`/`.V` suffixes. + */ +export function adaptCeoSymbolDoc( + doc: unknown, + context: AdaptCeoSymbolContext +): AdaptTickerSourceResult { + if (!isPlainRecord(doc)) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const sourceIdField = readOptionalString(doc, 'ceoId'); + const symbolField = readOptionalString(doc, 'symbol'); + const exchangeField = readFirstOptionalString(doc, ['exchange', 'exchangeCode']); + const countryField = readFirstOptionalString(doc, ['countryCode', 'country']); + const currencyField = readOptionalString(doc, 'currency'); + + const rawLastSeen = doc.lastSeen; + const lastSeenTypeValid = + rawLastSeen === undefined || + rawLastSeen === null || + typeof rawLastSeen === 'string' || + rawLastSeen instanceof Date; + + if ( + !sourceIdField.ok || + !symbolField.ok || + !exchangeField.ok || + !countryField.ok || + !currencyField.ok || + !lastSeenTypeValid + ) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + if (sourceIdField.value === null) { + return { ok: false, skipReason: 'missingId' }; + } + + const sourceId = sourceIdField.value; + const rawExchange = exchangeField.value; + const exchangeEntry = + rawExchange !== null ? context.exchangeLookup.get('ceo', rawExchange) : undefined; + + const normalizedCountry = + countryField.value !== null ? normalizeCountryIso2(countryField.value) : null; + + if (context.allowedCountries !== null) { + if (countryField.value !== null) { + if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) { + if (!context.allowedCountries.has(exchangeEntry.countryIso)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } + } + + if (exchangeEntry?.role === 'excluded_fund') { + return { ok: false, skipReason: 'excludedMutualFund' }; + } + + if (rawExchange === null || exchangeEntry === undefined) { + return { ok: false, skipReason: 'unmappedExchange' }; + } + + const parsedTicker = parseTickerDetailed(symbolField.value, 'ceo'); + const ticker = parsedTicker.ok + ? formatStageBSafeCeoTicker(parsedTicker.tickerRoot, parsedTicker.classSuffix) + : symbolField.value; + + const currency = + currencyField.value !== null + ? currencyField.value.toUpperCase() + : exchangeEntry.mic !== null + ? context.micCurrencyMap.get(exchangeEntry.mic) ?? 'CAD' + : 'CAD'; + + let span = toSpanDateRange(context.ceoSpans?.get(sourceId)); + if (span === null && rawLastSeen !== undefined && rawLastSeen !== null) { + const lastSeenDate = normalizeBarDate(rawLastSeen); + if (lastSeenDate !== null) { + span = { firstBarDate: lastSeenDate, lastBarDate: lastSeenDate }; + } + } + + return { + ok: true, + tickerSource: { + source: 'ceo', + sourceId, + ticker, + mic: exchangeEntry.mic, + role: exchangeEntry.role, + currency, + span, + }, + }; +} + +/** + * Pure adapter converting a raw `eodSymbolChange` document into a validated + * Stage B symbol-change input that will never throw in `matchListingsStageB`. + */ +export function adaptEodSymbolChangeDoc( + doc: unknown, + context: AdaptEodSymbolChangeContext +): AdaptEodSymbolChangeResult { + if (!isPlainRecord(doc)) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const oldSymbolField = readOptionalString(doc, 'oldSymbol'); + const newSymbolField = readOptionalString(doc, 'newSymbol'); + const exchangeField = readOptionalString(doc, 'exchange'); + const eodExchangeField = readOptionalString(doc, 'eodExchange'); + const eodSearchCodeField = readOptionalString(doc, 'eodSearchCode'); + const countryField = readFirstOptionalString(doc, ['country', 'Country']); + + const isValidDateField = (value: unknown): boolean => + value === undefined || value === null || typeof value === 'string' || value instanceof Date; + + const dateTypeValid = + isValidDateField(doc.effective) && + isValidDateField(doc.effectiveDate) && + isValidDateField(doc.date); + const rawDate = + doc.effective !== undefined && doc.effective !== null + ? doc.effective + : doc.effectiveDate !== undefined && doc.effectiveDate !== null + ? doc.effectiveDate + : doc.date; + + const rawValidFrom = doc.validFrom; + const validFromTypeValid = isValidDateField(rawValidFrom); + + if ( + !oldSymbolField.ok || + !newSymbolField.ok || + !exchangeField.ok || + !eodExchangeField.ok || + !eodSearchCodeField.ok || + !countryField.ok || + !dateTypeValid || + !validFromTypeValid + ) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + if ( + oldSymbolField.value === null || + newSymbolField.value === null || + exchangeField.value === null + ) { + return { ok: false, skipReason: 'missingId' }; + } + + const exchange = exchangeField.value; + const exchangeEntry = context.exchangeLookup.get('eod', exchange); + + if (context.allowedCountries !== null) { + if (countryField.value !== null) { + const normalizedCountry = normalizeCountryIso2(countryField.value); + if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) { + if (!context.allowedCountries.has(exchangeEntry.countryIso)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } + } + + if (exchange.toUpperCase() === 'NMFQS' || exchangeEntry?.role === 'excluded_fund') { + return { ok: false, skipReason: 'excludedMutualFund' }; + } + + if (exchangeEntry === undefined) { + return { ok: false, skipReason: 'unmappedExchange' }; + } + + const parsedOld = parseTickerDetailed(oldSymbolField.value, 'eod'); + if (!parsedOld.ok || parsedOld.tickerRoot.length > MAX_TICKER_ROOT_LENGTH) { + return { ok: false, skipReason: 'invalidIdentifier' }; + } + + const effectiveDate = normalizeBarDate(rawDate); + if (effectiveDate === null || effectiveDate <= '0001-01-01') { + return { ok: false, skipReason: 'invalidIdentifier' }; + } + + let validFrom: string | null = null; + if (rawValidFrom !== undefined && rawValidFrom !== null) { + const normalizedValidFrom = normalizeBarDate(rawValidFrom); + if (normalizedValidFrom === null || normalizedValidFrom >= effectiveDate) { + return { ok: false, skipReason: 'invalidIdentifier' }; + } + validFrom = normalizedValidFrom; + } + + const eodSourceId = + eodSearchCodeField.value ?? + `${newSymbolField.value}.${ + eodExchangeField.value ?? (exchangeEntry.countryIso === 'US' ? 'US' : exchange) + }`; + + const symbolChange: StageBSymbolChangeInput = + validFrom !== null + ? { + eodSourceId, + oldTicker: formatCanonicalTicker(parsedOld.tickerRoot, parsedOld.classSuffix), + effectiveDate, + validFrom, + } + : { + eodSourceId, + oldTicker: formatCanonicalTicker(parsedOld.tickerRoot, parsedOld.classSuffix), + effectiveDate, + }; + + return { ok: true, symbolChange }; +} + +/** Streams and adapts `eodSymbols` from a read-only MongoDB reader. */ +export async function readEodSymbols( + reader: ReadOnlySourceSymbolReader, + options: ReadSourceCollectionOptions +): Promise { + const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries); + const micCurrencyMap = buildMicCurrencyMap(options.knownExchanges); + const context: AdaptEodSymbolContext = { + exchangeLookup: options.exchangeLookup, + barSpans: options.barSpans, + allowedCountries, + micCurrencyMap, + }; + + const stageARecords: StageASourceRecord[] = []; + const eodListings: StageBEodListingInput[] = []; + const securityTypeRecords: SecurityTypeInputRecord[] = []; + const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.eod); + + const findOptions: SourceSymbolFindOptions = { + projection: { ...EOD_SYMBOLS_PROJECTION }, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }; + + await streamCollection( + reader, + SOURCE_SYMBOL_COLLECTIONS.eod, + buildEodCountryFilter(options.exchangeLookup, countryList), + findOptions, + doc => { + stats.docsRead += 1; + const adapted = adaptEodSymbolDoc(doc, context); + if (!adapted.ok) { + stats.skips[adapted.skipReason] += 1; + return; + } + stageARecords.push(adapted.stageARecord); + eodListings.push(adapted.eodListing); + securityTypeRecords.push({ + isin: adapted.resolvedIsin, + rawType: adapted.rawType, + sourceId: adapted.stageARecord.sourceId, + }); + stats.emitted += 1; + stats.invalidIdentifiersNulled += adapted.invalidIdentifiersNulled; + } + ); + + stageARecords.sort(compareStageARecords); + eodListings.sort(compareEodListings); + securityTypeRecords.sort(compareSecurityTypeRecords); + + // Compute vocabulary diagnostics across every emitted EOD row, while building the loader-facing + // `securityTypeByIsin` map and its conflicts strictly from EOD rows accepted as Stage A + // instrument members so quarantined rows (e.g. isin_cusip_mismatch, duplicate_source_id) + // cannot supply or veto a valid instrument's type. + const securityTypeOptions = + options.maxSecurityTypeConflicts !== undefined + ? { maxConflicts: options.maxSecurityTypeConflicts } + : undefined; + const allSecurityTypeResult = buildSecurityTypeByIsin(securityTypeRecords, securityTypeOptions); + const eodStageA = matchInstrumentsStageA(stageARecords); + const loaderSecurityTypeResult = buildSecurityTypeByIsinForStageA( + securityTypeRecords, + eodStageA.instruments, + securityTypeOptions + ); + + return { + stageARecords, + eodListings, + securityTypeRecords, + securityTypeByIsin: loaderSecurityTypeResult.securityTypeByIsin, + securityTypeStats: allSecurityTypeResult.stats, + securityTypeLoaderStats: loaderSecurityTypeResult.stats, + unknownSecurityTypes: allSecurityTypeResult.unknownRawTypes, + securityTypeConflicts: loaderSecurityTypeResult.conflicts, + stats, + }; +} + +/** Streams and adapts `ibSymbols` from a read-only MongoDB reader. */ +export async function readIbSymbols( + reader: ReadOnlySourceSymbolReader, + options: ReadSourceCollectionOptions +): Promise { + const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries); + const context: AdaptIbSymbolContext = { + exchangeLookup: options.exchangeLookup, + allowedCountries, + }; + + const stageARecords: StageASourceRecord[] = []; + const ibContracts: StageBIbContractInput[] = []; + const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.ib); + + const findOptions: SourceSymbolFindOptions = { + projection: { ...IB_SYMBOLS_PROJECTION }, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }; + + await streamCollection( + reader, + SOURCE_SYMBOL_COLLECTIONS.ib, + buildIbCountryFilter(countryList), + findOptions, + doc => { + stats.docsRead += 1; + const adapted = adaptIbSymbolDoc(doc, context); + if (!adapted.ok) { + stats.skips[adapted.skipReason] += 1; + return; + } + stageARecords.push(adapted.stageARecord); + ibContracts.push(adapted.ibContract); + stats.emitted += 1; + stats.invalidIdentifiersNulled += adapted.invalidIdentifiersNulled; + } + ); + + stageARecords.sort(compareStageARecords); + ibContracts.sort(compareIbContracts); + + return { stageARecords, ibContracts, stats }; +} + +/** Streams and adapts `qmSymbols` from a read-only MongoDB reader. */ +export async function readQmSymbols( + reader: ReadOnlySourceSymbolReader, + options: ReadSourceCollectionOptions +): Promise { + const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries); + const micCurrencyMap = buildMicCurrencyMap(options.knownExchanges); + const context: AdaptQmSymbolContext = { + exchangeLookup: options.exchangeLookup, + barSpans: options.barSpans, + allowedCountries, + micCurrencyMap, + }; + + const tickerSources: StageBTickerSourceInput[] = []; + const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.qm); + + const findOptions: SourceSymbolFindOptions = { + projection: { ...QM_SYMBOLS_PROJECTION }, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }; + + await streamCollection( + reader, + SOURCE_SYMBOL_COLLECTIONS.qm, + buildQmCountryFilter(options.exchangeLookup, countryList), + findOptions, + doc => { + stats.docsRead += 1; + const adapted = adaptQmSymbolDoc(doc, context); + if (!adapted.ok) { + stats.skips[adapted.skipReason] += 1; + return; + } + tickerSources.push(adapted.tickerSource); + stats.emitted += 1; + } + ); + + tickerSources.sort(compareTickerSources); + + return { tickerSources, stats }; +} + +/** Streams and adapts `ceoSymbols` from a read-only MongoDB reader. */ +export async function readCeoSymbols( + reader: ReadOnlySourceSymbolReader, + options: ReadSourceCollectionOptions +): Promise { + const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries); + const micCurrencyMap = buildMicCurrencyMap(options.knownExchanges); + const context: AdaptCeoSymbolContext = { + exchangeLookup: options.exchangeLookup, + ceoSpans: options.ceoSpans, + allowedCountries, + micCurrencyMap, + }; + + const tickerSources: StageBTickerSourceInput[] = []; + const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.ceo); + + const findOptions: SourceSymbolFindOptions = { + projection: { ...CEO_SYMBOLS_PROJECTION }, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }; + + await streamCollection( + reader, + SOURCE_SYMBOL_COLLECTIONS.ceo, + buildCeoCountryFilter(options.exchangeLookup, countryList), + findOptions, + doc => { + stats.docsRead += 1; + const adapted = adaptCeoSymbolDoc(doc, context); + if (!adapted.ok) { + stats.skips[adapted.skipReason] += 1; + return; + } + tickerSources.push(adapted.tickerSource); + stats.emitted += 1; + } + ); + + tickerSources.sort(compareTickerSources); + + return { tickerSources, stats }; +} + +/** Streams and adapts `eodSymbolChange` from a read-only MongoDB reader. */ +export async function readEodSymbolChanges( + reader: ReadOnlySourceSymbolReader, + options: ReadSourceCollectionOptions +): Promise { + const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries); + const context: AdaptEodSymbolChangeContext = { + exchangeLookup: options.exchangeLookup, + allowedCountries, + }; + + const symbolChanges: StageBSymbolChangeInput[] = []; + const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.eodSymbolChange); + + const findOptions: SourceSymbolFindOptions = { + projection: { ...EOD_SYMBOL_CHANGE_PROJECTION }, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }; + + await streamCollection( + reader, + SOURCE_SYMBOL_COLLECTIONS.eodSymbolChange, + buildEodSymbolChangeFilter(options.exchangeLookup, countryList), + findOptions, + doc => { + stats.docsRead += 1; + const adapted = adaptEodSymbolChangeDoc(doc, context); + if (!adapted.ok) { + stats.skips[adapted.skipReason] += 1; + return; + } + symbolChanges.push(adapted.symbolChange); + stats.emitted += 1; + } + ); + + symbolChanges.sort(compareSymbolChanges); + + return { symbolChanges, stats }; +} + +/** + * Aggregate read-only entry point reading `eodSymbols`, `ibSymbols`, `qmSymbols`, + * `ceoSymbols`, and `eodSymbolChange` into deterministic Stage A and Stage B inputs. + */ +export async function readSecurityMasterSources( + reader: ReadOnlySourceSymbolReader, + options: ReadSecurityMasterSourcesOptions +): Promise { + assertReadOnlyReader(reader); + + const eodResult = await readEodSymbols(reader, options); + const ibResult = await readIbSymbols(reader, options); + const qmResult = await readQmSymbols(reader, options); + const ceoResult = await readCeoSymbols(reader, options); + const symbolChangeResult = await readEodSymbolChanges(reader, options); + + const stageARecords: StageASourceRecord[] = [ + ...eodResult.stageARecords, + ...ibResult.stageARecords, + ]; + stageARecords.sort(compareStageARecords); + + const tickerSources: StageBTickerSourceInput[] = [ + ...qmResult.tickerSources, + ...ceoResult.tickerSources, + ]; + tickerSources.sort(compareTickerSources); + + return { + stageARecords, + stageBInput: { + eodListings: eodResult.eodListings, + ibContracts: ibResult.ibContracts, + tickerSources, + symbolChanges: symbolChangeResult.symbolChanges, + }, + securityTypeRecords: eodResult.securityTypeRecords, + securityTypeByIsin: eodResult.securityTypeByIsin, + securityTypeStats: eodResult.securityTypeStats, + securityTypeLoaderStats: eodResult.securityTypeLoaderStats, + unknownSecurityTypes: eodResult.unknownSecurityTypes, + securityTypeConflicts: eodResult.securityTypeConflicts, + stats: { + eodSymbols: eodResult.stats, + ibSymbols: ibResult.stats, + qmSymbols: qmResult.stats, + ceoSymbols: ceoResult.stats, + eodSymbolChange: symbolChangeResult.stats, + }, + }; +} diff --git a/libs/calculations/README.md b/libs/calculations/README.md index d4a28db7..3005977d 100644 --- a/libs/calculations/README.md +++ b/libs/calculations/README.md @@ -52,6 +52,55 @@ const risk = returnStatistics(returns); and downside deviation uses full-series RMS. Trade holding periods are minutes. Persisted strategy versions and execution/checkpoint behavior are unchanged. The legacy Kelly/leverage fields in `performanceAnalysis` remain compatibility heuristics, not optimizers. + Canonical Deflated Sharpe Ratio (`deflatedSharpeRatio`, `effectiveIndependentTrials`, + `trialMoments`, `normalCdf`, `inverseNormalCdf`, `passesDsrGate`, `DSR_VALIDATION_GATE`) + and cross-sectional Signal Analysis (`analyzeSignalPanel`, `crossSectionIc`, + `neweyWestMeanTest`, `defaultNeweyWestLag`, `summarizeIcSeries`, `evaluateRecencyGate`, + `SignalAnalysisError`, `DEFAULT_MIN_CROSS_SECTION`, `DEFAULT_QUANTILE_COUNT`, + `RECENCY_SPLIT_DATE`, `RECENCY_MIN_RATIO`), plus pure Event-Study math (`eventDayIndex`, + `eventStudy`, `EventStudyError`, `DEFAULT_EVENT_PRE_DAYS`, `DEFAULT_EVENT_POST_DAYS`, + `DEFAULT_EVENT_MIN_EVENTS`) with date-clustered Newey-West significance, R-7 CAR + percentile fans, and a sign-preserving post-2023 recency gate, are exported from both + `./analytics` and the root entry. + +## Benchmark + +Run the fixed-seed DSR + effective-trials benchmark (`K = 500` trials × `2,520` daily +observations, `124,750` pairs): + +```sh +bun run libs/calculations/scripts/benchmark-deflated-sharpe.ts +``` + +Observed locally on Bun 1.2.16 (2 runs, seed `20260401`): `150.18 ms` (`830,660 pairs/s`) +and `159.79 ms` (`780,707 pairs/s`), `meanCorrelation = 0.071187`, `nHat = 464.4776`. + +Run the fixed-seed Signal Analysis benchmark (`5,040` dates × `3,000` names, +`15,120,000` observations, covering full `analyzeSignalPanel` with IC, Newey-West HAC, +quintile spreads, turnover, and recency gate): + +```sh +bun run libs/calculations/scripts/benchmark-signal-analysis.ts +``` + +Observed locally on Bun 1.2.16 (2 runs, seed `20260402`): `1,779.96 ms` +(`2,832 dates/s`, `8,494,557 observations/s`) and `1,809.95 ms` (`2,785 dates/s`, +`8,353,819 observations/s`), `meanRankIc = 0.057294`, `rankIcTStat = 218.5078`, +`spreadMean = 0.003369`, `recencyGatePassed = true`. + +Run the fixed-seed Event Study benchmark (`2,000` entities × `5,040` sessions, +`200,000` events, window `-10..+20`, covering full `eventStudy` with benchmark-adjusted +AAR/CAAR, R-7 CAR percentile fans, date-clustered Newey-West HAC, and recency gate): + +```sh +bun run test:calculations +``` + +Observed locally on Bun 1.2.16 (2026-11-28, seed `20260404`): + +```text +[event-study benchmark] events=200000 window=-10..+20 elapsedMs=608.09 events/s=328896 +``` The root entry exports the supported returns, indicators and market-data helpers. Use subpaths to avoid loading unrelated math. Shared domain types remain owned by diff --git a/libs/calculations/scripts/benchmark-deflated-sharpe.ts b/libs/calculations/scripts/benchmark-deflated-sharpe.ts new file mode 100644 index 00000000..20918fa9 --- /dev/null +++ b/libs/calculations/scripts/benchmark-deflated-sharpe.ts @@ -0,0 +1,111 @@ +import { + deflatedSharpeRatio, + effectiveIndependentTrials, + trialMoments, +} from '../src/analytics/deflated-sharpe'; + +const SEED = 20260401; +const K = 500; +const N_OBS = 2520; + +function createMulberry32(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) / 4294967296; + }; +} + +function createStandardNormal(seed: number): () => number { + const nextUniform = createMulberry32(seed); + let spare: number | null = null; + return () => { + if (spare !== null) { + const value = spare; + spare = null; + return value; + } + let u1 = nextUniform(); + while (u1 <= 1e-12) { + u1 = nextUniform(); + } + const u2 = nextUniform(); + const radius = Math.sqrt(-2 * Math.log(u1)); + const theta = 2 * Math.PI * u2; + spare = radius * Math.sin(theta); + return radius * Math.cos(theta); + }; +} + +// Generate K=500 synthetic daily return series of length T=2,520 with a mild common factor +// so pairwise correlations are realistic and non-degenerate. +const randn = createStandardNormal(SEED); +const marketFactor = new Float64Array(N_OBS); +for (let t = 0; t < N_OBS; t++) { + marketFactor[t] = 0.0003 + 0.01 * randn(); +} + +const seriesList: number[][] = new Array(K); +for (let i = 0; i < K; i++) { + const beta = 0.25 + (i % 10) * 0.02; + const alpha = ((i % 25) - 12) * 0.00004; + const series: number[] = new Array(N_OBS); + for (let t = 0; t < N_OBS; t++) { + series[t] = alpha + beta * (marketFactor[t] as number) + 0.012 * randn(); + } + seriesList[i] = series; +} + +const started = performance.now(); + +const momentsList = new Array(K); +const clusterSharpes: number[] = new Array(K); +for (let i = 0; i < K; i++) { + const m = trialMoments(seriesList[i] as number[]); + if (m === null) { + throw new Error(`Unexpected null trialMoments at trial ${i}`); + } + momentsList[i] = m; + clusterSharpes[i] = m.sharpeUnann; +} + +const eff = effectiveIndependentTrials(seriesList); + +let passedCount = 0; +for (let i = 0; i < K; i++) { + const m = momentsList[i]; + const res = deflatedSharpeRatio({ + sharpeUnann: m.sharpeUnann, + nObs: m.nObs, + skewness: m.skewness, + kurtosis: m.kurtosis, + nHat: eff.nHat, + clusterSharpes, + }); + if (res !== null && res.dsr >= 0.95) { + passedCount++; + } +} + +const elapsedMs = performance.now() - started; +const pairsPerSec = eff.pairsUsed / (elapsedMs / 1000); + +console.log( + JSON.stringify( + { + seed: SEED, + k: K, + nObs: N_OBS, + pairsUsed: eff.pairsUsed, + meanCorrelation: Number((eff.meanCorrelation ?? 0).toFixed(6)), + nHat: Number(eff.nHat.toFixed(4)), + passedDsrGate: passedCount, + elapsedMs: Number(elapsedMs.toFixed(2)), + pairsPerSec: Math.round(pairsPerSec), + }, + null, + 2 + ) +); diff --git a/libs/calculations/scripts/benchmark-signal-analysis.ts b/libs/calculations/scripts/benchmark-signal-analysis.ts new file mode 100644 index 00000000..37524b31 --- /dev/null +++ b/libs/calculations/scripts/benchmark-signal-analysis.ts @@ -0,0 +1,132 @@ +import { analyzeSignalPanel, type SignalCrossSection } from '../src/analytics/signal-analysis'; + +const SEED = 20260402; +const DATES = 5040; +const NAMES_PER_DATE = 3000; + +function createMulberry32(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) / 4294967296; + }; +} + +function createStandardNormal(seed: number): () => number { + const nextUniform = createMulberry32(seed); + let spare: number | null = null; + return () => { + if (spare !== null) { + const value = spare; + spare = null; + return value; + } + let u1 = nextUniform(); + while (u1 <= 1e-12) { + u1 = nextUniform(); + } + const u2 = nextUniform(); + const radius = Math.sqrt(-2 * Math.log(u1)); + const theta = 2 * Math.PI * u2; + spare = radius * Math.sin(theta); + return radius * Math.cos(theta); + }; +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function generateBusinessDates(count: number, startYear: number): string[] { + const dates: string[] = new Array(count); + let year = startYear; + let month = 1; + let day = 1; + // 2006-01-01 was a Sunday (dow = 0) + let dow = 0; + let produced = 0; + + while (produced < count) { + if (dow !== 0 && dow !== 6) { + const yyyy = String(year).padStart(4, '0'); + const mm = String(month).padStart(2, '0'); + const dd = String(day).padStart(2, '0'); + dates[produced++] = `${yyyy}-${mm}-${dd}`; + } + + dow = (dow + 1) % 7; + day++; + const baseDays = DAYS_IN_MONTH[month] ?? 31; + const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays; + if (day > maxDay) { + day = 1; + month++; + if (month > 12) { + month = 1; + year++; + } + } + } + + return dates; +} + +const randn = createStandardNormal(SEED); +const isoDates = generateBusinessDates(DATES, 2006); +const sharedIds = new Int32Array(NAMES_PER_DATE); +for (let i = 0; i < NAMES_PER_DATE; i++) { + sharedIds[i] = i + 1; +} + +const panel: SignalCrossSection[] = new Array(DATES); +for (let t = 0; t < DATES; t++) { + const signal = new Float64Array(NAMES_PER_DATE); + const forwardReturn = new Float64Array(NAMES_PER_DATE); + for (let i = 0; i < NAMES_PER_DATE; i++) { + const s = randn(); + signal[i] = s; + forwardReturn[i] = 0.0004 + 0.0012 * s + 0.02 * randn(); + } + panel[t] = { + date: isoDates[t] as string, + ids: sharedIds, + signal, + forwardReturn, + }; +} + +const started = performance.now(); +const result = analyzeSignalPanel(panel); +const elapsedMs = performance.now() - started; + +const totalObservations = DATES * NAMES_PER_DATE; +const elapsedSec = elapsedMs / 1000; +const datesPerSec = DATES / elapsedSec; +const observationsPerSec = totalObservations / elapsedSec; + +console.log( + JSON.stringify( + { + seed: SEED, + dates: DATES, + namesPerDate: NAMES_PER_DATE, + totalObservations, + elapsedMs: Number(elapsedMs.toFixed(2)), + datesPerSec: Math.round(datesPerSec), + observationsPerSec: Math.round(observationsPerSec), + meanRankIc: Number((result.rankIc.mean ?? 0).toFixed(6)), + rankIcTStat: + result.rankIc.neweyWest.status === 'ok' + ? Number(result.rankIc.neweyWest.tStat.toFixed(4)) + : null, + spreadMean: Number((result.quantiles.spreadSummary.mean ?? 0).toFixed(6)), + recencyGatePassed: result.recency.gate.pass, + }, + null, + 2 + ) +); diff --git a/libs/calculations/src/analytics/deflated-sharpe.ts b/libs/calculations/src/analytics/deflated-sharpe.ts new file mode 100644 index 00000000..4b488bc0 --- /dev/null +++ b/libs/calculations/src/analytics/deflated-sharpe.ts @@ -0,0 +1,662 @@ +import { mean, sampleDeviation } from './return-statistics'; + +/** + * Canonical Deflated Sharpe Ratio (DSR) and effective independent trials (N-hat) + * math per `design/VALIDATION-AND-RIGOR.md` §2.B and §2.C (Bailey & López de Prado). + * + * Pure stateless math: zero I/O, zero wall-clock or random calls, never throws on + * degenerate numeric input (returns `null` when a statistic is undefined). + * + * Local benchmark (fixed seed `20260401`, `K = 500` trials x `2,520` daily observations, + * `124,750` pairs, covering `trialMoments` + `effectiveIndependentTrials` + `deflatedSharpeRatio` + * for all 500 trials): + * - Command: `bun run libs/calculations/scripts/benchmark-deflated-sharpe.ts` + * - Observed (Bun 1.2.16, 2 runs): `150.18 ms` (`830,660 pairs/s`) and `159.79 ms` (`780,707 pairs/s`). + */ + +/** Euler-Mascheroni constant (gamma). */ +export const EULER_MASCHERONI = 0.5772156649015329; + +/** Canonical Candidate -> Validated DSR threshold (`DSR >= 0.95`). */ +export const DSR_VALIDATION_GATE = 0.95; + +/** + * Per-trial daily return or IC moments matching `trial_ledger` columns. + * + * - `nObs`: count of finite observations used (`>= 2`). + * - `sharpeUnann`: unannualized daily Sharpe `(mean - dailyRiskFree) / sampleStd` + * using sample standard deviation (`n - 1` degrees of freedom). + * - `skewness`: plugin third standardized central moment `m3 / m2^(3/2)`, where + * `m_k = (1/n) * sum((x_i - mean)^k)`. Defined for all `nObs >= 2`. + * - `kurtosis`: plugin Pearson fourth standardized central moment `m4 / m2^2` + * (normal distribution = `3.0`, not excess kurtosis). Defined for all `nObs >= 2` + * and always satisfies `kurtosis >= skewness^2 + 1 >= 1`. + */ +export interface TrialMoments { + readonly nObs: number; + readonly sharpeUnann: number; + readonly skewness: number; + readonly kurtosis: number; +} + +/** + * Effective independent trials (`nHat`) computed from pairwise overlapping + * Pearson correlations across `k` trial series in a relatedness cluster. + */ +export interface EffectiveTrialsResult { + readonly k: number; + readonly pairsUsed: number; + readonly pairsSkipped: number; + readonly meanCorrelation: number | null; + readonly nHat: number; +} + +/** Inputs for the non-normal Deflated Sharpe Ratio calculation. */ +export interface DeflatedSharpeInput { + readonly sharpeUnann: number; + readonly nObs: number; + readonly skewness: number; + readonly kurtosis: number; + readonly nHat: number; + readonly clusterSharpes: readonly number[]; +} + +/** Output of the non-normal Deflated Sharpe Ratio calculation. */ +export interface DeflatedSharpeResult { + readonly sr0: number; + readonly standardError: number; + readonly dsr: number; +} + +const INV_SQRT_PI = 0.5641895835477563; + +// Cody (1969) rational Chebyshev coefficients for erf/erfc (~1e-15 accuracy). +const ERF_A0 = 3.1611237438705655; +const ERF_A1 = 113.86415415105016; +const ERF_A2 = 377.485237685302; +const ERF_A3 = 3209.3775891384694; +const ERF_A4 = 0.18577770618460315; + +const ERF_B0 = 23.601290952344122; +const ERF_B1 = 244.02463793444417; +const ERF_B2 = 1282.6165260773723; +const ERF_B3 = 2844.236833439171; + +const ERFC_C0 = 0.5641884969886701; +const ERFC_C1 = 8.883149794388377; +const ERFC_C2 = 66.11919063714163; +const ERFC_C3 = 298.6351381974001; +const ERFC_C4 = 881.952221241769; +const ERFC_C5 = 1712.0476126340707; +const ERFC_C6 = 2051.0783778260716; +const ERFC_C7 = 1230.3393547979972; +const ERFC_C8 = 2.1531153547440383e-8; + +const ERFC_D0 = 15.744926110709835; +const ERFC_D1 = 117.6939508913125; +const ERFC_D2 = 537.1811018620099; +const ERFC_D3 = 1621.3895745666903; +const ERFC_D4 = 3290.7992357334597; +const ERFC_D5 = 4362.619090143247; +const ERFC_D6 = 3439.3676741437216; +const ERFC_D7 = 1230.3393548037495; + +const ERFC_P0 = 0.30532663496123236; +const ERFC_P1 = 0.36034489994980445; +const ERFC_P2 = 0.12578172611122926; +const ERFC_P3 = 0.016083785148742275; +const ERFC_P4 = 0.0006587491615298378; +const ERFC_P5 = 0.016315387137302097; + +const ERFC_Q0 = 2.568520192289822; +const ERFC_Q1 = 1.8729528499234604; +const ERFC_Q2 = 0.5279051029514285; +const ERFC_Q3 = 0.06051834131244132; +const ERFC_Q4 = 0.0023352049762686918; + +function erfSmall(y: number): number { + const ysq = y * y; + let xnum = ERF_A4 * ysq; + let xden = ysq; + xnum = (xnum + ERF_A0) * ysq; + xden = (xden + ERF_B0) * ysq; + xnum = (xnum + ERF_A1) * ysq; + xden = (xden + ERF_B1) * ysq; + xnum = (xnum + ERF_A2) * ysq; + xden = (xden + ERF_B2) * ysq; + return (y * (xnum + ERF_A3)) / (xden + ERF_B3); +} + +function erfcPositive(y: number): number { + if (y <= 0.46875) { + return 1 - erfSmall(y); + } + if (y <= 4.0) { + let xnum = ERFC_C8 * y; + let xden = y; + xnum = (xnum + ERFC_C0) * y; + xden = (xden + ERFC_D0) * y; + xnum = (xnum + ERFC_C1) * y; + xden = (xden + ERFC_D1) * y; + xnum = (xnum + ERFC_C2) * y; + xden = (xden + ERFC_D2) * y; + xnum = (xnum + ERFC_C3) * y; + xden = (xden + ERFC_D3) * y; + xnum = (xnum + ERFC_C4) * y; + xden = (xden + ERFC_D4) * y; + xnum = (xnum + ERFC_C5) * y; + xden = (xden + ERFC_D5) * y; + xnum = (xnum + ERFC_C6) * y; + xden = (xden + ERFC_D6) * y; + const ratio = (xnum + ERFC_C7) / (xden + ERFC_D7); + const ysq = Math.trunc(y * 16) / 16; + const del = (y - ysq) * (y + ysq); + return Math.exp(-ysq * ysq) * Math.exp(-del) * ratio; + } + if (y >= 26.543) { + return 0; + } + const ysq = 1 / (y * y); + let xnum = ERFC_P5 * ysq; + let xden = ysq; + xnum = (xnum + ERFC_P0) * ysq; + xden = (xden + ERFC_Q0) * ysq; + xnum = (xnum + ERFC_P1) * ysq; + xden = (xden + ERFC_Q1) * ysq; + xnum = (xnum + ERFC_P2) * ysq; + xden = (xden + ERFC_Q2) * ysq; + xnum = (xnum + ERFC_P3) * ysq; + xden = (xden + ERFC_Q3) * ysq; + const tail = (ysq * (xnum + ERFC_P4)) / (xden + ERFC_Q4); + const ratio = (INV_SQRT_PI - tail) / y; + const yTrunc = Math.trunc(y * 16) / 16; + const del = (y - yTrunc) * (y + yTrunc); + return Math.exp(-yTrunc * yTrunc) * Math.exp(-del) * ratio; +} + +/** + * Standard normal cumulative distribution function `Phi(x)`. + * Uses Cody's rational Chebyshev `erfc` approximation (~1e-15 accuracy). + * Returns `null` for non-finite inputs. + */ +export function normalCdf(x: number): number | null { + if (!Number.isFinite(x)) { + return null; + } + const y = Math.abs(x) * Math.SQRT1_2; + if (y <= 0.46875) { + const halfErf = 0.5 * erfSmall(y); + return x >= 0 ? 0.5 + halfErf : 0.5 - halfErf; + } + const tail = 0.5 * erfcPositive(y); + return x >= 0 ? 1 - tail : tail; +} + +// Wichura Algorithm AS 241 (ppnd16) rational coefficients (~1e-16 accuracy). +const PPND_A0 = 3.3871328727963665; +const PPND_A1 = 133.14166789178438; +const PPND_A2 = 1971.5909503065513; +const PPND_A3 = 13731.69376550946; +const PPND_A4 = 45921.95393154987; +const PPND_A5 = 67265.7709270087; +const PPND_A6 = 33430.57558358813; +const PPND_A7 = 2509.0809287301227; + +const PPND_B1 = 42.31333070160091; +const PPND_B2 = 687.1870074920579; +const PPND_B3 = 5394.196021424751; +const PPND_B4 = 21213.794301586597; +const PPND_B5 = 39307.89580009271; +const PPND_B6 = 28729.085735721943; +const PPND_B7 = 5226.495278852854; + +const PPND_C0 = 1.4234371107496835; +const PPND_C1 = 4.630337846156546; +const PPND_C2 = 5.769497221460691; +const PPND_C3 = 3.6478483247632045; +const PPND_C4 = 1.2704582524523684; +const PPND_C5 = 0.2417807251774506; +const PPND_C6 = 0.022723844989269184; +const PPND_C7 = 0.0007745450142783414; + +const PPND_D1 = 2.053191626637759; +const PPND_D2 = 1.6763848301838038; +const PPND_D3 = 0.6897673349851; +const PPND_D4 = 0.14810397642748008; +const PPND_D5 = 0.015198666563616457; +const PPND_D6 = 0.0005475938084995345; +const PPND_D7 = 1.0507500716444169e-9; + +const PPND_E0 = 6.657904643501103; +const PPND_E1 = 5.463784911164114; +const PPND_E2 = 1.7848265399172913; +const PPND_E3 = 0.29656057182850487; +const PPND_E4 = 0.026532189526576124; +const PPND_E5 = 0.0012426609473880784; +const PPND_E6 = 0.000027115555687434876; +const PPND_E7 = 2.0103343992922881e-7; + +const PPND_F1 = 0.599832206555888; +const PPND_F2 = 0.1369298809227358; +const PPND_F3 = 0.014875361290850615; +const PPND_F4 = 0.0007868691311456133; +const PPND_F5 = 0.000018463183175100548; +const PPND_F6 = 1.421511758316446e-7; +const PPND_F7 = 2.0442631033899397e-15; + +/** + * Inverse standard normal CDF `Phi^-1(p)` via Wichura's Algorithm AS 241 (`ppnd16`). + * Achieves <= 1e-15 absolute error across `p in [1e-12, 1 - 1e-12]` with exact + * antisymmetry `Phi^-1(1 - p) = -Phi^-1(p)`. + * Returns `null` when `p <= 0`, `p >= 1`, or `p` is non-finite. + */ +export function inverseNormalCdf(p: number): number | null { + if (!Number.isFinite(p) || p <= 0 || p >= 1) { + return null; + } + + const q = p - 0.5; + if (Math.abs(q) <= 0.425) { + const r = 0.180625 - q * q; + const num = + (((((((PPND_A7 * r + PPND_A6) * r + PPND_A5) * r + PPND_A4) * r + PPND_A3) * r + PPND_A2) * + r + + PPND_A1) * + r + + PPND_A0) * + q; + const den = + ((((((PPND_B7 * r + PPND_B6) * r + PPND_B5) * r + PPND_B4) * r + PPND_B3) * r + PPND_B2) * r + + PPND_B1) * + r + + 1; + return num / den; + } + + const tailP = q < 0 ? p : 1 - p; + const r = Math.sqrt(-Math.log(tailP)); + let val: number; + if (r <= 5.0) { + const s = r - 1.6; + const num = + ((((((PPND_C7 * s + PPND_C6) * s + PPND_C5) * s + PPND_C4) * s + PPND_C3) * s + PPND_C2) * s + + PPND_C1) * + s + + PPND_C0; + const den = + ((((((PPND_D7 * s + PPND_D6) * s + PPND_D5) * s + PPND_D4) * s + PPND_D3) * s + PPND_D2) * s + + PPND_D1) * + s + + 1; + val = num / den; + } else { + const s = r - 5.0; + const num = + ((((((PPND_E7 * s + PPND_E6) * s + PPND_E5) * s + PPND_E4) * s + PPND_E3) * s + PPND_E2) * s + + PPND_E1) * + s + + PPND_E0; + const den = + ((((((PPND_F7 * s + PPND_F6) * s + PPND_F5) * s + PPND_F4) * s + PPND_F3) * s + PPND_F2) * s + + PPND_F1) * + s + + 1; + val = num / den; + } + + return q < 0 ? -val : val; +} + +/** + * Computes per-trial moments `{ nObs, sharpeUnann, skewness, kurtosis }` for a + * daily return or IC series, matching `trial_ledger` columns. + * + * Estimators: + * - Non-finite and sparse entries are filtered out before computing moments. + * - `sharpeUnann = (mean - dailyRiskFree) / sampleStd`, where `sampleStd` uses + * `n - 1` degrees of freedom via `sampleDeviation`. + * - `skewness = m3 / m2^(3/2)` and Pearson `kurtosis = m4 / m2^2` (normal = 3.0), + * using plugin central moments `m_k = (1/n) * sum((x_i - mean)^k)`. + * + * Returns `null` if `dailyRiskFree` is non-finite, fewer than 2 finite + * observations exist, variance is zero, or any resulting moment is non-finite. + */ +export function trialMoments(series: readonly number[], dailyRiskFree = 0): TrialMoments | null { + if (!Number.isFinite(dailyRiskFree)) { + return null; + } + + const finiteValues: number[] = []; + for (let i = 0; i < series.length; i++) { + const value = series[i]; + if (typeof value === 'number' && Number.isFinite(value)) { + finiteValues.push(value); + } + } + + const n = finiteValues.length; + if (n < 2) { + return null; + } + + const average = mean(finiteValues); + const std = sampleDeviation(finiteValues); + if (average === null || std === null || std === 0) { + return null; + } + + const sharpeUnann = (average - dailyRiskFree) / std; + let sum2 = 0; + let sum3 = 0; + let sum4 = 0; + for (let i = 0; i < n; i++) { + const d = (finiteValues[i] as number) - average; + const d2 = d * d; + sum2 += d2; + sum3 += d2 * d; + sum4 += d2 * d2; + } + + const m2 = sum2 / n; + if (!Number.isFinite(m2) || m2 <= 0) { + return null; + } + + const skewness = sum3 / n / (m2 * Math.sqrt(m2)); + const kurtosis = sum4 / n / (m2 * m2); + if (!Number.isFinite(sharpeUnann) || !Number.isFinite(skewness) || !Number.isFinite(kurtosis)) { + return null; + } + + return { nObs: n, sharpeUnann, skewness, kurtosis }; +} + +interface PreparedSeries { + readonly raw: Float64Array; + readonly allFinite: boolean; + readonly unit: Float64Array | null; +} + +function prepareSeries(series: readonly number[]): PreparedSeries { + const len = series.length; + const raw = new Float64Array(len); + let allFinite = true; + let sum = 0; + let allEqual = true; + let first = 0; + + for (let t = 0; t < len; t++) { + const v = series[t]; + if (typeof v === 'number' && Number.isFinite(v)) { + raw[t] = v; + sum += v; + if (t === 0) { + first = v; + } else if (v !== first) { + allEqual = false; + } + } else { + raw[t] = Number.NaN; + allFinite = false; + } + } + + if (!allFinite || len < 2 || allEqual) { + return { raw, allFinite, unit: null }; + } + + const mu = sum / len; + if (!Number.isFinite(mu)) { + return { raw, allFinite, unit: null }; + } + + const unit = new Float64Array(len); + let normSq = 0; + for (let t = 0; t < len; t++) { + const d = (raw[t] as number) - mu; + unit[t] = d; + normSq += d * d; + } + + if (!Number.isFinite(normSq) || normSq <= 0) { + return { raw, allFinite, unit: null }; + } + + const invNorm = 1 / Math.sqrt(normSq); + if (!Number.isFinite(invNorm)) { + return { raw, allFinite, unit: null }; + } + + for (let t = 0; t < len; t++) { + unit[t] = (unit[t] as number) * invNorm; + } + + return { raw, allFinite, unit }; +} + +/** + * Computes mean pairwise Pearson correlation `rho_bar` across overlapping + * index-aligned finite observations and effective independent trials: + * `nHat = max(1, 1 + (K - 1) * (1 - max(0, rho_bar)))`. + * + * Pairs with fewer than 2 overlapping finite observations or zero variance on + * the overlap are skipped and counted in `pairsSkipped` rather than silently + * treated as `rho = 0`. + * + * - For `K <= 1`, returns `{ k, pairsUsed: 0, pairsSkipped: 0, meanCorrelation: null, nHat: 1 }`. + * - For `K >= 2` with `pairsUsed === 0`, returns `meanCorrelation: null` and + * conservative `nHat = K` (no correlation discount without valid pairs). + */ +export function effectiveIndependentTrials( + seriesList: readonly (readonly number[])[] +): EffectiveTrialsResult { + const k = seriesList.length; + if (k <= 1) { + return { k, pairsUsed: 0, pairsSkipped: 0, meanCorrelation: null, nHat: 1 }; + } + + const prepared: PreparedSeries[] = new Array(k); + for (let i = 0; i < k; i++) { + prepared[i] = prepareSeries(seriesList[i] as readonly number[]); + } + + let rhoSum = 0; + let pairsUsed = 0; + let pairsSkipped = 0; + + for (let i = 0; i < k - 1; i++) { + const a = prepared[i] as PreparedSeries; + const aRaw = a.raw; + const aLen = aRaw.length; + const aUnit = a.unit; + const aAllFinite = a.allFinite; + + for (let j = i + 1; j < k; j++) { + const b = prepared[j] as PreparedSeries; + const bRaw = b.raw; + const bLen = bRaw.length; + + // Fast path: equal-length all-finite series use pre-normalized unit vectors. + if (aAllFinite && b.allFinite && aLen === bLen) { + const bUnit = b.unit; + if (aUnit === null || bUnit === null) { + pairsSkipped++; + continue; + } + let dot = 0; + for (let t = 0; t < aLen; t++) { + dot += (aUnit[t] as number) * (bUnit[t] as number); + } + if (!Number.isFinite(dot)) { + pairsSkipped++; + continue; + } + rhoSum += dot < -1 ? -1 : dot > 1 ? 1 : dot; + pairsUsed++; + continue; + } + + // General path: allocation-free two-pass centered Pearson over overlapping finite pairs. + const len = aLen < bLen ? aLen : bLen; + let overlap = 0; + let sumA = 0; + let sumB = 0; + let firstA = 0; + let firstB = 0; + let allEqualA = true; + let allEqualB = true; + + for (let t = 0; t < len; t++) { + const va = aRaw[t] as number; + const vb = bRaw[t] as number; + if (Number.isFinite(va) && Number.isFinite(vb)) { + if (overlap === 0) { + firstA = va; + firstB = vb; + } else { + if (va !== firstA) { + allEqualA = false; + } + if (vb !== firstB) { + allEqualB = false; + } + } + sumA += va; + sumB += vb; + overlap++; + } + } + + if (overlap < 2 || allEqualA || allEqualB) { + pairsSkipped++; + continue; + } + + const meanA = sumA / overlap; + const meanB = sumB / overlap; + let cov = 0; + let varA = 0; + let varB = 0; + + for (let t = 0; t < len; t++) { + const va = aRaw[t] as number; + const vb = bRaw[t] as number; + if (Number.isFinite(va) && Number.isFinite(vb)) { + const da = va - meanA; + const db = vb - meanB; + cov += da * db; + varA += da * da; + varB += db * db; + } + } + + if (!Number.isFinite(varA) || !Number.isFinite(varB) || varA <= 0 || varB <= 0) { + pairsSkipped++; + continue; + } + + const denom = Math.sqrt(varA * varB); + if (!Number.isFinite(denom) || denom <= 0) { + pairsSkipped++; + continue; + } + + const rawRho = cov / denom; + if (!Number.isFinite(rawRho)) { + pairsSkipped++; + continue; + } + + rhoSum += rawRho < -1 ? -1 : rawRho > 1 ? 1 : rawRho; + pairsUsed++; + } + } + + if (pairsUsed === 0) { + return { k, pairsUsed: 0, pairsSkipped, meanCorrelation: null, nHat: k }; + } + + const meanCorrelation = rhoSum / pairsUsed; + const nHat = Math.max(1, 1 + (k - 1) * (1 - Math.max(0, meanCorrelation))); + return { k, pairsUsed, pairsSkipped, meanCorrelation, nHat }; +} + +/** + * Computes the non-normal Deflated Sharpe Ratio (Bailey & López de Prado, 2014): + * + * - `SR0 = max(0, sigma_SR * [(1 - gamma) * Phi^-1(1 - 1/nHat) + gamma * Phi^-1(1 - 1/(nHat * e))])` + * where `sigma_SR` is the sample standard deviation of `clusterSharpes`. + * For `nHat === 1`, `clusterSharpes.length < 2`, or `sigma_SR === 0`, `SR0 = 0`. + * The `max(0, ...)` floor keeps `E[max Z] >= 0` for fractional `1 < nHat < ~1.298` + * (where the asymptotic EVT formula dips slightly negative) so DSR remains + * monotonically non-increasing in `nHat`. + * - `SE = sqrt((1 - skewness * sharpeUnann + ((kurtosis - 1) / 4) * sharpeUnann^2) / (nObs - 1))` + * - `DSR = Phi((sharpeUnann - SR0) / SE)` + * + * Returns `null` if any scalar or `clusterSharpes` entry is non-finite, + * `nObs < 2`, `nHat < 1`, or the SE radicand is non-positive. + */ +export function deflatedSharpeRatio(input: DeflatedSharpeInput): DeflatedSharpeResult | null { + const { sharpeUnann, nObs, skewness, kurtosis, nHat, clusterSharpes } = input; + + if ( + !Number.isFinite(sharpeUnann) || + !Number.isFinite(nObs) || + !Number.isFinite(skewness) || + !Number.isFinite(kurtosis) || + !Number.isFinite(nHat) || + nObs < 2 || + nHat < 1 + ) { + return null; + } + + for (let i = 0; i < clusterSharpes.length; i++) { + const value = clusterSharpes[i]; + if (typeof value !== 'number' || !Number.isFinite(value)) { + return null; + } + } + + let sr0 = 0; + if (nHat > 1 && clusterSharpes.length >= 2) { + const sigmaSr = sampleDeviation(clusterSharpes); + if (sigmaSr === null) { + return null; + } + if (sigmaSr > 0) { + const z1 = inverseNormalCdf(1 - 1 / nHat); + const z2 = inverseNormalCdf(1 - 1 / (nHat * Math.E)); + if (z1 === null || z2 === null) { + return null; + } + const rawSr0 = sigmaSr * ((1 - EULER_MASCHERONI) * z1 + EULER_MASCHERONI * z2); + if (!Number.isFinite(rawSr0)) { + return null; + } + sr0 = Math.max(0, rawSr0); + } + } + + const radicand = + (1 - skewness * sharpeUnann + ((kurtosis - 1) / 4) * sharpeUnann * sharpeUnann) / (nObs - 1); + if (!Number.isFinite(radicand) || radicand <= 0) { + return null; + } + + const standardError = Math.sqrt(radicand); + const dsr = normalCdf((sharpeUnann - sr0) / standardError); + if (dsr === null) { + return null; + } + + return { sr0, standardError, dsr }; +} + +/** + * Returns `true` when `dsr` is finite and meets or exceeds the validation gate + * (default `DSR_VALIDATION_GATE = 0.95`). Returns `false` for `null` or non-finite inputs. + */ +export function passesDsrGate(dsr: number | null, gate = DSR_VALIDATION_GATE): boolean { + return dsr !== null && Number.isFinite(dsr) && Number.isFinite(gate) && dsr >= gate; +} diff --git a/libs/calculations/src/analytics/event-study.ts b/libs/calculations/src/analytics/event-study.ts new file mode 100644 index 00000000..0bdd8cb4 --- /dev/null +++ b/libs/calculations/src/analytics/event-study.ts @@ -0,0 +1,1068 @@ +/** + * Pure, zero-I/O event-study math per `design/PLATFORM-PLAN.md`, `design/MILESTONES.md` (M1), + * and `design/VALIDATION-AND-RIGOR.md`. + * + * Covers: + * - Zero-look-ahead event timestamp to session index mapping (`eventDayIndex`) + * - Cross-sectional abnormal returns (raw or benchmark-adjusted) across `[-preDays, +postDays]` + * - Average abnormal return (AAR), cross-sectional standard error, cumulative AAR (`caar` and `caarFromZero`) + * - Per-offset R-7 CAR percentile fans (`p5`, `p25`, `p50`, `p75`, `p95`) + * - Date-clustered post-event `CAR[0..postDays]` significance via Newey-West HAC (`neweyWestMeanTest`) + * - Sign-preserving pre/post-2023 recency split and gate reusing `evaluateRecencyGate` + * + * Pure stateless math: zero I/O, zero wall-clock or random calls, bit-identical determinism + * via canonical `(dayIndex ASC, entityId ASC)` 2-pass counting sort, and reused typed-array + * scratch buffers on the offset hot path. + */ + +import { + RECENCY_MIN_RATIO, + RECENCY_SPLIT_DATE, + evaluateRecencyGate, + neweyWestMeanTest, + type EntityId, + type IcSummary, + type NeweyWestResult, + type NumericSeries, + type RecencyGateReason, +} from './signal-analysis'; + +/** Default number of trading sessions before the event session (`-10`). */ +export const DEFAULT_EVENT_PRE_DAYS = 10; + +/** Default number of trading sessions after the event session (`+20`). */ +export const DEFAULT_EVENT_POST_DAYS = 20; + +/** Default minimum usable events required to run an event study. */ +export const DEFAULT_EVENT_MIN_EVENTS = 5; + +/** Machine-readable error codes thrown by {@link EventStudyError}. */ +export type EventStudyErrorCode = + | 'INVALID_OPTION' + | 'INVALID_DATE' + | 'UNSORTED_DATES' + | 'DUPLICATE_DATE' + | 'INVALID_TIMESTAMP' + | 'UNSORTED_TIMESTAMPS' + | 'LENGTH_MISMATCH' + | 'INVALID_EVENT' + | 'NON_FINITE_RETURN'; + +/** Typed validation error thrown for malformed event-study inputs or options. */ +export class EventStudyError extends RangeError { + readonly code: EventStudyErrorCode; + + constructor(code: EventStudyErrorCode, message: string) { + super(message); + this.name = 'EventStudyError'; + this.code = code; + } +} + +/** Result of mapping an event timestamp to the first eligible session close (`>= knownAtTs`). */ +export type EventDayIndexResult = + | { + readonly status: 'ok'; + readonly dayIndex: number; + } + | { + readonly status: 'no_session'; + readonly reason: 'empty_calendar' | 'after_last_session'; + }; + +/** Single event anchored to an entity and a zero-based session calendar index. */ +export interface EventStudyEvent { + readonly entityId: EntityId; + readonly dayIndex: number; +} + +/** Input panel and event list for {@link eventStudy}. */ +export interface EventStudyInput { + readonly sessionDates: readonly string[]; + readonly entityReturns: ReadonlyMap; + readonly benchmarkReturns?: NumericSeries; + readonly events: readonly EventStudyEvent[]; +} + +/** Configuration options for {@link eventStudy}. */ +export interface EventStudyOptions { + readonly preDays?: number; + readonly postDays?: number; + readonly minEvents?: number; + readonly neweyWestLag?: number; + readonly recencySplitDate?: string; + readonly recencyMinRatio?: number; +} + +/** Cross-sectional R-7 linear-interpolation percentiles of per-event CARs at one offset. */ +export interface EventStudyPercentiles { + readonly p5: number; + readonly p25: number; + readonly p50: number; + readonly p75: number; + readonly p95: number; +} + +/** Abnormal-return and cumulative-abnormal-return summary for a single event offset. */ +export interface EventStudyOffsetStats { + readonly offset: number; + readonly n: number; + readonly aar: number; + readonly standardError: number; + readonly caar: number; + readonly caarFromZero: number | null; + readonly carPercentiles: EventStudyPercentiles; + readonly postCarPercentiles: EventStudyPercentiles | null; +} + +/** Columnar per-event `CAR[0..postDays]` ordered canonically by `(dayIndex ASC, entityId ASC)`. */ +export interface EventCarSeries { + readonly entityIds: readonly EntityId[]; + readonly dayIndices: Int32Array; + readonly dates: readonly string[]; + readonly cars: Float64Array; +} + +/** Date-clustered post-event `CAR[0..postDays]` summary and Newey-West HAC test. */ +export interface DateClusteredCarResult { + readonly nDates: number; + readonly dates: readonly string[]; + readonly eventCounts: Int32Array; + readonly meanCars: Float64Array; + readonly carMean: number; + readonly neweyWest: NeweyWestResult; +} + +/** Explicit reason describing why the sign-preserving event-study recency gate passed or failed. */ +export type EventStudyRecencyReason = + | 'passed' + | 'empty_pre_window' + | 'empty_post_window' + | 'zero_pre_mean' + | 'sign_flipped' + | 'post_below_ratio_threshold'; + +/** Pass/fail outcome of the sign-preserving post-2023 event-study recency gate. */ +export interface EventStudyRecencyGate { + readonly pass: boolean; + readonly reason: EventStudyRecencyReason; + readonly ratio: number | null; +} + +/** + * Pre/post recency split summaries and sign-preserving gate decision on date-clustered CARs. + * + * Cohort assignment follows the event session date (`sessionDates[dayIndex] < splitDate` vs + * `>= splitDate`): each event's complete `CAR[0..postDays]` belongs to its event-date cohort. + * Consequently, a late pre-split event whose post-event window extends into the post-split + * calendar period contributes those returns to `pre`. Callers requiring strictly disjoint + * calendar return periods should exclude pre-split events whose `dayIndex + postDays` session + * falls on or after `splitDate`. + */ +export interface EventStudyRecencyResult { + readonly splitDate: string; + readonly minRatio: number; + readonly pre: IcSummary; + readonly post: IcSummary; + readonly gate: EventStudyRecencyGate; +} + +/** Exact event-filtering accounting (`eventsIn === eventsUsed + all dropped/collapsed`). */ +export interface EventStudyDiagnostics { + readonly eventsIn: number; + readonly eventsUsed: number; + readonly droppedUnknownEntity: number; + readonly droppedWindowOutOfRange: number; + readonly droppedMissingReturns: number; + readonly duplicateEventsCollapsed: number; +} + +/** Output of {@link eventStudy}. Returns an `insufficient_data` variant instead of `NaN`. */ +export type EventStudyResult = + | { + readonly status: 'ok'; + readonly preDays: number; + readonly postDays: number; + readonly hasBenchmark: boolean; + readonly offsets: readonly EventStudyOffsetStats[]; + readonly eventCars: EventCarSeries; + readonly clustered: DateClusteredCarResult; + readonly recency: EventStudyRecencyResult; + readonly diagnostics: EventStudyDiagnostics; + } + | { + readonly status: 'insufficient_data'; + readonly reason: 'below_min_events' | 'too_few_event_dates'; + readonly preDays: number; + readonly postDays: number; + readonly hasBenchmark: boolean; + readonly eventsUsed: number; + readonly nDates: number; + readonly diagnostics: EventStudyDiagnostics; + }; + +const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function assertIsoDate(value: string, label: string): void { + if (typeof value !== 'string' || !ISO_DATE_RE.test(value)) { + throw new EventStudyError('INVALID_DATE', `${label} must be a valid YYYY-MM-DD date`); + } + const year = Number(value.slice(0, 4)); + const month = Number(value.slice(5, 7)); + const day = Number(value.slice(8, 10)); + if (month < 1 || month > 12) { + throw new EventStudyError('INVALID_DATE', `${label} has invalid month: ${value}`); + } + const baseDays = DAYS_IN_MONTH[month] ?? 0; + const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays; + if (day < 1 || day > maxDay) { + throw new EventStudyError('INVALID_DATE', `${label} is not a valid calendar date: ${value}`); + } +} + +function assertIntegerOption(value: number, min: number, label: string): void { + if (typeof value !== 'number' || !Number.isInteger(value) || value < min) { + throw new EventStudyError( + 'INVALID_OPTION', + `${label} must be an integer >= ${min}, received ${String(value)}` + ); + } +} + +function assertPositiveFiniteOption(value: number, label: string): void { + if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) { + throw new EventStudyError( + 'INVALID_OPTION', + `${label} must be a finite number > 0, received ${String(value)}` + ); + } +} + +function assertValidEntityId(id: EntityId, label: string): void { + if (typeof id === 'string') { + return; + } + if (typeof id === 'number' && !Number.isNaN(id)) { + return; + } + throw new EventStudyError('INVALID_EVENT', `${label} must be a string or non-NaN number`); +} + +function assertReturnSeriesValid(series: NumericSeries, expectedLength: number, label: string): void { + if (series.length !== expectedLength) { + throw new EventStudyError( + 'LENGTH_MISMATCH', + `${label} length (${series.length}) does not match sessionDates length (${expectedLength})` + ); + } + for (let i = 0; i < expectedLength; i++) { + const v = series[i]; + if ( + typeof v !== 'number' || + v === Number.POSITIVE_INFINITY || + v === Number.NEGATIVE_INFINITY + ) { + throw new EventStudyError( + 'NON_FINITE_RETURN', + `${label}[${i}] must be a finite number or NaN, received ${String(v)}` + ); + } + } +} + +function compareIds(a: EntityId, b: EntityId): number { + const typeA = typeof a; + const typeB = typeof b; + if (typeA === typeB) { + return a < b ? -1 : a > b ? 1 : 0; + } + return typeA === 'number' ? -1 : 1; +} + +function insertionSortRange(buf: Float64Array, left: number, right: number): void { + for (let i = left + 1; i <= right; i++) { + const val = buf[i] as number; + let j = i - 1; + while (j >= left && (buf[j] as number) > val) { + buf[j + 1] = buf[j] as number; + j--; + } + buf[j + 1] = val; + } +} + +function siftDown(buf: Float64Array, offset: number, start: number, count: number): void { + let root = start; + while (true) { + const leftChild = (root << 1) + 1; + if (leftChild >= count) { + return; + } + let swapIdx = root; + if ((buf[offset + swapIdx] as number) < (buf[offset + leftChild] as number)) { + swapIdx = leftChild; + } + const rightChild = leftChild + 1; + if ( + rightChild < count && + (buf[offset + swapIdx] as number) < (buf[offset + rightChild] as number) + ) { + swapIdx = rightChild; + } + if (swapIdx === root) { + return; + } + const tmp = buf[offset + root] as number; + buf[offset + root] = buf[offset + swapIdx] as number; + buf[offset + swapIdx] = tmp; + root = swapIdx; + } +} + +function heapSortRange(buf: Float64Array, left: number, right: number): void { + const count = right - left + 1; + for (let start = (count - 2) >> 1; start >= 0; start--) { + siftDown(buf, left, start, count); + } + for (let end = count - 1; end > 0; end--) { + const tmp = buf[left + end] as number; + buf[left + end] = buf[left] as number; + buf[left] = tmp; + siftDown(buf, left, 0, end); + } +} + +function medianOfThree(a: number, b: number, c: number): number { + if (a < b) { + if (b < c) { + return b; + } + return a < c ? c : a; + } + if (a < c) { + return a; + } + return b < c ? c : b; +} + +function introselect(buf: Float64Array, leftInit: number, rightInit: number, k: number): void { + let left = leftInit; + let right = rightInit; + const span = right - left + 1; + let depthLimit = span > 1 ? 2 * Math.floor(Math.log2(span)) + 2 : 0; + + while (right - left > 16) { + if (depthLimit === 0) { + heapSortRange(buf, left, right); + return; + } + depthLimit--; + + const mid = (left + right) >>> 1; + const pivot = medianOfThree(buf[left] as number, buf[mid] as number, buf[right] as number); + + // 3-way partition so equal-value runs collapse in O(n). + let lt = left; + let i = left; + let gt = right; + while (i <= gt) { + const v = buf[i] as number; + if (v < pivot) { + buf[i] = buf[lt] as number; + buf[lt] = v; + lt++; + i++; + } else if (v > pivot) { + buf[i] = buf[gt] as number; + buf[gt] = v; + gt--; + } else { + i++; + } + } + + if (k < lt) { + right = lt - 1; + } else if (k > gt) { + left = gt + 1; + } else { + return; + } + } + + if (right > left) { + insertionSortRange(buf, left, right); + } +} + +function minInRange(buf: Float64Array, start: number, endInclusive: number): number { + let best = buf[start] as number; + for (let i = start + 1; i <= endInclusive; i++) { + const v = buf[i] as number; + if (v < best) { + best = v; + } + } + return best; +} + +function computeR7Percentiles(buf: Float64Array, length: number): EventStudyPercentiles { + const last = length - 1; + if (length < 65) { + insertionSortRange(buf, 0, last); + const pick = (q: number): number => { + const pos = q * last; + const lo = Math.floor(pos); + const hi = Math.ceil(pos); + const loVal = buf[lo] as number; + if (lo === hi) { + return loVal; + } + return loVal + (pos - lo) * ((buf[hi] as number) - loVal); + }; + return { + p5: pick(0.05), + p25: pick(0.25), + p50: pick(0.5), + p75: pick(0.75), + p95: pick(0.95), + }; + } + + const pos5 = 0.05 * last; + const pos25 = 0.25 * last; + const pos50 = 0.5 * last; + const pos75 = 0.75 * last; + const pos95 = 0.95 * last; + + const lo5 = Math.floor(pos5); + const lo25 = Math.floor(pos25); + const lo50 = Math.floor(pos50); + const lo75 = Math.floor(pos75); + const lo95 = Math.floor(pos95); + + // For length >= 65, lo5 < lo25 < lo50 < lo75 < lo95 < last are strictly separated. + introselect(buf, 0, last, lo50); + introselect(buf, 0, lo50 - 1, lo25); + introselect(buf, 0, lo25 - 1, lo5); + introselect(buf, lo50 + 1, last, lo75); + introselect(buf, lo75 + 1, last, lo95); + + const v5 = buf[lo5] as number; + const f5 = pos5 - lo5; + const p5 = f5 === 0 ? v5 : v5 + f5 * (minInRange(buf, lo5 + 1, lo25 - 1) - v5); + + const v25 = buf[lo25] as number; + const f25 = pos25 - lo25; + const p25 = f25 === 0 ? v25 : v25 + f25 * (minInRange(buf, lo25 + 1, lo50 - 1) - v25); + + const v50 = buf[lo50] as number; + const f50 = pos50 - lo50; + const p50 = f50 === 0 ? v50 : v50 + f50 * (minInRange(buf, lo50 + 1, lo75 - 1) - v50); + + const v75 = buf[lo75] as number; + const f75 = pos75 - lo75; + const p75 = f75 === 0 ? v75 : v75 + f75 * (minInRange(buf, lo75 + 1, lo95 - 1) - v75); + + const v95 = buf[lo95] as number; + const f95 = pos95 - lo95; + const p95 = f95 === 0 ? v95 : v95 + f95 * (minInRange(buf, lo95 + 1, last) - v95); + + return { p5, p25, p50, p75, p95 }; +} + +function mapRecencyReason(reason: RecencyGateReason): EventStudyRecencyReason { + switch (reason) { + case 'non_positive_pre_mean': + return 'zero_pre_mean'; + case 'non_positive_post_mean': + return 'sign_flipped'; + default: + return reason; + } +} + +/** + * Maps an event's information-availability timestamp (`knownAtTs`) to the first trading + * session whose close timestamp is `>= knownAtTs`. + * + * Enforces zero look-ahead: an event known strictly after session `k`'s close maps to + * session `k + 1`. Validates every timestamp in `sessionCloseTs` for finiteness and + * strict ascending order before running the lower-bound binary search. + */ +export function eventDayIndex( + sessionCloseTs: NumericSeries, + knownAtTs: number +): EventDayIndexResult { + if (typeof knownAtTs !== 'number' || !Number.isFinite(knownAtTs)) { + throw new EventStudyError( + 'INVALID_TIMESTAMP', + `knownAtTs must be a finite number, received ${String(knownAtTs)}` + ); + } + + const n = sessionCloseTs.length; + for (let i = 0; i < n; i++) { + const ts = sessionCloseTs[i]; + if (typeof ts !== 'number' || !Number.isFinite(ts)) { + throw new EventStudyError( + 'INVALID_TIMESTAMP', + `sessionCloseTs[${i}] must be a finite number, received ${String(ts)}` + ); + } + if (i > 0 && ts <= (sessionCloseTs[i - 1] as number)) { + throw new EventStudyError( + 'UNSORTED_TIMESTAMPS', + `sessionCloseTs must be strictly ascending: ${String(sessionCloseTs[i - 1])} followed by ${String(ts)} at index ${i}` + ); + } + } + + if (n === 0) { + return { status: 'no_session', reason: 'empty_calendar' }; + } + + if (knownAtTs > (sessionCloseTs[n - 1] as number)) { + return { status: 'no_session', reason: 'after_last_session' }; + } + + let lo = 0; + let hi = n - 1; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if ((sessionCloseTs[mid] as number) < knownAtTs) { + lo = mid + 1; + } else { + hi = mid; + } + } + + return { status: 'ok', dayIndex: lo }; +} + +/** + * Runs a pure, deterministic event study over an aligned daily-return panel: + * - computes raw or benchmark-adjusted abnormal returns across `[-preDays, +postDays]`, + * - produces per-offset AAR, cross-sectional standard error, CAAR (`-preDays..k` and `0..k`), + * and R-7 CAR percentile fans (`p5`, `p25`, `p50`, `p75`, `p95`), + * - clusters per-event `CAR[0..postDays]` by event session date and evaluates Newey-West HAC + * significance on the date-ordered clustered series, + * - evaluates the sign-preserving pre/post-2023 recency gate on the date-clustered series. + */ +export function eventStudy( + input: EventStudyInput, + options?: EventStudyOptions +): EventStudyResult { + const preDays = options?.preDays ?? DEFAULT_EVENT_PRE_DAYS; + const postDays = options?.postDays ?? DEFAULT_EVENT_POST_DAYS; + const minEvents = options?.minEvents ?? DEFAULT_EVENT_MIN_EVENTS; + const neweyWestLag = options?.neweyWestLag; + const recencySplitDate = options?.recencySplitDate ?? RECENCY_SPLIT_DATE; + const recencyMinRatio = options?.recencyMinRatio ?? RECENCY_MIN_RATIO; + + assertIntegerOption(preDays, 0, 'preDays'); + assertIntegerOption(postDays, 0, 'postDays'); + assertIntegerOption(minEvents, 1, 'minEvents'); + if (neweyWestLag !== undefined) { + assertIntegerOption(neweyWestLag, 0, 'neweyWestLag'); + } + assertIsoDate(recencySplitDate, 'recencySplitDate'); + assertPositiveFiniteOption(recencyMinRatio, 'recencyMinRatio'); + + const { sessionDates, entityReturns, benchmarkReturns, events } = input; + const T = sessionDates.length; + for (let t = 0; t < T; t++) { + const d = sessionDates[t] as string; + assertIsoDate(d, `sessionDates[${t}]`); + if (t > 0) { + const prev = sessionDates[t - 1] as string; + if (d === prev) { + throw new EventStudyError('DUPLICATE_DATE', `Duplicate session date at index ${t}: ${d}`); + } + if (d < prev) { + throw new EventStudyError( + 'UNSORTED_DATES', + `sessionDates must be strictly ascending: ${prev} followed by ${d} at index ${t}` + ); + } + } + } + + const hasBenchmark = benchmarkReturns !== undefined; + let benchPrefixNaN: Int32Array | null = null; + if (benchmarkReturns !== undefined) { + assertReturnSeriesValid(benchmarkReturns, T, 'benchmarkReturns'); + benchPrefixNaN = new Int32Array(T + 1); + let nanCount = 0; + for (let t = 0; t < T; t++) { + const v = benchmarkReturns[t] as number; + if (v !== v) { + nanCount++; + } + benchPrefixNaN[t + 1] = nanCount; + } + } + + const canonicalEntityIds: EntityId[] = []; + for (const [entityId, series] of entityReturns) { + assertValidEntityId(entityId, 'entityReturns key'); + assertReturnSeriesValid(series, T, `entityReturns[${String(entityId)}]`); + canonicalEntityIds.push(entityId); + } + canonicalEntityIds.sort(compareIds); + + const E = canonicalEntityIds.length; + const entityIndexMap = new Map(); + const entitySeriesArr: NumericSeries[] = new Array(E); + for (let e = 0; e < E; e++) { + const id = canonicalEntityIds[e] as EntityId; + entityIndexMap.set(id, e); + entitySeriesArr[e] = entityReturns.get(id) as NumericSeries; + } + + const eventsIn = events.length; + const candDay = new Int32Array(eventsIn); + const candEnt = new Int32Array(eventsIn); + let candCount = 0; + + let droppedUnknownEntity = 0; + let droppedWindowOutOfRange = 0; + let droppedMissingReturns = 0; + let duplicateEventsCollapsed = 0; + + let unknownSeen: Set | null = null; + let outOfRangeSeen: Set | null = null; + + for (let i = 0; i < eventsIn; i++) { + const ev = events[i] as EventStudyEvent; + assertValidEntityId(ev.entityId, `events[${i}].entityId`); + const dayIndex = ev.dayIndex; + if (typeof dayIndex !== 'number' || !Number.isInteger(dayIndex) || dayIndex < 0) { + throw new EventStudyError( + 'INVALID_EVENT', + `events[${i}].dayIndex must be a non-negative integer, received ${String(dayIndex)}` + ); + } + + const entIdx = entityIndexMap.get(ev.entityId); + if (entIdx === undefined) { + if (unknownSeen === null) { + unknownSeen = new Set(); + } + const key = `${typeof ev.entityId === 'number' ? 'n' : 's'}:${String(ev.entityId)}:${dayIndex}`; + if (unknownSeen.has(key)) { + duplicateEventsCollapsed++; + } else { + unknownSeen.add(key); + droppedUnknownEntity++; + } + continue; + } + + if (dayIndex - preDays < 0 || dayIndex + postDays >= T) { + if (outOfRangeSeen === null) { + outOfRangeSeen = new Set(); + } + const key = `${entIdx}:${dayIndex}`; + if (outOfRangeSeen.has(key)) { + duplicateEventsCollapsed++; + } else { + outOfRangeSeen.add(key); + droppedWindowOutOfRange++; + } + continue; + } + + candDay[candCount] = dayIndex; + candEnt[candCount] = entIdx; + candCount++; + } + + // Canonical 2-pass counting sort into (dayIndex ASC, entityOrder ASC). + if (candCount > 1) { + const tmpDay = new Int32Array(candCount); + const tmpEnt = new Int32Array(candCount); + + const entCounts = new Int32Array(E + 1); + for (let i = 0; i < candCount; i++) { + const idx = (candEnt[i] as number) + 1; + entCounts[idx] = (entCounts[idx] as number) + 1; + } + for (let e = 1; e <= E; e++) { + entCounts[e] = (entCounts[e] as number) + (entCounts[e - 1] as number); + } + for (let i = 0; i < candCount; i++) { + const e = candEnt[i] as number; + const pos = entCounts[e] as number; + entCounts[e] = pos + 1; + tmpDay[pos] = candDay[i] as number; + tmpEnt[pos] = e; + } + + const dayCounts = new Int32Array(T + 1); + for (let i = 0; i < candCount; i++) { + const idx = (tmpDay[i] as number) + 1; + dayCounts[idx] = (dayCounts[idx] as number) + 1; + } + for (let t = 1; t <= T; t++) { + dayCounts[t] = (dayCounts[t] as number) + (dayCounts[t - 1] as number); + } + for (let i = 0; i < candCount; i++) { + const d = tmpDay[i] as number; + const pos = dayCounts[d] as number; + dayCounts[d] = pos + 1; + candDay[pos] = d; + candEnt[pos] = tmpEnt[i] as number; + } + } + + const evDay = new Int32Array(candCount); + const evEnt = new Int32Array(candCount); + let eventsUsed = 0; + let prevDay = -1; + let prevEnt = -1; + + for (let i = 0; i < candCount; i++) { + const d = candDay[i] as number; + const e = candEnt[i] as number; + if (d === prevDay && e === prevEnt) { + duplicateEventsCollapsed++; + continue; + } + prevDay = d; + prevEnt = e; + + const start = d - preDays; + const end = d + postDays; + + if ( + benchPrefixNaN !== null && + (benchPrefixNaN[end + 1] as number) !== (benchPrefixNaN[start] as number) + ) { + droppedMissingReturns++; + continue; + } + + const series = entitySeriesArr[e] as NumericSeries; + let missing = false; + for (let t = start; t <= end; t++) { + const v = series[t] as number; + if (v !== v) { + missing = true; + break; + } + } + if (missing) { + droppedMissingReturns++; + continue; + } + + evDay[eventsUsed] = d; + evEnt[eventsUsed] = e; + eventsUsed++; + } + + let nDates = 0; + let lastDay = -1; + for (let i = 0; i < eventsUsed; i++) { + const d = evDay[i] as number; + if (d !== lastDay) { + nDates++; + lastDay = d; + } + } + + const diagnostics: EventStudyDiagnostics = { + eventsIn, + eventsUsed, + droppedUnknownEntity, + droppedWindowOutOfRange, + droppedMissingReturns, + duplicateEventsCollapsed, + }; + + if (eventsUsed < minEvents) { + return { + status: 'insufficient_data', + reason: 'below_min_events', + preDays, + postDays, + hasBenchmark, + eventsUsed, + nDates, + diagnostics, + }; + } + + if (nDates < 2) { + return { + status: 'insufficient_data', + reason: 'too_few_event_dates', + preDays, + postDays, + hasBenchmark, + eventsUsed, + nDates, + diagnostics, + }; + } + + const M = eventsUsed; + const windowLen = preDays + postDays + 1; + const arBuf = new Float64Array(M); + const runningCar = new Float64Array(M); + const runningPostCar = new Float64Array(M); + const sortBuf = new Float64Array(M); + + const offsets: EventStudyOffsetStats[] = new Array(windowLen); + const invSeDenom = 1 / (M * (M - 1)); + + let caarSum = 0; + let caarComp = 0; + let caarZeroSum = 0; + let caarZeroComp = 0; + + for (let w = 0; w < windowLen; w++) { + const k = w - preDays; + let aarSum = 0; + let aarComp = 0; + + if (benchmarkReturns !== undefined) { + if (k >= 0) { + for (let i = 0; i < M; i++) { + const t = (evDay[i] as number) + k; + const r = + ((entitySeriesArr[evEnt[i] as number] as NumericSeries)[t] as number) - + (benchmarkReturns[t] as number); + arBuf[i] = r; + runningCar[i] = (runningCar[i] as number) + r; + runningPostCar[i] = (runningPostCar[i] as number) + r; + const next = aarSum + r; + if (Math.abs(aarSum) >= Math.abs(r)) { + aarComp += aarSum - next + r; + } else { + aarComp += r - next + aarSum; + } + aarSum = next; + } + } else { + for (let i = 0; i < M; i++) { + const t = (evDay[i] as number) + k; + const r = + ((entitySeriesArr[evEnt[i] as number] as NumericSeries)[t] as number) - + (benchmarkReturns[t] as number); + arBuf[i] = r; + runningCar[i] = (runningCar[i] as number) + r; + const next = aarSum + r; + if (Math.abs(aarSum) >= Math.abs(r)) { + aarComp += aarSum - next + r; + } else { + aarComp += r - next + aarSum; + } + aarSum = next; + } + } + } else if (k >= 0) { + for (let i = 0; i < M; i++) { + const t = (evDay[i] as number) + k; + const r = (entitySeriesArr[evEnt[i] as number] as NumericSeries)[t] as number; + arBuf[i] = r; + runningCar[i] = (runningCar[i] as number) + r; + runningPostCar[i] = (runningPostCar[i] as number) + r; + const next = aarSum + r; + if (Math.abs(aarSum) >= Math.abs(r)) { + aarComp += aarSum - next + r; + } else { + aarComp += r - next + aarSum; + } + aarSum = next; + } + } else { + for (let i = 0; i < M; i++) { + const t = (evDay[i] as number) + k; + const r = (entitySeriesArr[evEnt[i] as number] as NumericSeries)[t] as number; + arBuf[i] = r; + runningCar[i] = (runningCar[i] as number) + r; + const next = aarSum + r; + if (Math.abs(aarSum) >= Math.abs(r)) { + aarComp += aarSum - next + r; + } else { + aarComp += r - next + aarSum; + } + aarSum = next; + } + } + + const aar = (aarSum + aarComp) / M; + + let sumSq = 0; + for (let i = 0; i < M; i++) { + const diff = (arBuf[i] as number) - aar; + sumSq += diff * diff; + } + const standardError = Math.sqrt(sumSq * invSeDenom); + + const nextCaar = caarSum + aar; + if (Math.abs(caarSum) >= Math.abs(aar)) { + caarComp += caarSum - nextCaar + aar; + } else { + caarComp += aar - nextCaar + caarSum; + } + caarSum = nextCaar; + const caar = caarSum + caarComp; + + let caarFromZero: number | null = null; + if (k >= 0) { + const nextZero = caarZeroSum + aar; + if (Math.abs(caarZeroSum) >= Math.abs(aar)) { + caarZeroComp += caarZeroSum - nextZero + aar; + } else { + caarZeroComp += aar - nextZero + caarZeroSum; + } + caarZeroSum = nextZero; + caarFromZero = caarZeroSum + caarZeroComp; + } + + sortBuf.set(runningCar); + const carPercentiles = computeR7Percentiles(sortBuf, M); + + let postCarPercentiles: EventStudyPercentiles | null = null; + if (k >= 0) { + sortBuf.set(runningPostCar); + postCarPercentiles = computeR7Percentiles(sortBuf, M); + } + + offsets[w] = { + offset: k, + n: M, + aar, + standardError, + caar, + caarFromZero, + carPercentiles, + postCarPercentiles, + }; + } + + // Columnar per-event CAR[0..postDays] in canonical (dayIndex ASC, entityId ASC) order. + const eventEntityIds: EntityId[] = new Array(M); + const eventDates: string[] = new Array(M); + const eventDayIndices = evDay.length === M ? evDay : evDay.slice(0, M); + for (let i = 0; i < M; i++) { + eventEntityIds[i] = canonicalEntityIds[evEnt[i] as number] as EntityId; + eventDates[i] = sessionDates[eventDayIndices[i] as number] as string; + } + + const eventCars: EventCarSeries = { + entityIds: eventEntityIds, + dayIndices: eventDayIndices, + dates: eventDates, + cars: runningPostCar, + }; + + // Cluster per-event CAR[0..postDays] by event session date. + const clusteredDates: string[] = new Array(nDates); + const clusteredCounts = new Int32Array(nDates); + const clusteredMeanCars = new Float64Array(nDates); + + let clusterIdx = 0; + let pos = 0; + let totalClusterSum = 0; + let totalClusterComp = 0; + while (pos < M) { + const d = eventDayIndices[pos] as number; + let sum = 0; + let comp = 0; + let count = 0; + while (pos < M && (eventDayIndices[pos] as number) === d) { + const v = runningPostCar[pos] as number; + const next = sum + v; + if (Math.abs(sum) >= Math.abs(v)) { + comp += sum - next + v; + } else { + comp += v - next + sum; + } + sum = next; + count++; + pos++; + } + const meanCar = (sum + comp) / count; + clusteredDates[clusterIdx] = sessionDates[d] as string; + clusteredCounts[clusterIdx] = count; + clusteredMeanCars[clusterIdx] = meanCar; + + const nextTotal = totalClusterSum + meanCar; + if (Math.abs(totalClusterSum) >= Math.abs(meanCar)) { + totalClusterComp += totalClusterSum - nextTotal + meanCar; + } else { + totalClusterComp += meanCar - nextTotal + totalClusterSum; + } + totalClusterSum = nextTotal; + clusterIdx++; + } + + const carMean = (totalClusterSum + totalClusterComp) / nDates; + const neweyWest = neweyWestMeanTest(clusteredMeanCars, neweyWestLag); + + const clustered: DateClusteredCarResult = { + nDates, + dates: clusteredDates, + eventCounts: clusteredCounts, + meanCars: clusteredMeanCars, + carMean, + neweyWest, + }; + + // Sign-preserving recency gate reusing T-82's evaluateRecencyGate. + // Cohorts are split by event session date (`clusteredDates[i] < recencySplitDate` vs `>=`); + // each complete CAR[0..postDays] stays with its event date. Callers needing strictly disjoint + // return periods must pre-filter pre-split events whose post-event window reaches the split. + const rawRecency = evaluateRecencyGate(clusteredDates, clusteredMeanCars, { + recencySplitDate, + recencyMinRatio, + lag: neweyWestLag, + }); + + let gateSource = rawRecency.gate; + if (rawRecency.pre.mean !== null && rawRecency.pre.mean < 0) { + const negated = new Float64Array(nDates); + for (let i = 0; i < nDates; i++) { + negated[i] = -(clusteredMeanCars[i] as number); + } + const flippedRecency = evaluateRecencyGate(clusteredDates, negated, { + recencySplitDate, + recencyMinRatio, + lag: neweyWestLag, + }); + gateSource = flippedRecency.gate; + } + + const recency: EventStudyRecencyResult = { + splitDate: rawRecency.splitDate, + minRatio: rawRecency.minRatio, + pre: rawRecency.pre, + post: rawRecency.post, + gate: { + pass: gateSource.pass, + reason: mapRecencyReason(gateSource.reason), + ratio: gateSource.ratio, + }, + }; + + return { + status: 'ok', + preDays, + postDays, + hasBenchmark, + offsets, + eventCars, + clustered, + recency, + diagnostics, + }; +} diff --git a/libs/calculations/src/analytics/index.ts b/libs/calculations/src/analytics/index.ts index 06e16349..39050ce3 100644 --- a/libs/calculations/src/analytics/index.ts +++ b/libs/calculations/src/analytics/index.ts @@ -4,3 +4,77 @@ export { factorStatistics, mean, returnStatistics, sampleDeviation } from './ret export { tradeStatistics } from './trade-statistics'; export type { TradeObservation } from './trade-statistics'; export { formatStatistic, performanceAnalysis } from './performance'; +export { + DSR_VALIDATION_GATE, + EULER_MASCHERONI, + deflatedSharpeRatio, + effectiveIndependentTrials, + inverseNormalCdf, + normalCdf, + passesDsrGate, + trialMoments, +} from './deflated-sharpe'; +export type { + DeflatedSharpeInput, + DeflatedSharpeResult, + EffectiveTrialsResult, + TrialMoments, +} from './deflated-sharpe'; +export { + DEFAULT_MIN_CROSS_SECTION, + DEFAULT_QUANTILE_COUNT, + RECENCY_MIN_RATIO, + RECENCY_SPLIT_DATE, + SignalAnalysisError, + analyzeSignalPanel, + crossSectionIc, + defaultNeweyWestLag, + evaluateRecencyGate, + neweyWestMeanTest, + summarizeIcSeries, +} from './signal-analysis'; +export type { + CrossSectionIcOptions, + CrossSectionIcResult, + EntityId, + EntityIdSeries, + IcSummary, + IcSummaryOptions, + NeweyWestResult, + NumericSeries, + QuantileSpreadResult, + RecencyGateOptions, + RecencyGateReason, + RecencyGateResult, + RecencySplitResult, + SignalAnalysisErrorCode, + SignalAnalysisOptions, + SignalCrossSection, + SignalPanelAnalysis, + SignalPanelDiagnostics, + TurnoverResult, +} from './signal-analysis'; +export { + DEFAULT_EVENT_MIN_EVENTS, + DEFAULT_EVENT_POST_DAYS, + DEFAULT_EVENT_PRE_DAYS, + EventStudyError, + eventDayIndex, + eventStudy, +} from './event-study'; +export type { + DateClusteredCarResult, + EventCarSeries, + EventDayIndexResult, + EventStudyDiagnostics, + EventStudyErrorCode, + EventStudyEvent, + EventStudyInput, + EventStudyOffsetStats, + EventStudyOptions, + EventStudyPercentiles, + EventStudyRecencyGate, + EventStudyRecencyReason, + EventStudyRecencyResult, + EventStudyResult, +} from './event-study'; diff --git a/libs/calculations/src/analytics/signal-analysis.ts b/libs/calculations/src/analytics/signal-analysis.ts new file mode 100644 index 00000000..fa7ab4f3 --- /dev/null +++ b/libs/calculations/src/analytics/signal-analysis.ts @@ -0,0 +1,1450 @@ +/** + * Pure, zero-I/O cross-sectional signal analysis math per `design/PLATFORM-PLAN.md` + * and `design/VALIDATION-AND-RIGOR.md` §3. + * + * Covers: + * - Per-date Pearson IC and Spearman rank-IC (average ranks for ties) + * - Newey-West HAC t-statistic of the mean (Bartlett kernel, finite-sample scaling) + * - Deterministic-tie-break quantile bucket returns and top-minus-bottom spreads + * - Consecutive-date top/bottom quantile membership turnover + * - Pre/post-2023 recency split & gate with optional exclusive `vaultCutoffDate` fence + * + * Pure stateless math: zero I/O, zero wall-clock or random calls, reusable typed-array + * scratch buffers on the panel hot path. + * + * Local benchmark (fixed seed `20260402`, `5,040` dates x `3,000` names = `15,120,000` + * observations, covering full `analyzeSignalPanel`): + * - Command: `bun run libs/calculations/scripts/benchmark-signal-analysis.ts` + * - Observed (Bun 1.2.16, 2 runs): `1,779.96 ms` (`8,494,557 observations/s`) and + * `1,809.95 ms` (`8,353,819 observations/s`). + */ + +/** Default minimum finite cross-sectional pairs required to compute per-date IC. */ +export const DEFAULT_MIN_CROSS_SECTION = 5; + +/** Default number of signal quantile buckets (quintiles). */ +export const DEFAULT_QUANTILE_COUNT = 5; + +/** Canonical recency split boundary (`pre < 2023-01-01`, `post >= 2023-01-01`). */ +export const RECENCY_SPLIT_DATE = '2023-01-01'; + +/** Canonical minimum post/pre mean rank-IC ratio required to pass the recency gate. */ +export const RECENCY_MIN_RATIO = 0.5; + +/** Machine-readable error codes thrown by {@link SignalAnalysisError}. */ +export type SignalAnalysisErrorCode = + | 'LENGTH_MISMATCH' + | 'UNSORTED_DATES' + | 'DUPLICATE_DATE' + | 'DUPLICATE_ID' + | 'INVALID_ID' + | 'INVALID_DATE' + | 'INVALID_OPTION'; + +/** Typed validation error thrown for malformed signal panels or invalid options. */ +export class SignalAnalysisError extends RangeError { + readonly code: SignalAnalysisErrorCode; + + constructor(code: SignalAnalysisErrorCode, message: string) { + super(message); + this.name = 'SignalAnalysisError'; + this.code = code; + } +} + +/** Numeric vector accepted by signal-analysis routines (prefers `Float64Array` on hot paths). */ +export type NumericSeries = Float64Array | readonly number[]; + +/** Cross-sectional entity identifier used for deterministic tie-breaking and turnover. */ +export type EntityId = number | string; + +/** Entity identifier vector aligned index-for-index with a cross-section's signal and return. */ +export type EntityIdSeries = readonly EntityId[] | Int32Array | Uint32Array; + +/** Single date cross-section in a date-ordered signal panel. */ +export interface SignalCrossSection { + readonly date: string; + readonly ids: EntityIdSeries; + readonly signal: NumericSeries; + readonly forwardReturn: NumericSeries; +} + +/** Options for {@link crossSectionIc}. */ +export interface CrossSectionIcOptions { + readonly minCrossSection?: number; +} + +/** Options for {@link summarizeIcSeries}. */ +export interface IcSummaryOptions { + readonly lag?: number; +} + +/** Options for {@link evaluateRecencyGate}. */ +export interface RecencyGateOptions { + readonly lag?: number; + readonly recencySplitDate?: string; + readonly recencyMinRatio?: number; + readonly vaultCutoffDate?: string; +} + +/** Options for {@link analyzeSignalPanel}. */ +export interface SignalAnalysisOptions { + readonly minCrossSection?: number; + readonly quantiles?: number; + readonly lag?: number; + readonly recencySplitDate?: string; + readonly recencyMinRatio?: number; + readonly vaultCutoffDate?: string; +} + +/** Output of {@link neweyWestMeanTest}. Never emits `NaN`. */ +export type NeweyWestResult = + | { + readonly status: 'ok'; + readonly lag: number; + readonly standardError: number; + readonly tStat: number; + readonly longRunVariance: number; + } + | { + readonly status: 'insufficient_data'; + readonly reason: 'too_few_observations' | 'non_positive_variance'; + readonly lag: number | null; + }; + +/** Time-series summary statistics for an IC or spread series. */ +export interface IcSummary { + readonly count: number; + readonly mean: number | null; + readonly std: number | null; + readonly icir: number | null; + readonly hitRate: number | null; + readonly neweyWest: NeweyWestResult; +} + +/** Output of {@link crossSectionIc} for a single date. */ +export type CrossSectionIcResult = + | { + readonly status: 'ok'; + readonly validCount: number; + readonly droppedPairs: number; + readonly pearsonIc: number; + readonly rankIc: number; + } + | { + readonly status: 'skipped'; + readonly reason: 'below_min_cross_section' | 'zero_variance'; + readonly validCount: number; + readonly droppedPairs: number; + }; + +/** Per-quantile equal-weight forward return series and top-minus-bottom spread summary. */ +export interface QuantileSpreadResult { + readonly quantiles: number; + readonly validDates: number; + readonly skippedDates: number; + readonly dates: readonly string[]; + readonly bucketMeanReturns: readonly (number | null)[]; + readonly perBucketSeries: readonly Float64Array[]; + readonly spreadSeries: Float64Array; + readonly spreadSummary: IcSummary; +} + +/** Consecutive-date membership turnover for the top and bottom signal quantiles. */ +export interface TurnoverResult { + readonly count: number; + readonly dates: readonly string[]; + readonly topSeries: Float64Array; + readonly bottomSeries: Float64Array; + readonly meanTopTurnover: number | null; + readonly meanBottomTurnover: number | null; +} + +/** Explicit reason describing why the recency gate passed or failed. */ +export type RecencyGateReason = + | 'passed' + | 'empty_pre_window' + | 'empty_post_window' + | 'non_positive_pre_mean' + | 'non_positive_post_mean' + | 'post_below_ratio_threshold'; + +/** Pass/fail outcome of the post-2023 recency gate. */ +export interface RecencyGateResult { + readonly pass: boolean; + readonly reason: RecencyGateReason; + readonly ratio: number | null; +} + +/** Pre/post recency split summaries, vault exclusion count, and gate decision. */ +export interface RecencySplitResult { + readonly splitDate: string; + readonly minRatio: number; + readonly vaultCutoffDate: string | null; + readonly vaultExcludedDates: number; + readonly pre: IcSummary; + readonly post: IcSummary; + readonly gate: RecencyGateResult; +} + +/** Observation and date-level accounting across the analyzed panel. */ +export interface SignalPanelDiagnostics { + readonly totalDates: number; + readonly eligibleDates: number; + readonly vaultExcludedDates: number; + readonly totalObservations: number; + readonly validObservations: number; + readonly droppedPairs: number; + readonly icValidDates: number; + readonly icSkippedBelowMin: number; + readonly icSkippedZeroVariance: number; + readonly quantileValidDates: number; + readonly quantileSkippedDates: number; +} + +/** Full cross-sectional signal analysis result returned by {@link analyzeSignalPanel}. */ +export interface SignalPanelAnalysis { + readonly dates: readonly string[]; + readonly pearsonIcSeries: Float64Array; + readonly rankIcSeries: Float64Array; + readonly pearsonIc: IcSummary; + readonly rankIc: IcSummary; + readonly quantiles: QuantileSpreadResult; + readonly turnover: TurnoverResult; + readonly recency: RecencySplitResult; + readonly diagnostics: SignalPanelDiagnostics; +} + +const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; +const RECENCY_ZERO_TOLERANCE_ULPS = 16; +const FAST_ID_EPOCH_LIMIT = 65536; + +interface CompensatedSumResult { + readonly sum: number; + readonly absSum: number; +} + +function compensatedSum(series: NumericSeries): CompensatedSumResult { + let sum = 0; + let compensation = 0; + let absSum = 0; + for (let i = 0; i < series.length; i++) { + const v = series[i] as number; + const t = sum + v; + if (Math.abs(sum) >= Math.abs(v)) { + compensation += sum - t + v; + } else { + compensation += v - t + sum; + } + sum = t; + absSum += Math.abs(v); + } + return { sum: sum + compensation, absSum }; +} + +function zeroToleranceForMean(absSum: number, count: number): number { + if (count <= 0 || absSum <= 0) { + return 0; + } + return RECENCY_ZERO_TOLERANCE_ULPS * Number.EPSILON * (absSum / count); +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function assertIsoDate(value: string, label: string): void { + if (typeof value !== 'string' || !ISO_DATE_RE.test(value)) { + throw new SignalAnalysisError('INVALID_DATE', `${label} must be a valid YYYY-MM-DD date`); + } + const year = Number(value.slice(0, 4)); + const month = Number(value.slice(5, 7)); + const day = Number(value.slice(8, 10)); + if (month < 1 || month > 12) { + throw new SignalAnalysisError('INVALID_DATE', `${label} has invalid month: ${value}`); + } + const baseDays = DAYS_IN_MONTH[month] ?? 0; + const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays; + if (day < 1 || day > maxDay) { + throw new SignalAnalysisError('INVALID_DATE', `${label} is not a valid calendar date: ${value}`); + } +} + +function assertIntegerOption(value: number, min: number, label: string): void { + if (typeof value !== 'number' || !Number.isInteger(value) || value < min) { + throw new SignalAnalysisError( + 'INVALID_OPTION', + `${label} must be an integer >= ${min}, received ${String(value)}` + ); + } +} + +function assertPositiveFiniteOption(value: number, label: string): void { + if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) { + throw new SignalAnalysisError( + 'INVALID_OPTION', + `${label} must be a finite number > 0, received ${String(value)}` + ); + } +} + +interface PanelScratch { + capacity: number; + validIdx: Int32Array; + validSignal: Float64Array; + validReturn: Float64Array; + orderSignal: Int32Array; + orderReturn: Int32Array; + sortScratch: Int32Array; + rankSignal: Float64Array; + rankReturn: Float64Array; +} + +function createPanelScratch(initialCapacity: number): PanelScratch { + const cap = initialCapacity > 0 ? initialCapacity : 1; + return { + capacity: cap, + validIdx: new Int32Array(cap), + validSignal: new Float64Array(cap), + validReturn: new Float64Array(cap), + orderSignal: new Int32Array(cap), + orderReturn: new Int32Array(cap), + sortScratch: new Int32Array(cap), + rankSignal: new Float64Array(cap), + rankReturn: new Float64Array(cap), + }; +} + +function compareIds(a: EntityId, b: EntityId): number { + const typeA = typeof a; + const typeB = typeof b; + if (typeA === typeB) { + return a < b ? -1 : a > b ? 1 : 0; + } + return typeA === 'number' ? -1 : 1; +} + +const INSERTION_RUN = 16; + +function sortOrderByFloat( + order: Int32Array, + values: Float64Array, + length: number, + scratch: Int32Array +): void { + if (length <= 1) { + return; + } + + for (let start = 0; start < length; start += INSERTION_RUN) { + const end = start + INSERTION_RUN < length ? start + INSERTION_RUN : length; + for (let i = start + 1; i < end; i++) { + const idx = order[i] as number; + const val = values[idx] as number; + let j = i - 1; + while (j >= start) { + const prevIdx = order[j] as number; + if ((values[prevIdx] as number) <= val) { + break; + } + order[j + 1] = prevIdx; + j--; + } + order[j + 1] = idx; + } + } + + let src = order; + let dst = scratch; + for (let width = INSERTION_RUN; width < length; width <<= 1) { + const step = width << 1; + for (let left = 0; left < length; left += step) { + const mid = left + width < length ? left + width : length; + const right = left + step < length ? left + step : length; + let i = left; + let j = mid; + let k = left; + while (i < mid && j < right) { + const li = src[i] as number; + const rj = src[j] as number; + if ((values[li] as number) <= (values[rj] as number)) { + dst[k++] = li; + i++; + } else { + dst[k++] = rj; + j++; + } + } + while (i < mid) { + dst[k++] = src[i++] as number; + } + while (j < right) { + dst[k++] = src[j++] as number; + } + } + const tmp = src; + src = dst; + dst = tmp; + } + + if (src !== order) { + for (let i = 0; i < length; i++) { + order[i] = src[i] as number; + } + } +} + +function sortOrderBySignalAndId( + order: Int32Array, + values: Float64Array, + validIdx: Int32Array, + ids: EntityIdSeries, + length: number, + scratch: Int32Array +): void { + if (length <= 1) { + return; + } + + for (let start = 0; start < length; start += INSERTION_RUN) { + const end = start + INSERTION_RUN < length ? start + INSERTION_RUN : length; + for (let i = start + 1; i < end; i++) { + const idx = order[i] as number; + const val = values[idx] as number; + let j = i - 1; + while (j >= start) { + const prevIdx = order[j] as number; + const prevVal = values[prevIdx] as number; + if ( + prevVal < val || + (prevVal === val && + compareIds( + ids[validIdx[prevIdx] as number] as EntityId, + ids[validIdx[idx] as number] as EntityId + ) <= 0) + ) { + break; + } + order[j + 1] = prevIdx; + j--; + } + order[j + 1] = idx; + } + } + + let src = order; + let dst = scratch; + for (let width = INSERTION_RUN; width < length; width <<= 1) { + const step = width << 1; + for (let left = 0; left < length; left += step) { + const mid = left + width < length ? left + width : length; + const right = left + step < length ? left + step : length; + let i = left; + let j = mid; + let k = left; + while (i < mid && j < right) { + const li = src[i] as number; + const rj = src[j] as number; + const va = values[li] as number; + const vb = values[rj] as number; + if ( + va < vb || + (va === vb && + compareIds( + ids[validIdx[li] as number] as EntityId, + ids[validIdx[rj] as number] as EntityId + ) <= 0) + ) { + dst[k++] = li; + i++; + } else { + dst[k++] = rj; + j++; + } + } + while (i < mid) { + dst[k++] = src[i++] as number; + } + while (j < right) { + dst[k++] = src[j++] as number; + } + } + const tmp = src; + src = dst; + dst = tmp; + } + + if (src !== order) { + for (let i = 0; i < length; i++) { + order[i] = src[i] as number; + } + } +} + +function assignAverageRanks( + order: Int32Array, + values: Float64Array, + ranksOut: Float64Array, + length: number +): void { + let i = 0; + while (i < length) { + const val = values[order[i] as number] as number; + let j = i + 1; + while (j < length && (values[order[j] as number] as number) === val) { + j++; + } + const midRank = (i + (j - 1)) * 0.5; + for (let k = i; k < j; k++) { + ranksOut[order[k] as number] = midRank; + } + i = j; + } +} + +function twoPassPearson(x: Float64Array, y: Float64Array, length: number): number | null { + if (length < 2) { + return null; + } + + let sumX = 0; + let sumY = 0; + const firstX = x[0] as number; + const firstY = y[0] as number; + let allEqualX = true; + let allEqualY = true; + + for (let i = 0; i < length; i++) { + const vx = x[i] as number; + const vy = y[i] as number; + sumX += vx; + sumY += vy; + if (vx !== firstX) { + allEqualX = false; + } + if (vy !== firstY) { + allEqualY = false; + } + } + + if (allEqualX || allEqualY) { + return null; + } + + const meanX = sumX / length; + const meanY = sumY / length; + if (!Number.isFinite(meanX) || !Number.isFinite(meanY)) { + return null; + } + + let cov = 0; + let varX = 0; + let varY = 0; + for (let i = 0; i < length; i++) { + const dx = (x[i] as number) - meanX; + const dy = (y[i] as number) - meanY; + cov += dx * dy; + varX += dx * dx; + varY += dy * dy; + } + + if (!Number.isFinite(varX) || !Number.isFinite(varY) || varX <= 0 || varY <= 0) { + return null; + } + + const denom = Math.sqrt(varX * varY); + if (!Number.isFinite(denom) || denom <= 0) { + return null; + } + + const rho = cov / denom; + if (!Number.isFinite(rho)) { + return null; + } + + return rho < -1 ? -1 : rho > 1 ? 1 : rho; +} + +function twoPassPearsonOrdered( + x: Float64Array, + y: Float64Array, + order: Int32Array, + length: number +): number | null { + if (length < 2) { + return null; + } + + let sumX = 0; + let sumY = 0; + const firstIdx = order[0] as number; + const firstX = x[firstIdx] as number; + const firstY = y[firstIdx] as number; + let allEqualX = true; + let allEqualY = true; + + for (let k = 0; k < length; k++) { + const idx = order[k] as number; + const vx = x[idx] as number; + const vy = y[idx] as number; + sumX += vx; + sumY += vy; + if (vx !== firstX) { + allEqualX = false; + } + if (vy !== firstY) { + allEqualY = false; + } + } + + if (allEqualX || allEqualY) { + return null; + } + + const meanX = sumX / length; + const meanY = sumY / length; + if (!Number.isFinite(meanX) || !Number.isFinite(meanY)) { + return null; + } + + let cov = 0; + let varX = 0; + let varY = 0; + for (let k = 0; k < length; k++) { + const idx = order[k] as number; + const dx = (x[idx] as number) - meanX; + const dy = (y[idx] as number) - meanY; + cov += dx * dy; + varX += dx * dx; + varY += dy * dy; + } + + if (!Number.isFinite(varX) || !Number.isFinite(varY) || varX <= 0 || varY <= 0) { + return null; + } + + const denom = Math.sqrt(varX * varY); + if (!Number.isFinite(denom) || denom <= 0) { + return null; + } + + const rho = cov / denom; + if (!Number.isFinite(rho)) { + return null; + } + + return rho < -1 ? -1 : rho > 1 ? 1 : rho; +} + +/** + * Computes single-date Pearson IC and Spearman rank-IC (using average ranks for ties) + * between `signal` and `forwardReturn`. + * + * Pairs where either value is non-finite are dropped and counted in `droppedPairs`. + * Dates with fewer than `minCrossSection` (default 5) valid pairs or zero variance on + * either side return `{ status: 'skipped', ... }` rather than `NaN`. + */ +export function crossSectionIc( + signal: NumericSeries, + forwardReturn: NumericSeries, + options?: CrossSectionIcOptions +): CrossSectionIcResult { + const minCrossSection = options?.minCrossSection ?? DEFAULT_MIN_CROSS_SECTION; + assertIntegerOption(minCrossSection, 2, 'minCrossSection'); + + const n = signal.length; + if (n !== forwardReturn.length) { + throw new SignalAnalysisError( + 'LENGTH_MISMATCH', + `signal length (${n}) does not match forwardReturn length (${forwardReturn.length})` + ); + } + + const validSignal = new Float64Array(n); + const validReturn = new Float64Array(n); + let m = 0; + for (let i = 0; i < n; i++) { + const s = signal[i]; + const r = forwardReturn[i]; + if (typeof s === 'number' && typeof r === 'number' && Number.isFinite(s) && Number.isFinite(r)) { + validSignal[m] = s; + validReturn[m] = r; + m++; + } + } + + const droppedPairs = n - m; + if (m < minCrossSection) { + return { + status: 'skipped', + reason: 'below_min_cross_section', + validCount: m, + droppedPairs, + }; + } + + const pearsonIc = twoPassPearson(validSignal, validReturn, m); + if (pearsonIc === null) { + return { + status: 'skipped', + reason: 'zero_variance', + validCount: m, + droppedPairs, + }; + } + + const orderSignal = new Int32Array(m); + const orderReturn = new Int32Array(m); + const sortScratch = new Int32Array(m); + for (let i = 0; i < m; i++) { + orderSignal[i] = i; + orderReturn[i] = i; + } + + sortOrderByFloat(orderSignal, validSignal, m, sortScratch); + sortOrderByFloat(orderReturn, validReturn, m, sortScratch); + + const rankSignal = new Float64Array(m); + const rankReturn = new Float64Array(m); + assignAverageRanks(orderSignal, validSignal, rankSignal, m); + assignAverageRanks(orderReturn, validReturn, rankReturn, m); + + const rankIc = twoPassPearson(rankSignal, rankReturn, m); + if (rankIc === null) { + return { + status: 'skipped', + reason: 'zero_variance', + validCount: m, + droppedPairs, + }; + } + + return { + status: 'ok', + validCount: m, + droppedPairs, + pearsonIc, + rankIc, + }; +} + +/** + * Default Newey-West (1994) Bartlett bandwidth: `floor(4 * (T / 100)^(2/9))`. + * Returns `0` for `nObs < 2`. + */ +export function defaultNeweyWestLag(nObs: number): number { + if (!Number.isFinite(nObs) || nObs < 2) { + return 0; + } + return Math.floor(4 * Math.pow(nObs / 100, 2 / 9)); +} + +/** + * Newey-West HAC test of the mean using the Bartlett kernel and finite-sample + * `1 / (T - 1)` autocovariance scaling so `lag = 0` matches the plain Student t-stat + * `mean / (sampleStd / sqrt(T))` exactly. + * + * Returns a typed `insufficient_data` result rather than `NaN` when `T < 2` or + * the estimated long-run variance is non-positive / non-finite. + */ +export function neweyWestMeanTest(series: NumericSeries, lag?: number): NeweyWestResult { + if (lag !== undefined) { + assertIntegerOption(lag, 0, 'lag'); + } + + const n = series.length; + if (n < 2) { + return { + status: 'insufficient_data', + reason: 'too_few_observations', + lag: null, + }; + } + + const resolvedLag = lag ?? defaultNeweyWestLag(n); + let sum = 0; + let compensation = 0; + const first = series[0] as number; + let allEqual = true; + for (let t = 0; t < n; t++) { + const v = series[t] as number; + if (!Number.isFinite(v)) { + return { + status: 'insufficient_data', + reason: 'non_positive_variance', + lag: resolvedLag, + }; + } + const next = sum + v; + if (Math.abs(sum) >= Math.abs(v)) { + compensation += sum - next + v; + } else { + compensation += v - next + sum; + } + sum = next; + if (v !== first) { + allEqual = false; + } + } + + const avg = (sum + compensation) / n; + if (!Number.isFinite(avg) || allEqual) { + return { + status: 'insufficient_data', + reason: 'non_positive_variance', + lag: resolvedLag, + }; + } + + const residuals = new Float64Array(n); + let sumSq = 0; + for (let t = 0; t < n; t++) { + const e = (series[t] as number) - avg; + residuals[t] = e; + sumSq += e * e; + } + + const invDof = 1 / (n - 1); + let longRunVariance = sumSq * invDof; + const maxLag = resolvedLag < n - 1 ? resolvedLag : n - 1; + for (let l = 1; l <= maxLag; l++) { + let cov = 0; + for (let t = l; t < n; t++) { + cov += (residuals[t] as number) * (residuals[t - l] as number); + } + const gamma = cov * invDof; + const weight = 1 - l / (resolvedLag + 1); + longRunVariance += 2 * weight * gamma; + } + + if (!Number.isFinite(longRunVariance) || longRunVariance <= 0) { + return { + status: 'insufficient_data', + reason: 'non_positive_variance', + lag: resolvedLag, + }; + } + + const standardError = Math.sqrt(longRunVariance / n); + if (!Number.isFinite(standardError) || standardError <= 0) { + return { + status: 'insufficient_data', + reason: 'non_positive_variance', + lag: resolvedLag, + }; + } + + const tStat = avg / standardError; + if (!Number.isFinite(tStat)) { + return { + status: 'insufficient_data', + reason: 'non_positive_variance', + lag: resolvedLag, + }; + } + + return { + status: 'ok', + lag: resolvedLag, + standardError, + tStat, + longRunVariance, + }; +} + +interface IcSummaryWithAbsSum { + readonly summary: IcSummary; + readonly absSum: number; +} + +function summarizeIcSeriesInternal( + series: NumericSeries, + lag: number | undefined +): IcSummaryWithAbsSum { + const n = series.length; + if (n === 0) { + return { + summary: { + count: 0, + mean: null, + std: null, + icir: null, + hitRate: null, + neweyWest: { + status: 'insufficient_data', + reason: 'too_few_observations', + lag: null, + }, + }, + absSum: 0, + }; + } + + const { sum, absSum } = compensatedSum(series); + let hits = 0; + const first = series[0] as number; + let allEqual = true; + for (let i = 0; i < n; i++) { + const v = series[i] as number; + if (v > 0) { + hits++; + } + if (v !== first) { + allEqual = false; + } + } + + const avg = sum / n; + const hitRate = hits / n; + if (n < 2) { + return { + summary: { + count: n, + mean: Number.isFinite(avg) ? avg : null, + std: null, + icir: null, + hitRate, + neweyWest: { + status: 'insufficient_data', + reason: 'too_few_observations', + lag: null, + }, + }, + absSum, + }; + } + + let std: number | null; + if (allEqual) { + std = 0; + } else { + let sumSq = 0; + for (let i = 0; i < n; i++) { + const d = (series[i] as number) - avg; + sumSq += d * d; + } + const variance = sumSq / (n - 1); + std = Number.isFinite(variance) && variance >= 0 ? Math.sqrt(variance) : null; + } + + const icir = + std !== null && std > 0 && Number.isFinite(avg / std) ? avg / std : null; + + return { + summary: { + count: n, + mean: Number.isFinite(avg) ? avg : null, + std, + icir, + hitRate, + neweyWest: neweyWestMeanTest(series, lag), + }, + absSum, + }; +} + +/** + * Summarizes an IC or spread time series with count, mean, sample standard deviation + * (`n - 1` dof), ICIR (`mean / std`), hit rate (fraction strictly `> 0`), and + * Newey-West HAC t-statistic. + */ +export function summarizeIcSeries(series: NumericSeries, options?: IcSummaryOptions): IcSummary { + const lag = options?.lag; + if (lag !== undefined) { + assertIntegerOption(lag, 0, 'lag'); + } + return summarizeIcSeriesInternal(series, lag).summary; +} + +function buildRecencySplitResult( + dates: readonly string[], + rankIc: NumericSeries, + splitDate: string, + minRatio: number, + vaultCutoffDate: string | null, + vaultExcludedDates: number, + lag: number | undefined +): RecencySplitResult { + const preValues: number[] = []; + const postValues: number[] = []; + for (let i = 0; i < dates.length; i++) { + const d = dates[i] as string; + const v = rankIc[i] as number; + if (d < splitDate) { + preValues.push(v); + } else { + postValues.push(v); + } + } + + const preStats = summarizeIcSeriesInternal(Float64Array.from(preValues), lag); + const postStats = summarizeIcSeriesInternal(Float64Array.from(postValues), lag); + const pre = preStats.summary; + const post = postStats.summary; + + const preTol = zeroToleranceForMean(preStats.absSum, pre.count); + const postTol = zeroToleranceForMean(postStats.absSum, post.count); + + let gate: RecencyGateResult; + if (pre.count === 0 || pre.mean === null) { + gate = { pass: false, reason: 'empty_pre_window', ratio: null }; + } else if (post.count === 0 || post.mean === null) { + gate = { pass: false, reason: 'empty_post_window', ratio: null }; + } else if (pre.mean <= preTol) { + gate = { pass: false, reason: 'non_positive_pre_mean', ratio: null }; + } else { + const ratio = post.mean / pre.mean; + const ratioThresholdTol = postTol + minRatio * preTol; + if (post.mean <= postTol) { + gate = { pass: false, reason: 'non_positive_post_mean', ratio }; + } else if (post.mean < minRatio * pre.mean - ratioThresholdTol) { + gate = { pass: false, reason: 'post_below_ratio_threshold', ratio }; + } else { + gate = { pass: true, reason: 'passed', ratio }; + } + } + + return { + splitDate, + minRatio, + vaultCutoffDate, + vaultExcludedDates, + pre, + post, + gate, + }; +} + +/** + * Splits a date-ordered rank-IC series into `pre` (`date < recencySplitDate`) and + * `post` (`date >= recencySplitDate`, default `2023-01-01`), optionally excluding + * dates `>= vaultCutoffDate`, and evaluates the recency gate. + * + * Passing requires `pre.mean > 0`, `post.mean > 0`, and + * `post.mean >= recencyMinRatio * pre.mean` (default `0.5`). + */ +export function evaluateRecencyGate( + dates: readonly string[], + rankIc: NumericSeries, + options?: RecencyGateOptions +): RecencySplitResult { + const splitDate = options?.recencySplitDate ?? RECENCY_SPLIT_DATE; + const minRatio = options?.recencyMinRatio ?? RECENCY_MIN_RATIO; + const vaultCutoffDate = options?.vaultCutoffDate; + const lag = options?.lag; + + assertIsoDate(splitDate, 'recencySplitDate'); + assertPositiveFiniteOption(minRatio, 'recencyMinRatio'); + if (vaultCutoffDate !== undefined) { + assertIsoDate(vaultCutoffDate, 'vaultCutoffDate'); + } + if (lag !== undefined) { + assertIntegerOption(lag, 0, 'lag'); + } + + if (dates.length !== rankIc.length) { + throw new SignalAnalysisError( + 'LENGTH_MISMATCH', + `dates length (${dates.length}) does not match rankIc length (${rankIc.length})` + ); + } + + let eligibleCount = 0; + for (let i = 0; i < dates.length; i++) { + const d = dates[i] as string; + assertIsoDate(d, `dates[${i}]`); + if (i > 0) { + const prev = dates[i - 1] as string; + if (d === prev) { + throw new SignalAnalysisError('DUPLICATE_DATE', `Duplicate date at index ${i}: ${d}`); + } + if (d < prev) { + throw new SignalAnalysisError( + 'UNSORTED_DATES', + `Dates must be strictly ascending: ${prev} followed by ${d} at index ${i}` + ); + } + } + if (vaultCutoffDate === undefined || d < vaultCutoffDate) { + eligibleCount++; + } + } + + const vaultExcludedDates = dates.length - eligibleCount; + const eligibleDates = eligibleCount === dates.length ? dates : dates.slice(0, eligibleCount); + const eligibleRankIc = + eligibleCount === rankIc.length + ? rankIc + : rankIc instanceof Float64Array + ? rankIc.subarray(0, eligibleCount) + : rankIc.slice(0, eligibleCount); + + return buildRecencySplitResult( + eligibleDates, + eligibleRankIc, + splitDate, + minRatio, + vaultCutoffDate ?? null, + vaultExcludedDates, + lag + ); +} + +function meanFloat64(series: Float64Array): number | null { + const n = series.length; + if (n === 0) { + return null; + } + const avg = compensatedSum(series).sum / n; + return Number.isFinite(avg) ? avg : null; +} + +function trimFloat64(buffer: Float64Array, length: number): Float64Array { + return length === buffer.length ? buffer : buffer.slice(0, length); +} + +/** + * Runs the full cross-sectional signal analysis over a date-ordered panel: + * per-date Pearson & Spearman rank-IC, IC summaries with Newey-West HAC t-stats, + * deterministic-tie-break quantile bucket returns & top-minus-bottom spreads, + * consecutive-date top/bottom quantile turnover, and the pre/post-2023 recency gate + * with optional exclusive `vaultCutoffDate` exclusion. + */ +export function analyzeSignalPanel( + panel: readonly SignalCrossSection[], + options?: SignalAnalysisOptions +): SignalPanelAnalysis { + const minCrossSection = options?.minCrossSection ?? DEFAULT_MIN_CROSS_SECTION; + const q = options?.quantiles ?? DEFAULT_QUANTILE_COUNT; + const lag = options?.lag; + const splitDate = options?.recencySplitDate ?? RECENCY_SPLIT_DATE; + const minRatio = options?.recencyMinRatio ?? RECENCY_MIN_RATIO; + const vaultCutoffDate = options?.vaultCutoffDate; + + assertIntegerOption(minCrossSection, 2, 'minCrossSection'); + assertIntegerOption(q, 2, 'quantiles'); + if (lag !== undefined) { + assertIntegerOption(lag, 0, 'lag'); + } + assertIsoDate(splitDate, 'recencySplitDate'); + assertPositiveFiniteOption(minRatio, 'recencyMinRatio'); + if (vaultCutoffDate !== undefined) { + assertIsoDate(vaultCutoffDate, 'vaultCutoffDate'); + } + + let eligibleDates = 0; + let maxCrossSectionLen = 0; + + for (let t = 0; t < panel.length; t++) { + const slice = panel[t] as SignalCrossSection; + assertIsoDate(slice.date, `panel[${t}].date`); + if (t > 0) { + const prevDate = (panel[t - 1] as SignalCrossSection).date; + if (slice.date === prevDate) { + throw new SignalAnalysisError( + 'DUPLICATE_DATE', + `Duplicate date at panel index ${t}: ${slice.date}` + ); + } + if (slice.date < prevDate) { + throw new SignalAnalysisError( + 'UNSORTED_DATES', + `Panel dates must be strictly ascending: ${prevDate} followed by ${slice.date} at index ${t}` + ); + } + } + + const nIds = slice.ids.length; + const nSig = slice.signal.length; + const nRet = slice.forwardReturn.length; + if (nIds !== nSig || nSig !== nRet) { + throw new SignalAnalysisError( + 'LENGTH_MISMATCH', + `Cross-section length mismatch on ${slice.date}: ids=${nIds}, signal=${nSig}, forwardReturn=${nRet}` + ); + } + + if (vaultCutoffDate === undefined || slice.date < vaultCutoffDate) { + eligibleDates++; + if (nSig > maxCrossSectionLen) { + maxCrossSectionLen = nSig; + } + } + } + + const vaultExcludedDates = panel.length - eligibleDates; + const scratch = createPanelScratch(maxCrossSectionLen); + + const icDates: string[] = []; + const pearsonIcBuf = new Float64Array(eligibleDates); + const rankIcBuf = new Float64Array(eligibleDates); + + const quantileDates: string[] = []; + const perBucketBufs: Float64Array[] = new Array(q); + for (let b = 0; b < q; b++) { + perBucketBufs[b] = new Float64Array(eligibleDates); + } + const spreadBuf = new Float64Array(eligibleDates); + + const turnoverCap = eligibleDates > 1 ? eligibleDates - 1 : 0; + const turnoverDates: string[] = []; + const topTurnoverBuf = new Float64Array(turnoverCap); + const bottomTurnoverBuf = new Float64Array(turnoverCap); + + let prevTop = new Set(); + let currTop = new Set(); + let prevBottom = new Set(); + let currBottom = new Set(); + const seenEpoch = new Int32Array(FAST_ID_EPOCH_LIMIT); + const seenIds = new Set(); + let idEpoch = 0; + + let totalObservations = 0; + let validObservations = 0; + let droppedPairs = 0; + let icCount = 0; + let icSkippedBelowMin = 0; + let icSkippedZeroVariance = 0; + let quantileCount = 0; + let quantileSkippedDates = 0; + let turnoverCount = 0; + + const { + validIdx, + validSignal, + validReturn, + orderSignal, + orderReturn, + sortScratch, + rankSignal, + rankReturn, + } = scratch; + + for (let t = 0; t < eligibleDates; t++) { + const slice = panel[t] as SignalCrossSection; + const { ids, signal, forwardReturn } = slice; + const n = signal.length; + totalObservations += n; + + idEpoch++; + if (idEpoch === 0x7fffffff) { + seenEpoch.fill(0); + idEpoch = 1; + } + if (seenIds.size > 0) { + seenIds.clear(); + } + + let m = 0; + for (let i = 0; i < n; i++) { + const s = signal[i]; + const r = forwardReturn[i]; + if ( + typeof s === 'number' && + typeof r === 'number' && + Number.isFinite(s) && + Number.isFinite(r) + ) { + const id = ids[i] as EntityId; + if ( + typeof id === 'number' && + (id | 0) === id && + id >= 0 && + id < FAST_ID_EPOCH_LIMIT + ) { + if (seenEpoch[id] === idEpoch) { + throw new SignalAnalysisError( + 'DUPLICATE_ID', + `Duplicate entity id ${String(id)} on ${slice.date}` + ); + } + seenEpoch[id] = idEpoch; + } else { + if (typeof id === 'number' && Number.isNaN(id)) { + throw new SignalAnalysisError( + 'INVALID_ID', + `Entity id must not be NaN on ${slice.date} at index ${i}` + ); + } + if (seenIds.has(id)) { + throw new SignalAnalysisError( + 'DUPLICATE_ID', + `Duplicate entity id ${String(id)} on ${slice.date}` + ); + } + seenIds.add(id); + } + + validIdx[m] = i; + validSignal[m] = s; + validReturn[m] = r; + orderSignal[m] = m; + m++; + } + } + + validObservations += m; + droppedPairs += n - m; + + const needsIc = m >= minCrossSection; + const needsQuantiles = m >= q; + + if (needsIc || needsQuantiles) { + sortOrderBySignalAndId(orderSignal, validSignal, validIdx, ids, m, sortScratch); + } + + if (!needsIc) { + icSkippedBelowMin++; + } else { + const pearson = twoPassPearsonOrdered(validSignal, validReturn, orderSignal, m); + if (pearson === null) { + icSkippedZeroVariance++; + } else { + for (let i = 0; i < m; i++) { + orderReturn[i] = i; + } + sortOrderByFloat(orderReturn, validReturn, m, sortScratch); + assignAverageRanks(orderSignal, validSignal, rankSignal, m); + assignAverageRanks(orderReturn, validReturn, rankReturn, m); + + const rankIc = twoPassPearsonOrdered(rankSignal, rankReturn, orderSignal, m); + if (rankIc === null) { + icSkippedZeroVariance++; + } else { + icDates.push(slice.date); + pearsonIcBuf[icCount] = pearson; + rankIcBuf[icCount] = rankIc; + icCount++; + } + } + } + + if (!needsQuantiles) { + quantileSkippedDates++; + } else { + for (let b = 0; b < q; b++) { + const start = Math.floor((b * m) / q); + const end = Math.floor(((b + 1) * m) / q); + let bucketSum = 0; + for (let k = start; k < end; k++) { + bucketSum += validReturn[orderSignal[k] as number] as number; + } + (perBucketBufs[b] as Float64Array)[quantileCount] = bucketSum / (end - start); + } + + const bottomRet = (perBucketBufs[0] as Float64Array)[quantileCount] as number; + const topRet = (perBucketBufs[q - 1] as Float64Array)[quantileCount] as number; + spreadBuf[quantileCount] = topRet - bottomRet; + quantileDates.push(slice.date); + + currBottom.clear(); + const bottomEnd = Math.floor(m / q); + for (let k = 0; k < bottomEnd; k++) { + currBottom.add(ids[validIdx[orderSignal[k] as number] as number] as EntityId); + } + + currTop.clear(); + const topStart = Math.floor(((q - 1) * m) / q); + for (let k = topStart; k < m; k++) { + currTop.add(ids[validIdx[orderSignal[k] as number] as number] as EntityId); + } + + if (quantileCount > 0) { + let topOverlap = 0; + for (const id of currTop) { + if (prevTop.has(id)) { + topOverlap++; + } + } + let bottomOverlap = 0; + for (const id of currBottom) { + if (prevBottom.has(id)) { + bottomOverlap++; + } + } + topTurnoverBuf[turnoverCount] = 1 - topOverlap / currTop.size; + bottomTurnoverBuf[turnoverCount] = 1 - bottomOverlap / currBottom.size; + turnoverDates.push(slice.date); + turnoverCount++; + } + + const tmpTop = prevTop; + prevTop = currTop; + currTop = tmpTop; + + const tmpBottom = prevBottom; + prevBottom = currBottom; + currBottom = tmpBottom; + + quantileCount++; + } + } + + const pearsonIcSeries = trimFloat64(pearsonIcBuf, icCount); + const rankIcSeries = trimFloat64(rankIcBuf, icCount); + const spreadSeries = trimFloat64(spreadBuf, quantileCount); + const perBucketSeries: Float64Array[] = new Array(q); + const bucketMeanReturns: (number | null)[] = new Array(q); + for (let b = 0; b < q; b++) { + const trimmed = trimFloat64(perBucketBufs[b] as Float64Array, quantileCount); + perBucketSeries[b] = trimmed; + bucketMeanReturns[b] = meanFloat64(trimmed); + } + + const topSeries = trimFloat64(topTurnoverBuf, turnoverCount); + const bottomSeries = trimFloat64(bottomTurnoverBuf, turnoverCount); + + const pearsonIc = summarizeIcSeries(pearsonIcSeries, { lag }); + const rankIc = summarizeIcSeries(rankIcSeries, { lag }); + const spreadSummary = summarizeIcSeries(spreadSeries, { lag }); + const recency = buildRecencySplitResult( + icDates, + rankIcSeries, + splitDate, + minRatio, + vaultCutoffDate ?? null, + vaultExcludedDates, + lag + ); + + return { + dates: icDates, + pearsonIcSeries, + rankIcSeries, + pearsonIc, + rankIc, + quantiles: { + quantiles: q, + validDates: quantileCount, + skippedDates: quantileSkippedDates, + dates: quantileDates, + bucketMeanReturns, + perBucketSeries, + spreadSeries, + spreadSummary, + }, + turnover: { + count: turnoverCount, + dates: turnoverDates, + topSeries, + bottomSeries, + meanTopTurnover: meanFloat64(topSeries), + meanBottomTurnover: meanFloat64(bottomSeries), + }, + recency, + diagnostics: { + totalDates: panel.length, + eligibleDates, + vaultExcludedDates, + totalObservations, + validObservations, + droppedPairs, + icValidDates: icCount, + icSkippedBelowMin, + icSkippedZeroVariance, + quantileValidDates: quantileCount, + quantileSkippedDates, + }, + }; +} diff --git a/libs/calculations/src/index.ts b/libs/calculations/src/index.ts index 6f5a828f..6b60c43a 100644 --- a/libs/calculations/src/index.ts +++ b/libs/calculations/src/index.ts @@ -55,3 +55,69 @@ export { filterByTimeRange, groupBySymbol, } from './market-data'; +export { + DEFAULT_EVENT_MIN_EVENTS, + DEFAULT_EVENT_POST_DAYS, + DEFAULT_EVENT_PRE_DAYS, + DEFAULT_MIN_CROSS_SECTION, + DEFAULT_QUANTILE_COUNT, + DSR_VALIDATION_GATE, + EULER_MASCHERONI, + EventStudyError, + RECENCY_MIN_RATIO, + RECENCY_SPLIT_DATE, + SignalAnalysisError, + analyzeSignalPanel, + crossSectionIc, + defaultNeweyWestLag, + deflatedSharpeRatio, + effectiveIndependentTrials, + evaluateRecencyGate, + eventDayIndex, + eventStudy, + inverseNormalCdf, + neweyWestMeanTest, + normalCdf, + passesDsrGate, + summarizeIcSeries, + trialMoments, +} from './analytics'; +export type { + CrossSectionIcOptions, + CrossSectionIcResult, + DateClusteredCarResult, + DeflatedSharpeInput, + DeflatedSharpeResult, + EffectiveTrialsResult, + EntityId, + EntityIdSeries, + EventCarSeries, + EventDayIndexResult, + EventStudyDiagnostics, + EventStudyErrorCode, + EventStudyEvent, + EventStudyInput, + EventStudyOffsetStats, + EventStudyOptions, + EventStudyPercentiles, + EventStudyRecencyGate, + EventStudyRecencyReason, + EventStudyRecencyResult, + EventStudyResult, + IcSummary, + IcSummaryOptions, + NeweyWestResult, + NumericSeries, + QuantileSpreadResult, + RecencyGateOptions, + RecencyGateReason, + RecencyGateResult, + RecencySplitResult, + SignalAnalysisErrorCode, + SignalAnalysisOptions, + SignalCrossSection, + SignalPanelAnalysis, + SignalPanelDiagnostics, + TrialMoments, + TurnoverResult, +} from './analytics'; diff --git a/libs/calculations/test/deflated-sharpe-qa.test.ts b/libs/calculations/test/deflated-sharpe-qa.test.ts new file mode 100644 index 00000000..4d648df1 --- /dev/null +++ b/libs/calculations/test/deflated-sharpe-qa.test.ts @@ -0,0 +1,252 @@ +import { describe, expect, test } from 'bun:test'; +import { + deflatedSharpeRatio, + effectiveIndependentTrials, + inverseNormalCdf, + normalCdf, + trialMoments, +} from '@stock-bot/calculations'; + +// Reference values below were produced independently with CPython 3 stdlib +// (`math.erfc`, `statistics.NormalDist`, `statistics.stdev`, `statistics.correlation`), +// not by the module under test. + +describe('deflated-sharpe QA: independent reference values', () => { + test('normalCdf agrees with libm erfc to 1e-15 at Cody branch boundaries and deep tails', () => { + const cases: readonly (readonly [number, number])[] = [ + // y = |x|/sqrt(2) = 0.46875 (erf/erfc branch switch) + [-0.46875 * Math.SQRT2, 0.253693263391031], + // y = 4.0 (rational/asymptotic branch switch) + [-4 * Math.SQRT2, 7.70862895014001e-9], + [-8, 6.220960574271819e-16], + [-10, 7.619853024160593e-24], + ]; + for (const [x, expected] of cases) { + const value = normalCdf(x); + expect(value).not.toBeNull(); + expect(Math.abs((value as number) - expected)).toBeLessThanOrEqual(1e-15); + // Relative accuracy in the lower tail matters for tiny p-values. + expect(Math.abs((value as number) - expected) / expected).toBeLessThan(1e-12); + } + // Underflow is a valid probability, not null. + expect(normalCdf(-40)).toBe(0); + expect(normalCdf(40)).toBe(1); + }); + + test('normalCdf is monotone non-decreasing across all approximation branches', () => { + let previous = -1; + for (let x = -12; x <= 12; x += 0.001) { + const value = normalCdf(x) as number; + expect(value).toBeGreaterThanOrEqual(previous); + previous = value; + } + }); + + test('inverseNormalCdf matches statistics.NormalDist.inv_cdf on central and tail regions', () => { + const cases: readonly (readonly [number, number])[] = [ + [0.075, -1.4395314709384557], // central region boundary |q| <= 0.425 + [0.074, -1.4466320671589785], // just into tail region, r <= 5 + [1e-11, -6.706023155495136], // r > 5 branch + [0.96, 1.7506860712521695], + ]; + for (const [p, expected] of cases) { + expect(inverseNormalCdf(p) as number).toBeCloseTo(expected, 12); + } + }); + + test('trialMoments matches stdlib sample Sharpe and plugin skewness / Pearson kurtosis', () => { + const series = [0.012, -0.004, 0.007, -0.021, 0.015, 0.003, -0.009, 0.031, -0.002, 0.006]; + const moments = trialMoments(series); + expect(moments).not.toBeNull(); + expect(moments?.nObs).toBe(10); + expect(moments?.sharpeUnann as number).toBeCloseTo(0.2671027396298783, 12); + expect(moments?.skewness as number).toBeCloseTo(0.16688842823043712, 12); + expect(moments?.kurtosis as number).toBeCloseTo(2.9464511067020083, 12); + // Plugin moments obey Pearson's inequality kurtosis >= skew^2 + 1. + const skew = moments?.skewness as number; + expect(moments?.kurtosis as number).toBeGreaterThanOrEqual(skew * skew + 1); + }); + + test('effectiveIndependentTrials mean correlation matches stdlib pairwise Pearson average', () => { + const a = [0.3, -1.2, 0.8, 2.1, -0.4, 0.0, 1.1, -0.7]; + const b = [0.1, -0.9, 1.4, 1.0, -0.2, 0.5, 0.2, -1.3]; + const c = [-0.5, 0.4, 0.2, -1.1, 0.9, 0.3, -0.6, 0.7]; + // rho_ab = 0.7923790625364798, rho_ac = -0.840261348120643, rho_bc = -0.526175182297041 + // rho_bar = -0.19135248929373472 (< 0, so clamped) -> nHat = K = 3 + const result = effectiveIndependentTrials([a, b, c]); + expect(result.pairsUsed).toBe(3); + expect(result.pairsSkipped).toBe(0); + expect(result.meanCorrelation as number).toBeCloseTo(-0.19135248929373472, 12); + expect(result.nHat).toBe(3); + }); + + test('deflatedSharpeRatio matches an independently computed non-normal vector', () => { + // sigma_SR = stdev([0.01,0.03,0.05,0.02,0.07,0.04]) = 0.02160246899469287 + // SR0 = sigma_SR * [(1-g)*inv(1-1/25) + g*inv(1-1/(25e))] = 0.043143368521767964 + // SE = sqrt((1 + 0.8*0.08 + (5/4)*0.08^2) / 499) = 0.04634972052975479 + // DSR = Phi((0.08 - SR0)/SE) = 0.7867472337253661 + const result = deflatedSharpeRatio({ + sharpeUnann: 0.08, + nObs: 500, + skewness: -0.8, + kurtosis: 6, + nHat: 25, + clusterSharpes: [0.01, 0.03, 0.05, 0.02, 0.07, 0.04], + }); + expect(result).not.toBeNull(); + expect(result?.sr0 as number).toBeCloseTo(0.043143368521767964, 12); + expect(result?.standardError as number).toBeCloseTo(0.04634972052975479, 12); + expect(result?.dsr as number).toBeCloseTo(0.7867472337253661, 12); + }); +}); + +describe('deflated-sharpe QA: path consistency and degenerate inputs', () => { + test('fast (equal-length, all-finite) and general (unequal-length) paths give the same rho', () => { + const a = [0.3, -1.2, 0.8, 2.1, -0.4, 0.0, 1.1, -0.7]; + const b = [0.1, -0.9, 1.4, 1.0, -0.2, 0.5, 0.2, -1.3]; + const fast = effectiveIndependentTrials([a, b]); + // A trailing extra point on one side forces the general path over the same overlap. + const general = effectiveIndependentTrials([[...a, 42], b]); + // A NaN in one series forces the general path while keeping lengths equal. + const withNaN = effectiveIndependentTrials([ + [...a, Number.NaN], + [...b, 1], + ]); + expect(general.meanCorrelation as number).toBeCloseTo(fast.meanCorrelation as number, 12); + expect(withNaN.meanCorrelation as number).toBeCloseTo(fast.meanCorrelation as number, 12); + expect(fast.meanCorrelation as number).toBeCloseTo(0.7923790625364798, 12); + }); + + test('a series constant only on the overlap is skipped even if non-constant overall', () => { + const a = [1, 1, 1, 9]; + const b = [3, 4, 5]; + const result = effectiveIndependentTrials([a, b]); + expect(result).toEqual({ k: 2, pairsUsed: 0, pairsSkipped: 1, meanCorrelation: null, nHat: 2 }); + }); + + test('empty member series are skipped, not counted as zero correlation', () => { + const a = [1, 2, 3, 4]; + const b = [2, 3, 5, 9]; + const result = effectiveIndependentTrials([a, b, []]); + expect(result.pairsUsed).toBe(1); + expect(result.pairsSkipped).toBe(2); + expect(result.meanCorrelation as number).toBeGreaterThan(0.9); + }); + + test('overflowing magnitudes return null / skip instead of throwing', () => { + const huge = [1.7e308, 1.7e308, -1]; + expect(() => trialMoments(huge)).not.toThrow(); + expect(trialMoments(huge)).toBeNull(); + expect(() => effectiveIndependentTrials([huge, [1, 2, 3]])).not.toThrow(); + expect(effectiveIndependentTrials([huge, [1, 2, 3]]).pairsUsed).toBe(0); + expect( + deflatedSharpeRatio({ + sharpeUnann: 0.1, + nObs: 252, + skewness: 0, + kurtosis: 3, + nHat: 2, + clusterSharpes: [1e308, -1e308], + }) + ).toBeNull(); + }); + + test('duplicate series feed DSR exactly like nHat = 1 despite rounding in rho', () => { + // Identical series can produce rho = 1 - ulp, so nHat lands a hair above 1; + // the SR0 floor must make the DSR identical to the nHat = 1 case. + const series = [1, 2, 4, 3, 5, 7, 6]; + const { nHat } = effectiveIndependentTrials([series, series, series]); + expect(nHat).toBeGreaterThanOrEqual(1); + expect(nHat).toBeLessThan(1 + 1e-12); + const base = { + sharpeUnann: 0.1, + nObs: 252, + skewness: -0.3, + kurtosis: 4, + clusterSharpes: [0.02, 0.05, 0.1], + }; + const fromDuplicates = deflatedSharpeRatio({ ...base, nHat }); + const exact = deflatedSharpeRatio({ ...base, nHat: 1 }); + expect(fromDuplicates).toEqual(exact); + expect(fromDuplicates?.sr0).toBe(0); + }); + + test('DSR rises with T and with SR, and falls as cluster Sharpe dispersion grows', () => { + const base = { + sharpeUnann: 0.08, + nObs: 500, + skewness: 0, + kurtosis: 3, + nHat: 20, + clusterSharpes: [0.01, 0.03, 0.05], + }; + const dsr = (overrides: Partial) => + deflatedSharpeRatio({ ...base, ...overrides })?.dsr as number; + expect(dsr({ nObs: 2000 })).toBeGreaterThan(dsr({ nObs: 500 })); + expect(dsr({ sharpeUnann: 0.12 })).toBeGreaterThan(dsr({})); + expect(dsr({ clusterSharpes: [0.0, 0.03, 0.06] })).toBeLessThan(dsr({})); + }); + + test('SR below SR0 yields DSR < 0.5; zero SR with zero SR0 yields exactly 0.5', () => { + const below = deflatedSharpeRatio({ + sharpeUnann: 0.01, + nObs: 500, + skewness: 0, + kurtosis: 3, + nHat: 50, + clusterSharpes: [0.0, 0.05, 0.1], + }); + expect(below?.dsr as number).toBeLessThan(0.5); + const atZero = deflatedSharpeRatio({ + sharpeUnann: 0, + nObs: 500, + skewness: 0, + kurtosis: 3, + nHat: 1, + clusterSharpes: [], + }); + expect(atZero?.dsr).toBe(0.5); + }); + + test('nHat so large that 1 - 1/nHat rounds to 1 returns null rather than a bogus SR0', () => { + expect( + deflatedSharpeRatio({ + sharpeUnann: 0.1, + nObs: 252, + skewness: 0, + kurtosis: 3, + nHat: 1e17, + clusterSharpes: [0, 0.1], + }) + ).toBeNull(); + expect( + deflatedSharpeRatio({ + sharpeUnann: 0.1, + nObs: 252, + skewness: 0, + kurtosis: 3, + nHat: Number.POSITIVE_INFINITY, + clusterSharpes: [0, 0.1], + }) + ).toBeNull(); + }); + + test('inputs are not mutated', () => { + const series = [0.01, Number.NaN, -0.02, 0.03]; + const snapshot = [...series]; + const cluster = [0.01, 0.02, 0.04]; + const clusterSnapshot = [...cluster]; + trialMoments(series); + effectiveIndependentTrials([series, [0.02, 0.01, 0.0, 0.05]]); + deflatedSharpeRatio({ + sharpeUnann: 0.1, + nObs: 100, + skewness: 0, + kurtosis: 3, + nHat: 3, + clusterSharpes: cluster, + }); + expect(series).toEqual(snapshot); + expect(cluster).toEqual(clusterSnapshot); + }); +}); diff --git a/libs/calculations/test/deflated-sharpe.test.ts b/libs/calculations/test/deflated-sharpe.test.ts new file mode 100644 index 00000000..6e3fb3b2 --- /dev/null +++ b/libs/calculations/test/deflated-sharpe.test.ts @@ -0,0 +1,478 @@ +import { describe, expect, test } from 'bun:test'; +import * as rootExports from '@stock-bot/calculations'; +import * as analyticsExports from '@stock-bot/calculations/analytics'; +import { + DSR_VALIDATION_GATE, + EULER_MASCHERONI, + deflatedSharpeRatio, + effectiveIndependentTrials, + inverseNormalCdf, + normalCdf, + passesDsrGate, + trialMoments, +} from '@stock-bot/calculations'; + +function createMulberry32(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) / 4294967296; + }; +} + +function createStandardNormal(seed: number): () => number { + const nextUniform = createMulberry32(seed); + let spare: number | null = null; + return () => { + if (spare !== null) { + const value = spare; + spare = null; + return value; + } + let u1 = nextUniform(); + while (u1 <= 1e-12) { + u1 = nextUniform(); + } + const u2 = nextUniform(); + const radius = Math.sqrt(-2 * Math.log(u1)); + const theta = 2 * Math.PI * u2; + spare = radius * Math.sin(theta); + return radius * Math.cos(theta); + }; +} + +describe('deflated-sharpe exports', () => { + test('both root and analytics entrypoints export the complete DSR surface', () => { + const names = [ + 'DSR_VALIDATION_GATE', + 'EULER_MASCHERONI', + 'normalCdf', + 'inverseNormalCdf', + 'trialMoments', + 'effectiveIndependentTrials', + 'deflatedSharpeRatio', + 'passesDsrGate', + ] as const; + + for (const name of names) { + expect(rootExports[name]).toBeDefined(); + expect(analyticsExports[name]).toBe(rootExports[name]); + } + + expect(DSR_VALIDATION_GATE).toBe(0.95); + expect(EULER_MASCHERONI).toBeCloseTo(0.5772156649015329, 15); + }); +}); + +describe('normalCdf and inverseNormalCdf', () => { + test('matches known reference values across center and tails', () => { + expect(normalCdf(0)).toBe(0.5); + expect(normalCdf(1.959963984540054)).toBeCloseTo(0.975, 12); + expect(normalCdf(-1.959963984540054)).toBeCloseTo(0.025, 12); + expect(normalCdf(1)).toBeCloseTo(0.8413447460685429, 12); + expect(normalCdf(-1)).toBeCloseTo(0.15865525393145707, 12); + // Extreme tails: Phi(-6) = 9.86587645037698e-10 + expect(normalCdf(-6)).toBeCloseTo(9.86587645037698e-10, 15); + expect(normalCdf(6)).toBeCloseTo(1 - 9.86587645037698e-10, 15); + + expect(inverseNormalCdf(0.5)).toBe(0); + expect(inverseNormalCdf(0.975)).toBeCloseTo(1.959963984540054, 12); + expect(inverseNormalCdf(0.025)).toBeCloseTo(-1.959963984540054, 12); + expect(inverseNormalCdf(0.99)).toBeCloseTo(2.3263478740408408, 12); + expect(inverseNormalCdf(1e-12)).toBeCloseTo(-7.034483825301132, 12); + expect(inverseNormalCdf(1 - 1e-12)).toBeCloseTo(7.034486910047835, 9); + }); + + test('satisfies symmetry and round-trip accuracy <= 1e-9 across [1e-12, 1 - 1e-12]', () => { + for (const x of [0, 0.1, 0.45, 1, 2.5, 4, 5.5, 6.5]) { + const pos = normalCdf(x); + const neg = normalCdf(-x); + expect(pos).not.toBeNull(); + expect(neg).not.toBeNull(); + expect((pos as number) + (neg as number)).toBeCloseTo(1, 14); + } + + const probabilities = [ + 1e-12, + 1e-10, + 1e-8, + 1e-6, + 1e-4, + 0.001, + 0.025, + 0.1, + 0.25, + 0.5, + 0.75, + 0.9, + 0.975, + 0.999, + 1 - 1e-4, + 1 - 1e-6, + 1 - 1e-8, + 1 - 1e-10, + 1 - 1e-12, + ]; + + for (const p of probabilities) { + const z = inverseNormalCdf(p); + expect(z).not.toBeNull(); + const roundTrip = normalCdf(z as number); + expect(roundTrip).not.toBeNull(); + expect(Math.abs((roundTrip as number) - p)).toBeLessThanOrEqual(1e-9); + + if (p < 0.5) { + // Use exact IEEE-754 complement pairs (pExact + pComp === 1) so + // 1 - (1 - p) rounding at p = 1e-12 does not perturb the input. + const pComp = 1 - p; + const pExact = 1 - pComp; + const zExact = inverseNormalCdf(pExact); + const zSym = inverseNormalCdf(pComp); + expect(zExact).not.toBeNull(); + expect(zSym).not.toBeNull(); + expect(Math.abs((zExact as number) + (zSym as number))).toBeLessThanOrEqual(1e-12); + } + } + }); + + test('returns null without throwing on invalid inputs', () => { + for (const badX of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) { + expect(normalCdf(badX)).toBeNull(); + } + for (const badP of [ + -1, + -1e-15, + 0, + 1, + 1 + 1e-15, + 2, + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + ]) { + expect(inverseNormalCdf(badP)).toBeNull(); + } + }); +}); + +describe('trialMoments', () => { + test('computes unannualized daily Sharpe, plugin skewness, and Pearson kurtosis', () => { + // Symmetric 4-point series: [-1, 0, 2, 3] + // mean = 1.0 + // deviations = [-2, -1, 1, 2] + // sum2 = 10 -> sampleVar = 10/3, sampleStd = sqrt(10/3) + // sharpeUnann = 1 / sqrt(10/3) (unannualized, no sqrt(252)) + // m2 = 10/4 = 2.5, m3 = 0 -> skewness = 0 + // sum4 = 16 + 1 + 1 + 16 = 34 -> m4 = 8.5 -> kurtosis = 8.5 / 6.25 = 1.36 + const moments = trialMoments([-1, 0, 2, 3]); + expect(moments).not.toBeNull(); + expect(moments?.nObs).toBe(4); + expect(moments?.sharpeUnann).toBeCloseTo(1 / Math.sqrt(10 / 3), 12); + expect(moments?.skewness).toBeCloseTo(0, 12); + expect(moments?.kurtosis).toBeCloseTo(1.36, 12); + + // Daily risk-free rate subtracts directly from mean before dividing by sampleStd + const excess = trialMoments([-1, 0, 2, 3], 0.5); + expect(excess?.sharpeUnann).toBeCloseTo(0.5 / Math.sqrt(10 / 3), 12); + }); + + test('produces Pearson kurtosis near 3.0 on standard normal draws and supports nObs = 2 and 3', () => { + const randn = createStandardNormal(42); + const normalSample = Array.from({ length: 10000 }, () => randn()); + const moments = trialMoments(normalSample); + expect(moments).not.toBeNull(); + expect(moments?.nObs).toBe(10000); + expect(Math.abs(moments?.skewness as number)).toBeLessThan(0.1); + expect(moments?.kurtosis as number).toBeGreaterThan(2.85); + expect(moments?.kurtosis as number).toBeLessThan(3.15); + + // nObs = 2 (matching trial_ledger CHECK n_obs >= 2) + const two = trialMoments([0.01, 0.03]); + expect(two).not.toBeNull(); + expect(two?.nObs).toBe(2); + expect(two?.sharpeUnann).toBeCloseTo(0.02 / Math.sqrt(0.0002), 12); + expect(two?.skewness).toBeCloseTo(0, 12); + expect(two?.kurtosis).toBeCloseTo(1, 12); + + // nObs = 3 + const three = trialMoments([0.01, 0.02, 0.06]); + expect(three).not.toBeNull(); + expect(three?.nObs).toBe(3); + }); + + test('filters non-finite values and returns null on degenerate inputs without throwing', () => { + const withGarbage = [Number.NaN, -1, Number.POSITIVE_INFINITY, 0, 2, Number.NEGATIVE_INFINITY, 3]; + const filtered = trialMoments(withGarbage); + const clean = trialMoments([-1, 0, 2, 3]); + expect(filtered).toEqual(clean); + + // Sparse arrays + const sparse = new Array(5); + sparse[1] = 0.01; + sparse[3] = 0.03; + expect(trialMoments(sparse)).toEqual(trialMoments([0.01, 0.03])); + + // Degenerate inputs -> null + expect(trialMoments([])).toBeNull(); + expect(trialMoments([0.01])).toBeNull(); + expect(trialMoments([0.01, Number.NaN, Number.POSITIVE_INFINITY])).toBeNull(); + expect(trialMoments([0.1, 0.1, 0.1])).toBeNull(); + expect(trialMoments([0, 0, 0, 0])).toBeNull(); + expect(trialMoments(new Array(4))).toBeNull(); + expect(trialMoments([0.01, 0.02], Number.NaN)).toBeNull(); + expect(trialMoments([0.01, 0.02], Number.POSITIVE_INFINITY)).toBeNull(); + }); +}); + +describe('effectiveIndependentTrials', () => { + test('matches doc example: two series with rho ~= 0.97 yield nHat ~= 1.03', () => { + const randn = createStandardNormal(101); + const n = 5000; + const rhoTarget = 0.97; + const noiseScale = Math.sqrt(1 - rhoTarget * rhoTarget); + const s1: number[] = new Array(n); + const s2: number[] = new Array(n); + for (let t = 0; t < n; t++) { + const z1 = randn(); + const z2 = randn(); + s1[t] = z1; + s2[t] = rhoTarget * z1 + noiseScale * z2; + } + + const result = effectiveIndependentTrials([s1, s2]); + expect(result.k).toBe(2); + expect(result.pairsUsed).toBe(1); + expect(result.pairsSkipped).toBe(0); + expect(result.meanCorrelation).not.toBeNull(); + expect(result.meanCorrelation as number).toBeCloseTo(0.97, 2); + expect(result.nHat).toBeCloseTo(1.03, 2); + }); + + test('matches doc example: 100 near-orthogonal seeded series yield nHat ~= 100', () => { + const randn = createStandardNormal(2026); + const k = 100; + const n = 2520; + const seriesList: number[][] = Array.from({ length: k }, () => + Array.from({ length: n }, () => randn()) + ); + + const result = effectiveIndependentTrials(seriesList); + expect(result.k).toBe(100); + expect(result.pairsUsed).toBe((100 * 99) / 2); + expect(result.pairsSkipped).toBe(0); + expect(result.meanCorrelation).not.toBeNull(); + expect(Math.abs(result.meanCorrelation as number)).toBeLessThan(0.01); + // Tolerance: with K=100 independent draws of T=2520, std(rho_bar) ~ 0.0003, + // so nHat sits within [99.0, 100.0]. + expect(result.nHat).toBeGreaterThanOrEqual(99.0); + expect(result.nHat).toBeLessThanOrEqual(100.0); + }); + + test('handles identical series, negative correlation clamping, K <= 1, and large-offset stability', () => { + const base = [1, 2, 4, 3, 5, 7, 6]; + const identical = effectiveIndependentTrials([base, base, base]); + expect(identical.pairsUsed).toBe(3); + expect(identical.pairsSkipped).toBe(0); + expect(identical.meanCorrelation).toBeCloseTo(1, 12); + expect(identical.nHat).toBeCloseTo(1, 12); + + // Negatively correlated pair -> rho_bar = -1 -> clamped to nHat = K = 2 + const opposite = base.map(v => -v); + const neg = effectiveIndependentTrials([base, opposite]); + expect(neg.meanCorrelation).toBeCloseTo(-1, 12); + expect(neg.nHat).toBe(2); + + // K = 0 and K = 1 + expect(effectiveIndependentTrials([])).toEqual({ + k: 0, + pairsUsed: 0, + pairsSkipped: 0, + meanCorrelation: null, + nHat: 1, + }); + expect(effectiveIndependentTrials([base])).toEqual({ + k: 1, + pairsUsed: 0, + pairsSkipped: 0, + meanCorrelation: null, + nHat: 1, + }); + + // Shifted large-offset series verify centered correlation avoids catastrophic cancellation + const offset = 1e9; + const shiftedA = base.map(v => offset + v); + const shiftedB = base.map(v => offset + 2 * v + 5); + const shifted = effectiveIndependentTrials([shiftedA, shiftedB]); + expect(shifted.meanCorrelation).toBeCloseTo(1, 12); + expect(shifted.nHat).toBeCloseTo(1, 12); + }); + + test('skips degenerate pairs without diluting meanCorrelation with synthetic zeros', () => { + const a = [1, 2, 3, 4, 5]; + const b = [2, 4, 6, 8, 10]; // rho(a, b) = 1 + const constant = [0.1, 0.1, 0.1, 0.1, 0.1]; // constant -> skipped against both a and b + + const withConstant = effectiveIndependentTrials([a, b, constant]); + expect(withConstant.k).toBe(3); + expect(withConstant.pairsUsed).toBe(1); + expect(withConstant.pairsSkipped).toBe(2); + // If skipped pairs were treated as rho = 0, meanCorrelation would be 1/3 instead of 1. + expect(withConstant.meanCorrelation).toBeCloseTo(1, 12); + expect(withConstant.nHat).toBeCloseTo(1, 12); + + // Unequal lengths and NaN gaps: overlap on indices 1, 2, 4 -> (2,4), (3,6), (5,10) -> rho = 1 + const gappedA = [Number.NaN, 2, 3, Number.POSITIVE_INFINITY, 5, 99, 100]; + const gappedB = [1, 4, 6, 8, 10]; + const gapped = effectiveIndependentTrials([gappedA, gappedB]); + expect(gapped.pairsUsed).toBe(1); + expect(gapped.pairsSkipped).toBe(0); + expect(gapped.meanCorrelation).toBeCloseTo(1, 12); + + // Overlap < 2 finite points -> all pairs skipped -> conservative nHat = K + const disjointA = [1, Number.NaN, Number.NaN]; + const disjointB = [Number.NaN, 2, 3]; + const allSkipped = effectiveIndependentTrials([disjointA, disjointB]); + expect(allSkipped).toEqual({ + k: 2, + pairsUsed: 0, + pairsSkipped: 1, + meanCorrelation: null, + nHat: 2, + }); + }); +}); + +describe('deflatedSharpeRatio and passesDsrGate', () => { + test('matches hand-computed golden DSR vector and penalizes negative skew and excess kurtosis', () => { + // Hand-computed golden vector: + // sharpeUnann = 0.15, nObs = 1000 (T - 1 = 999), nHat = 100 + // clusterSharpes = [-0.02, 0.0, 0.02, 0.04, 0.06] + // mean = 0.02, sum((x - mean)^2) = 0.004, sampleVar = 0.001 + // sigmaSr = sqrt(0.001) = 0.03162277660168379 + // z1 = Phi^-1(1 - 1/100) = Phi^-1(0.99) = 2.3263478740408408 + // z2 = Phi^-1(1 - 1/(100 * e)) = Phi^-1(0.9963212055882856) = 2.680210444966887 + // bracket = (1 - 0.5772156649015329) * 2.3263478740408408 + // + 0.5772156649015329 * 2.680210444966887 + // = 2.5306028932016846 + // sr0 = 0.03162277660168379 * 2.5306028932016846 = 0.08002468995929155 + // + // Normal case (skewness = 0, kurtosis = 3): + // radicand = (1 - 0 + ((3 - 1)/4) * 0.15^2) / 999 = 1.01125 / 999 + // SE = sqrt(1.01125 / 999) = 0.031816069245937065 + // z = (0.15 - 0.08002468995929155) / 0.031816069245937065 = 2.1993700575697134 + // DSR = Phi(2.1993700575697134) = 0.9860741900352264 + const clusterSharpes = [-0.02, 0.0, 0.02, 0.04, 0.06]; + const normalCase = deflatedSharpeRatio({ + sharpeUnann: 0.15, + nObs: 1000, + skewness: 0, + kurtosis: 3, + nHat: 100, + clusterSharpes, + }); + expect(normalCase).not.toBeNull(); + expect(normalCase?.sr0).toBeCloseTo(0.08002468995929155, 10); + expect(normalCase?.standardError).toBeCloseTo(0.031816069245937065, 10); + expect(normalCase?.dsr).toBeCloseTo(0.9860741900352264, 10); + expect(passesDsrGate(normalCase?.dsr ?? null)).toBe(true); + + // Non-normal case (skewness = -1.5, kurtosis = 7): + // radicand = (1 - (-1.5)*0.15 + ((7 - 1)/4) * 0.15^2) / 999 = 1.25875 / 999 + // SE = sqrt(1.25875 / 999) = 0.035496619698360155 + // z = (0.15 - 0.08002468995929155) / 0.035496619698360155 = 1.9713232028632037 + // DSR = Phi(1.9713232028632037) = 0.9756565405046566 + const nonNormalCase = deflatedSharpeRatio({ + sharpeUnann: 0.15, + nObs: 1000, + skewness: -1.5, + kurtosis: 7, + nHat: 100, + clusterSharpes, + }); + expect(nonNormalCase).not.toBeNull(); + expect(nonNormalCase?.sr0).toBeCloseTo(normalCase?.sr0 as number, 12); + expect(nonNormalCase?.standardError).toBeCloseTo(0.035496619698360155, 10); + expect(nonNormalCase?.dsr).toBeCloseTo(0.9756565405046566, 10); + expect(nonNormalCase?.standardError as number).toBeGreaterThan( + normalCase?.standardError as number + ); + expect(nonNormalCase?.dsr as number).toBeLessThan(normalCase?.dsr as number); + }); + + test('is monotonically non-increasing as nHat grows (including fractional 1 < nHat < 1.3)', () => { + const clusterSharpes = [-0.02, 0.0, 0.02, 0.04, 0.06]; + const nHatValues = [1, 1.03, 1.2, 2, 10, 100, 1000]; + let prevSr0 = -1; + let prevDsr = 2; + + for (const nHat of nHatValues) { + const res = deflatedSharpeRatio({ + sharpeUnann: 0.15, + nObs: 1000, + skewness: -0.5, + kurtosis: 4, + nHat, + clusterSharpes, + }); + expect(res).not.toBeNull(); + expect(res?.sr0 as number).toBeGreaterThanOrEqual(0); + expect(res?.sr0 as number).toBeGreaterThanOrEqual(prevSr0); + expect(res?.dsr as number).toBeLessThanOrEqual(prevDsr); + prevSr0 = res?.sr0 as number; + prevDsr = res?.dsr as number; + } + }); + + test('handles defined edge cases and returns null on invalid inputs without throwing', () => { + const base = { + sharpeUnann: 0.1, + nObs: 252, + skewness: 0, + kurtosis: 3, + nHat: 10, + clusterSharpes: [0.02, 0.05, 0.1], + }; + + // nHat = 1 -> sr0 = 0 + expect(deflatedSharpeRatio({ ...base, nHat: 1 })?.sr0).toBe(0); + // < 2 clusterSharpes -> sr0 = 0 + expect(deflatedSharpeRatio({ ...base, clusterSharpes: [] })?.sr0).toBe(0); + expect(deflatedSharpeRatio({ ...base, clusterSharpes: [0.1] })?.sr0).toBe(0); + // Zero-variance clusterSharpes -> sr0 = 0 + expect(deflatedSharpeRatio({ ...base, clusterSharpes: [0.1, 0.1, 0.1] })?.sr0).toBe(0); + + // Invalid inputs -> null + expect(deflatedSharpeRatio({ ...base, nObs: 1 })).toBeNull(); + expect(deflatedSharpeRatio({ ...base, nObs: 0 })).toBeNull(); + expect(deflatedSharpeRatio({ ...base, nHat: 0.99 })).toBeNull(); + expect(deflatedSharpeRatio({ ...base, sharpeUnann: Number.NaN })).toBeNull(); + expect(deflatedSharpeRatio({ ...base, skewness: Number.POSITIVE_INFINITY })).toBeNull(); + expect(deflatedSharpeRatio({ ...base, kurtosis: Number.NaN })).toBeNull(); + expect(deflatedSharpeRatio({ ...base, clusterSharpes: [0.02, Number.NaN, 0.1] })).toBeNull(); + expect(deflatedSharpeRatio({ ...base, clusterSharpes: new Array(3) })).toBeNull(); + + // Non-positive SE radicand -> null: + // 1 - skewness * sr + ((kurtosis - 1)/4) * sr^2 = 1 - 10*0.5 + 0 = -4 <= 0 + expect( + deflatedSharpeRatio({ + ...base, + sharpeUnann: 0.5, + skewness: 10, + kurtosis: 1, + }) + ).toBeNull(); + }); + + test('passesDsrGate enforces DSR >= 0.95 and rejects null or non-finite values', () => { + expect(passesDsrGate(null)).toBe(false); + expect(passesDsrGate(Number.NaN)).toBe(false); + expect(passesDsrGate(Number.POSITIVE_INFINITY)).toBe(false); + expect(passesDsrGate(0.9499)).toBe(false); + expect(passesDsrGate(0.95)).toBe(true); + expect(passesDsrGate(0.99)).toBe(true); + expect(passesDsrGate(0.9, 0.9)).toBe(true); + expect(passesDsrGate(0.95, Number.NaN)).toBe(false); + }); +}); diff --git a/libs/calculations/test/event-study-qa.test.ts b/libs/calculations/test/event-study-qa.test.ts new file mode 100644 index 00000000..94bbaa86 --- /dev/null +++ b/libs/calculations/test/event-study-qa.test.ts @@ -0,0 +1,446 @@ +import { describe, expect, test } from 'bun:test'; +import { + EventStudyError, + evaluateRecencyGate, + eventDayIndex, + eventStudy, + neweyWestMeanTest, + type EntityId, + type EventStudyErrorCode, + type EventStudyEvent, + type EventStudyPercentiles, + type EventStudyResult, +} from '@stock-bot/calculations'; + +// QA edge cases for T-83 that the programmer suite does not reach: the introselect +// percentile path under ties / adversarial orderings and at the 64/65 switch-over, +// end-to-end timestamp -> session mapping (no look-ahead), id ordering, input +// immutability, default Newey-West lag, and degenerate calendars. + +function createMulberry32(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) / 4294967296; + }; +} + +function tradingDates(count: number, startYear = 2022): string[] { + const out: string[] = []; + const dt = new Date(Date.UTC(startYear, 0, 3)); + while (out.length < count) { + const dow = dt.getUTCDay(); + if (dow !== 0 && dow !== 6) { + out.push(dt.toISOString().slice(0, 10)); + } + dt.setUTCDate(dt.getUTCDate() + 1); + } + return out; +} + +function refPercentiles(values: readonly number[]): EventStudyPercentiles { + const s = [...values].sort((a, b) => a - b); + const q = (p: number): number => { + const pos = p * (s.length - 1); + const lo = Math.floor(pos); + const hi = Math.ceil(pos); + return lo === hi ? s[lo]! : s[lo]! + (pos - lo) * (s[hi]! - s[lo]!); + }; + return { p5: q(0.05), p25: q(0.25), p50: q(0.5), p75: q(0.75), p95: q(0.95) }; +} + +function expectCode(fn: () => unknown, code: EventStudyErrorCode): void { + let caught: unknown; + try { + fn(); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(EventStudyError); + expect((caught as EventStudyError).code).toBe(code); +} + +function okOrThrow(res: EventStudyResult): Extract { + if (res.status !== 'ok') { + throw new Error(`expected ok, got ${res.status}/${res.reason}`); + } + return res; +} + +/** + * One event per entity, all on day 1 and day 2 alternately (2 dates), window 0..0, so each + * offset's CAR cross-section is exactly `cars` and the percentile fan must equal R-7 on it. + */ +function fanForCars(cars: readonly number[]): EventStudyPercentiles { + const sessionDates = tradingDates(4); + const entityReturns = new Map(); + const events: EventStudyEvent[] = []; + for (let i = 0; i < cars.length; i++) { + const day = 1 + (i % 2); + const arr = new Float64Array(4); + arr[day] = cars[i]!; + entityReturns.set(i, arr); + events.push({ entityId: i, dayIndex: day }); + } + const res = okOrThrow( + eventStudy({ sessionDates, entityReturns, events }, { preDays: 0, postDays: 0, minEvents: 1 }) + ); + expect(res.offsets[0]!.n).toBe(cars.length); + return res.offsets[0]!.carPercentiles; +} + +function expectFanEqual(actual: EventStudyPercentiles, expected: EventStudyPercentiles): void { + for (const key of ['p5', 'p25', 'p50', 'p75', 'p95'] as const) { + expect(Math.abs(actual[key] - expected[key])).toBeLessThan(1e-15); + } +} + +describe('event-study QA: percentile fan (introselect path)', () => { + test('matches sorted R-7 at sizes around the 64/65 insertion-sort / introselect switch', () => { + const rng = createMulberry32(830_001); + for (const n of [2, 3, 20, 63, 64, 65, 66, 67, 99, 100, 101, 257, 1_000, 4_097]) { + const cars = Array.from({ length: n }, () => (rng() - 0.5) * 0.2); + expectFanEqual(fanForCars(cars), refPercentiles(cars)); + } + }); + + test('matches sorted R-7 under heavy ties (3-way partition) and all-equal values', () => { + const rng = createMulberry32(830_002); + for (const n of [65, 66, 200, 2_000]) { + // only 3 distinct values -> most order statistics land inside equal runs + const fewDistinct = Array.from({ length: n }, () => [-0.01, 0, 0.02][Math.floor(rng() * 3)]!); + expectFanEqual(fanForCars(fewDistinct), refPercentiles(fewDistinct)); + // tie straddling an interpolation neighbour: all but one equal + const almostConst = Array.from({ length: n }, (_, i) => (i === n - 1 ? 0.5 : 0.01)); + expectFanEqual(fanForCars(almostConst), refPercentiles(almostConst)); + const allEqual = new Array(n).fill(0.03); + expectFanEqual(fanForCars(allEqual), refPercentiles(allEqual)); + } + }); + + test('matches sorted R-7 on adversarial orderings that stress median-of-3 / heapsort fallback', () => { + const n = 3_001; + const ascending = Array.from({ length: n }, (_, i) => i * 1e-4); + const descending = [...ascending].reverse(); + const organPipe = Array.from({ length: n }, (_, i) => Math.min(i, n - 1 - i) * 1e-4); + const sawtooth = Array.from({ length: n }, (_, i) => (i % 17) * 1e-3); + // median-of-3 killer style: interleave small and large + const interleaved = Array.from({ length: n }, (_, i) => (i % 2 === 0 ? i : n * 2 - i) * 1e-5); + for (const cars of [ascending, descending, organPipe, sawtooth, interleaved]) { + expectFanEqual(fanForCars(cars), refPercentiles(cars)); + } + }); +}); + +describe('event-study QA: end-to-end information availability', () => { + test('an event known after session k close uses session k+1 as offset 0 (no look-ahead)', () => { + // closes at 16:00 on consecutive days (epoch ms); returns encode their own index + const T = 10; + const sessionDates = tradingDates(T); + const closes = sessionDates.map(d => Date.parse(`${d}T21:00:00Z`)); + const series = Float64Array.from({ length: T }, (_, t) => (t + 1) / 100); + const entityReturns = new Map([['X', series]]); + + const atClose = eventDayIndex(closes, closes[4]!); + const afterClose = eventDayIndex(closes, closes[4]! + 1); + const intraday = eventDayIndex(closes, closes[6]! - 3_600_000); + expect(atClose).toEqual({ status: 'ok', dayIndex: 4 }); + expect(afterClose).toEqual({ status: 'ok', dayIndex: 5 }); + expect(intraday).toEqual({ status: 'ok', dayIndex: 6 }); + + const res = okOrThrow( + eventStudy( + { + sessionDates, + entityReturns, + events: [ + { entityId: 'X', dayIndex: (afterClose as { dayIndex: number }).dayIndex }, + { entityId: 'X', dayIndex: (intraday as { dayIndex: number }).dayIndex }, + ], + }, + { preDays: 1, postDays: 1, minEvents: 2, neweyWestLag: 0 } + ) + ); + // offset 0 AR for event on day 5 is series[5] = 0.06, never series[4] + expect(Array.from(res.eventCars.dayIndices)).toEqual([5, 6]); + expect(Math.abs(res.eventCars.cars[0]! - (0.06 + 0.07))).toBeLessThan(1e-15); + expect(Math.abs(res.eventCars.cars[1]! - (0.07 + 0.08))).toBeLessThan(1e-15); + expect(res.eventCars.dates).toEqual([sessionDates[5], sessionDates[6]]); + }); + + test('eventDayIndex on a single-session calendar and with a huge sorted Float64Array', () => { + expect(eventDayIndex([100], 100)).toEqual({ status: 'ok', dayIndex: 0 }); + expect(eventDayIndex([100], -1e15)).toEqual({ status: 'ok', dayIndex: 0 }); + expect(eventDayIndex([100], 101)).toEqual({ status: 'no_session', reason: 'after_last_session' }); + + const big = Float64Array.from({ length: 100_000 }, (_, i) => i * 10); + for (const [ts, want] of [ + [0, 0], + [1, 1], + [10, 1], + [11, 2], + [499_990, 49_999], + [999_990, 99_999], + ] as const) { + expect(eventDayIndex(big, ts)).toEqual({ status: 'ok', dayIndex: want }); + } + expectCode(() => eventDayIndex([1, 2, 3], Number.NEGATIVE_INFINITY), 'INVALID_TIMESTAMP'); + expectCode(() => eventDayIndex([3, 2], 1), 'UNSORTED_TIMESTAMPS'); + }); +}); + +describe('event-study QA: ordering, immutability and defaults', () => { + test('numeric ids sort numerically (9 before 10) and before string ids in eventCars', () => { + const sessionDates = tradingDates(5); + const mk = (v: number) => Float64Array.from({ length: 5 }, () => v); + const entityReturns = new Map([ + ['b', mk(0.05)], + [10, mk(0.02)], + ['a', mk(0.04)], + [9, mk(0.01)], + ['10', mk(0.03)], + ]); + const events: EventStudyEvent[] = ['b', 10, 'a', 9, '10'].map(id => ({ + entityId: id, + dayIndex: 2, + })); + events.push({ entityId: 9, dayIndex: 3 }); + const res = okOrThrow( + eventStudy({ sessionDates, entityReturns, events }, { preDays: 1, postDays: 0, minEvents: 2 }) + ); + expect(res.eventCars.entityIds).toEqual([9, 10, '10', 'a', 'b', 9]); + expect(Array.from(res.eventCars.cars)).toEqual([0.01, 0.02, 0.03, 0.04, 0.05, 0.01]); + }); + + test('does not mutate inputs and returns fresh buffers on repeated calls', () => { + const rng = createMulberry32(830_003); + const T = 40; + const sessionDates = tradingDates(T); + const bench = Float64Array.from({ length: T }, () => (rng() - 0.5) * 0.01); + const entityReturns = new Map(); + for (let e = 0; e < 6; e++) { + entityReturns.set(e, Float64Array.from({ length: T }, () => (rng() - 0.5) * 0.04)); + } + const events: EventStudyEvent[] = Array.from({ length: 30 }, () => ({ + entityId: Math.floor(rng() * 6), + dayIndex: Math.floor(rng() * T), + })); + const snapshot = { + bench: Array.from(bench), + series: [...entityReturns].map(([id, s]) => [id, Array.from(s)]), + events: JSON.stringify(events), + dates: [...sessionDates], + }; + + const a = okOrThrow( + eventStudy({ sessionDates, entityReturns, benchmarkReturns: bench, events }, { preDays: 2, postDays: 3 }) + ); + const b = okOrThrow( + eventStudy({ sessionDates, entityReturns, benchmarkReturns: bench, events }, { preDays: 2, postDays: 3 }) + ); + + expect(Array.from(bench)).toEqual(snapshot.bench); + expect([...entityReturns].map(([id, s]) => [id, Array.from(s)])).toEqual(snapshot.series); + expect(JSON.stringify(events)).toBe(snapshot.events); + expect(sessionDates).toEqual(snapshot.dates); + + expect(a.eventCars.cars).not.toBe(b.eventCars.cars); + a.eventCars.cars.fill(99); + a.clustered.meanCars.fill(99); + expect(b.eventCars.cars[0]).not.toBe(99); + expect(b.clustered.meanCars[0]).not.toBe(99); + }); + + test('omitted neweyWestLag uses the T-82 default lag on the number of clustered dates', () => { + const rng = createMulberry32(830_004); + const T = 400; + const sessionDates = tradingDates(T, 2020); + const entityReturns = new Map(); + for (let e = 0; e < 5; e++) { + entityReturns.set(e, Float64Array.from({ length: T }, () => (rng() - 0.48) * 0.03)); + } + const events: EventStudyEvent[] = []; + for (let d = 5; d < T - 5; d += 2) { + events.push({ entityId: d % 5, dayIndex: d }); + } + const res = okOrThrow( + eventStudy({ sessionDates, entityReturns, events }, { preDays: 1, postDays: 3 }) + ); + const expected = neweyWestMeanTest(res.clustered.meanCars); + expect(res.clustered.nDates).toBeGreaterThan(100); + expect(res.clustered.neweyWest).toEqual(expected); + expect(res.clustered.neweyWest.lag).toBeGreaterThan(0); + + // positive-mean recency gate is exactly T-82's evaluateRecencyGate on the clustered series + const raw = evaluateRecencyGate(res.clustered.dates, res.clustered.meanCars); + expect(res.recency.pre).toEqual(raw.pre); + expect(res.recency.post).toEqual(raw.post); + if ((raw.pre.mean ?? 0) > 0) { + expect(res.recency.gate.pass).toBe(raw.gate.pass); + expect(res.recency.gate.ratio).toBe(raw.gate.ratio); + } + }); + + test('preDays = 0 makes caar equal caarFromZero and both fans identical at every offset', () => { + const rng = createMulberry32(830_005); + const T = 30; + const sessionDates = tradingDates(T); + const entityReturns = new Map(); + for (let e = 0; e < 4; e++) { + entityReturns.set(e, Float64Array.from({ length: T }, () => (rng() - 0.5) * 0.04)); + } + const events = Array.from({ length: 12 }, (_, i) => ({ entityId: i % 4, dayIndex: 2 + i * 2 })); + const res = okOrThrow( + eventStudy({ sessionDates, entityReturns, events }, { preDays: 0, postDays: 3, minEvents: 3 }) + ); + expect(res.offsets.map(o => o.offset)).toEqual([0, 1, 2, 3]); + for (const o of res.offsets) { + expect(o.caarFromZero).toBe(o.caar); + expect(o.postCarPercentiles).toEqual(o.carPercentiles); + } + }); + + test('compensated summation keeps AAR exact when large and small returns mix', () => { + const sessionDates = tradingDates(3); + const entityReturns = new Map(); + const vals = [1e8, 1, -1e8, 1, 1e8, -1e8]; + vals.forEach((v, i) => entityReturns.set(i, [0, v, 0])); + const events = vals.map((_, i) => ({ entityId: i, dayIndex: 1 })); + // one extra event on another date so nDates >= 2 (entity 0 day 2: return 0, window 0..0) + events.push({ entityId: 0, dayIndex: 2 }); + const res = okOrThrow( + eventStudy({ sessionDates, entityReturns, events }, { preDays: 0, postDays: 0, minEvents: 2 }) + ); + expect(res.offsets[0]!.aar).toBe(2 / 7); + expect(res.clustered.meanCars[0]).toBe(2 / 6); + }); +}); + +describe('event-study QA: degenerate inputs and validation gaps', () => { + test('empty calendar / empty events / empty entity map return insufficient_data with zeroed diagnostics', () => { + const empty = eventStudy({ sessionDates: [], entityReturns: new Map(), events: [] }); + expect(empty.status).toBe('insufficient_data'); + if (empty.status === 'insufficient_data') { + expect(empty.reason).toBe('below_min_events'); + expect(empty.nDates).toBe(0); + expect(empty.diagnostics).toEqual({ + eventsIn: 0, + eventsUsed: 0, + droppedUnknownEntity: 0, + droppedWindowOutOfRange: 0, + droppedMissingReturns: 0, + duplicateEventsCollapsed: 0, + }); + } + + const noEntities = eventStudy({ + sessionDates: tradingDates(3), + entityReturns: new Map(), + events: [ + { entityId: 1, dayIndex: 1 }, + { entityId: 1, dayIndex: 1 }, + ], + }); + expect(noEntities.diagnostics).toMatchObject({ + eventsIn: 2, + droppedUnknownEntity: 1, + duplicateEventsCollapsed: 1, + }); + }); + + test('huge dayIndex values are counted out of range, not wrapped through Int32 buffers', () => { + const sessionDates = tradingDates(10); + const entityReturns = new Map([[1, new Float64Array(10)]]); + const res = eventStudy( + { + sessionDates, + entityReturns, + events: [ + { entityId: 1, dayIndex: 2 ** 32 + 3 }, + { entityId: 1, dayIndex: 2 ** 31 }, + { entityId: 1, dayIndex: Number.MAX_SAFE_INTEGER }, + { entityId: 1, dayIndex: 3 }, + { entityId: 1, dayIndex: 4 }, + ], + }, + { preDays: 1, postDays: 1, minEvents: 2 } + ); + expect(res.status).toBe('ok'); + expect(res.diagnostics.droppedWindowOutOfRange).toBe(3); + expect(res.diagnostics.eventsUsed).toBe(2); + }); + + test('Infinity / holes anywhere in the benchmark or entity series throw, NaN entity key throws', () => { + const sessionDates = tradingDates(4); + const ok = new Float64Array(4); + const events = [{ entityId: 1, dayIndex: 1 }]; + expectCode( + () => + eventStudy({ + sessionDates, + entityReturns: new Map([[1, ok]]), + benchmarkReturns: [0, 0, 0, Number.NEGATIVE_INFINITY], + events, + }), + 'NON_FINITE_RETURN' + ); + // sparse array hole -> undefined, must not be silently treated as a return + const holey: number[] = new Array(4); + holey[0] = 0; + holey[1] = 0; + holey[3] = 0; + expectCode( + () => eventStudy({ sessionDates, entityReturns: new Map([[1, holey]]), events }), + 'NON_FINITE_RETURN' + ); + expectCode( + () => eventStudy({ sessionDates, entityReturns: new Map([[Number.NaN, ok]]), events }), + 'INVALID_EVENT' + ); + expectCode( + () => + eventStudy({ + sessionDates, + entityReturns: new Map([[1, ok]]), + events: [{ entityId: 1, dayIndex: Number.NaN }], + }), + 'INVALID_EVENT' + ); + expectCode( + () => eventStudy({ sessionDates: ['2022-1-03'], entityReturns: new Map(), events: [] }), + 'INVALID_DATE' + ); + expectCode( + () => eventStudy({ sessionDates: [], entityReturns: new Map(), events: [] }, { postDays: 0.5 }), + 'INVALID_OPTION' + ); + expectCode( + () => + eventStudy({ sessionDates: [], entityReturns: new Map(), events: [] }, { recencyMinRatio: -1 }), + 'INVALID_OPTION' + ); + }); + + test('negative effect strengthening post-split passes with ratio > 1 and keeps signed means', () => { + const pre = tradingDates(3, 2021); + const post = tradingDates(3, 2024); + const sessionDates = [...pre, ...post]; + const series = new Float64Array([-0.02, -0.02, -0.02, -0.05, -0.05, -0.05]); + const res = okOrThrow( + eventStudy( + { + sessionDates, + entityReturns: new Map([[1, series]]), + events: sessionDates.map((_, i) => ({ entityId: 1, dayIndex: i })), + }, + { preDays: 0, postDays: 0, minEvents: 2 } + ) + ); + expect(res.recency.pre.mean).toBeCloseTo(-0.02, 15); + expect(res.recency.post.mean).toBeCloseTo(-0.05, 15); + expect(res.recency.gate).toEqual({ pass: true, reason: 'passed', ratio: res.recency.gate.ratio }); + expect(res.recency.gate.ratio).toBeCloseTo(2.5, 12); + }); +}); diff --git a/libs/calculations/test/event-study.test.ts b/libs/calculations/test/event-study.test.ts new file mode 100644 index 00000000..45390b47 --- /dev/null +++ b/libs/calculations/test/event-study.test.ts @@ -0,0 +1,1398 @@ +import { describe, expect, test } from 'bun:test'; +import * as rootExports from '@stock-bot/calculations'; +import * as analyticsExports from '@stock-bot/calculations/analytics'; +import { + DEFAULT_EVENT_MIN_EVENTS, + DEFAULT_EVENT_POST_DAYS, + DEFAULT_EVENT_PRE_DAYS, + EventStudyError, + RECENCY_MIN_RATIO, + RECENCY_SPLIT_DATE, + eventDayIndex, + eventStudy, + neweyWestMeanTest, + type EntityId, + type EventStudyErrorCode, + type EventStudyEvent, + type EventStudyInput, + type EventStudyOptions, + type EventStudyPercentiles, + type EventStudyResult, +} from '@stock-bot/calculations'; + +function createMulberry32(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) / 4294967296; + }; +} + +function generateTradingDates(count: number, startYear = 2006): string[] { + const dates: string[] = new Array(count); + const dt = new Date(Date.UTC(startYear, 0, 2)); + let i = 0; + while (i < count) { + const dow = dt.getUTCDay(); + if (dow !== 0 && dow !== 6) { + const y = dt.getUTCFullYear(); + const m = String(dt.getUTCMonth() + 1).padStart(2, '0'); + const d = String(dt.getUTCDate()).padStart(2, '0'); + dates[i] = `${y}-${m}-${d}`; + i++; + } + dt.setUTCDate(dt.getUTCDate() + 1); + } + return dates; +} + +function assertNoNaNDeep(value: unknown): void { + if (typeof value === 'number') { + expect(Number.isFinite(value)).toBe(true); + return; + } + if (value instanceof Float64Array) { + for (let i = 0; i < value.length; i++) { + expect(Number.isFinite(value[i])).toBe(true); + } + return; + } + if (value instanceof Int32Array) { + return; + } + if (Array.isArray(value)) { + for (const item of value) { + assertNoNaNDeep(item); + } + return; + } + if (value !== null && typeof value === 'object') { + for (const entry of Object.values(value)) { + assertNoNaNDeep(entry); + } + } +} + +function expectEventStudyError(fn: () => unknown, code: EventStudyErrorCode): void { + try { + fn(); + throw new Error(`Expected EventStudyError(${code}) to be thrown`); + } catch (err) { + expect(err).toBeInstanceOf(EventStudyError); + expect(err).toBeInstanceOf(RangeError); + expect((err as EventStudyError).code).toBe(code); + } +} + +function assertAccountingIdentity(result: EventStudyResult): void { + const d = result.diagnostics; + expect(d.eventsIn).toBe( + d.eventsUsed + + d.droppedUnknownEntity + + d.droppedWindowOutOfRange + + d.droppedMissingReturns + + d.duplicateEventsCollapsed + ); +} + +function naiveR7Percentile(sorted: readonly number[], q: number): number { + const pos = q * (sorted.length - 1); + const lo = Math.floor(pos); + const hi = Math.ceil(pos); + if (lo === hi) { + return sorted[lo] as number; + } + const frac = pos - lo; + return (sorted[lo] as number) + frac * ((sorted[hi] as number) - (sorted[lo] as number)); +} + +function naivePercentiles(values: readonly number[]): EventStudyPercentiles { + const sorted = [...values].sort((a, b) => a - b); + return { + p5: naiveR7Percentile(sorted, 0.05), + p25: naiveR7Percentile(sorted, 0.25), + p50: naiveR7Percentile(sorted, 0.5), + p75: naiveR7Percentile(sorted, 0.75), + p95: naiveR7Percentile(sorted, 0.95), + }; +} + +interface NaiveReferenceResult { + readonly status: 'ok' | 'insufficient_data'; + readonly reason?: 'below_min_events' | 'too_few_event_dates'; + readonly diagnostics: { + readonly eventsIn: number; + readonly eventsUsed: number; + readonly droppedUnknownEntity: number; + readonly droppedWindowOutOfRange: number; + readonly droppedMissingReturns: number; + readonly duplicateEventsCollapsed: number; + }; + readonly offsets?: Array<{ + readonly offset: number; + readonly n: number; + readonly aar: number; + readonly standardError: number; + readonly caar: number; + readonly caarFromZero: number | null; + readonly carPercentiles: EventStudyPercentiles; + readonly postCarPercentiles: EventStudyPercentiles | null; + }>; + readonly eventCars?: readonly number[]; + readonly clusteredDates?: readonly string[]; + readonly clusteredCounts?: readonly number[]; + readonly clusteredMeanCars?: readonly number[]; + readonly carMean?: number; +} + +function naiveEventStudyReference( + input: EventStudyInput, + options?: EventStudyOptions +): NaiveReferenceResult { + const preDays = options?.preDays ?? DEFAULT_EVENT_PRE_DAYS; + const postDays = options?.postDays ?? DEFAULT_EVENT_POST_DAYS; + const minEvents = options?.minEvents ?? DEFAULT_EVENT_MIN_EVENTS; + const T = input.sessionDates.length; + + const seen = new Set(); + let droppedUnknownEntity = 0; + let droppedWindowOutOfRange = 0; + let droppedMissingReturns = 0; + let duplicateEventsCollapsed = 0; + + const usable: Array<{ entityId: EntityId; dayIndex: number }> = []; + + for (const ev of input.events) { + const key = `${typeof ev.entityId === 'number' ? 'n' : 's'}:${String(ev.entityId)}:${ev.dayIndex}`; + if (seen.has(key)) { + duplicateEventsCollapsed++; + continue; + } + seen.add(key); + + const series = input.entityReturns.get(ev.entityId); + if (!series) { + droppedUnknownEntity++; + continue; + } + if (ev.dayIndex - preDays < 0 || ev.dayIndex + postDays >= T) { + droppedWindowOutOfRange++; + continue; + } + let hasNaN = false; + for (let t = ev.dayIndex - preDays; t <= ev.dayIndex + postDays; t++) { + if (Number.isNaN(series[t])) { + hasNaN = true; + break; + } + if (input.benchmarkReturns && Number.isNaN(input.benchmarkReturns[t])) { + hasNaN = true; + break; + } + } + if (hasNaN) { + droppedMissingReturns++; + continue; + } + usable.push({ entityId: ev.entityId, dayIndex: ev.dayIndex }); + } + + usable.sort((a, b) => { + if (a.dayIndex !== b.dayIndex) { + return a.dayIndex - b.dayIndex; + } + const ta = typeof a.entityId; + const tb = typeof b.entityId; + if (ta !== tb) { + return ta === 'number' ? -1 : 1; + } + return a.entityId < b.entityId ? -1 : a.entityId > b.entityId ? 1 : 0; + }); + + const diagnostics = { + eventsIn: input.events.length, + eventsUsed: usable.length, + droppedUnknownEntity, + droppedWindowOutOfRange, + droppedMissingReturns, + duplicateEventsCollapsed, + }; + + const uniqueDates = new Set(usable.map(e => e.dayIndex)); + if (usable.length < minEvents) { + return { status: 'insufficient_data', reason: 'below_min_events', diagnostics }; + } + if (uniqueDates.size < 2) { + return { status: 'insufficient_data', reason: 'too_few_event_dates', diagnostics }; + } + + const M = usable.length; + const runningCar = new Array(M).fill(0); + const runningPostCar = new Array(M).fill(0); + let caar = 0; + let caarFromZero = 0; + const offsets: NonNullable = []; + + for (let k = preDays === 0 ? 0 : -preDays; k <= postDays; k++) { + const ars: number[] = []; + for (let i = 0; i < M; i++) { + const ev = usable[i]!; + const t = ev.dayIndex + k; + const ent = input.entityReturns.get(ev.entityId)![t]!; + const ar = input.benchmarkReturns ? ent - input.benchmarkReturns[t]! : ent; + ars.push(ar); + runningCar[i] = runningCar[i]! + ar; + if (k >= 0) { + runningPostCar[i] = runningPostCar[i]! + ar; + } + } + const aar = ars.reduce((s, v) => s + v, 0) / M; + const sumSq = ars.reduce((s, v) => s + (v - aar) * (v - aar), 0); + const standardError = Math.sqrt(sumSq / (M * (M - 1))); + caar += aar; + if (k >= 0) { + caarFromZero += aar; + } + offsets.push({ + offset: k, + n: M, + aar, + standardError, + caar, + caarFromZero: k >= 0 ? caarFromZero : null, + carPercentiles: naivePercentiles(runningCar), + postCarPercentiles: k >= 0 ? naivePercentiles(runningPostCar) : null, + }); + } + + const byDay = new Map(); + for (let i = 0; i < M; i++) { + const d = usable[i]!.dayIndex; + const arr = byDay.get(d); + if (arr) { + arr.push(runningPostCar[i]!); + } else { + byDay.set(d, [runningPostCar[i]!]); + } + } + const sortedDays = [...byDay.keys()].sort((a, b) => a - b); + const clusteredDates = sortedDays.map(d => input.sessionDates[d]!); + const clusteredCounts = sortedDays.map(d => byDay.get(d)!.length); + const clusteredMeanCars = sortedDays.map(d => { + const vals = byDay.get(d)!; + return vals.reduce((s, v) => s + v, 0) / vals.length; + }); + const carMean = + clusteredMeanCars.reduce((s, v) => s + v, 0) / clusteredMeanCars.length; + + return { + status: 'ok', + diagnostics, + offsets, + eventCars: runningPostCar, + clusteredDates, + clusteredCounts, + clusteredMeanCars, + carMean, + }; +} + +describe('event-study exports', () => { + test('both root and analytics entrypoints export the complete event-study surface', () => { + const names = [ + 'DEFAULT_EVENT_PRE_DAYS', + 'DEFAULT_EVENT_POST_DAYS', + 'DEFAULT_EVENT_MIN_EVENTS', + 'EventStudyError', + 'eventDayIndex', + 'eventStudy', + ] as const; + + for (const name of names) { + expect(rootExports[name]).toBeDefined(); + expect(analyticsExports[name]).toBe(rootExports[name]); + } + + expect(DEFAULT_EVENT_PRE_DAYS).toBe(10); + expect(DEFAULT_EVENT_POST_DAYS).toBe(20); + expect(DEFAULT_EVENT_MIN_EVENTS).toBe(5); + }); +}); + +describe('eventDayIndex', () => { + const closes = [1000, 2000, 3000, 4000, 5000]; + + test('maps before-first, exact-close, between-closes (zero look-ahead), after-last, and empty calendar', () => { + expect(eventDayIndex(closes, 500)).toEqual({ status: 'ok', dayIndex: 0 }); + expect(eventDayIndex(closes, 1000)).toEqual({ status: 'ok', dayIndex: 0 }); + expect(eventDayIndex(closes, 1001)).toEqual({ status: 'ok', dayIndex: 1 }); + expect(eventDayIndex(closes, 2000)).toEqual({ status: 'ok', dayIndex: 1 }); + expect(eventDayIndex(closes, 2500)).toEqual({ status: 'ok', dayIndex: 2 }); + expect(eventDayIndex(closes, 5000)).toEqual({ status: 'ok', dayIndex: 4 }); + expect(eventDayIndex(closes, 5001)).toEqual({ + status: 'no_session', + reason: 'after_last_session', + }); + expect(eventDayIndex([], 1000)).toEqual({ + status: 'no_session', + reason: 'empty_calendar', + }); + expect(eventDayIndex(new Float64Array(closes), 3000)).toEqual({ + status: 'ok', + dayIndex: 2, + }); + }); + + test('throws typed errors on unsorted, duplicate, off-probe-path inverted, or non-finite timestamps', () => { + expectEventStudyError(() => eventDayIndex(closes, Number.NaN), 'INVALID_TIMESTAMP'); + expectEventStudyError( + () => eventDayIndex(closes, Number.POSITIVE_INFINITY), + 'INVALID_TIMESTAMP' + ); + expectEventStudyError( + () => eventDayIndex([1000, Number.NaN, 3000], 1500), + 'INVALID_TIMESTAMP' + ); + expectEventStudyError( + () => eventDayIndex([1000, 2000, Number.NEGATIVE_INFINITY], 1500), + 'INVALID_TIMESTAMP' + ); + expectEventStudyError(() => eventDayIndex([1000, 2000, 2000, 3000], 1500), 'UNSORTED_TIMESTAMPS'); + // Off-probe-path inversion at the end while searching near index 0 + expectEventStudyError( + () => eventDayIndex([1000, 2000, 3000, 4000, 3500], 1000), + 'UNSORTED_TIMESTAMPS' + ); + }); +}); + +describe('eventStudy hand-computed golden fixture', () => { + // 3 entities, 12 sessions, 4 events, window -1..+2 + const sessionDates = [ + '2022-01-03', + '2022-01-04', + '2022-01-05', + '2022-01-06', + '2022-01-07', + '2022-01-10', + '2023-01-03', + '2023-01-04', + '2023-01-05', + '2023-01-06', + '2023-01-09', + '2023-01-10', + ]; + + // Simple exact decimal returns + const rA = [0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.02, 0.04, 0.06, 0.08, 0.01, 0.02]; + const rB = [0.0, 0.01, 0.02, 0.01, 0.03, 0.02, -0.01, 0.01, 0.03, 0.05, 0.02, 0.01]; + const rC = [0.02, -0.01, 0.01, 0.03, 0.02, 0.04, 0.03, 0.02, 0.01, 0.04, 0.05, 0.03]; + const bench = [0.005, 0.005, 0.01, 0.01, 0.01, 0.01, 0.005, 0.01, 0.01, 0.01, 0.005, 0.005]; + + // Events: + // E1: (A, 2) -> window [1..4], date 2022-01-05 + // E2: (B, 2) -> window [1..4], date 2022-01-05 + // E3: (C, 7) -> window [6..9], date 2023-01-04 + // E4: (A, 8) -> window [7..10], date 2023-01-05 + const entityReturns = new Map([ + ['A', rA], + ['B', rB], + ['C', rC], + ]); + const events: EventStudyEvent[] = [ + { entityId: 'A', dayIndex: 2 }, + { entityId: 'B', dayIndex: 2 }, + { entityId: 'C', dayIndex: 7 }, + { entityId: 'A', dayIndex: 8 }, + ]; + + test('matches hand-computed AAR, SE, CAAR, percentiles, CAR, and clustered stats without benchmark to 1e-12', () => { + const res = eventStudy( + { sessionDates, entityReturns, events }, + { preDays: 1, postDays: 2, minEvents: 4, neweyWestLag: 0 } + ); + expect(res.status).toBe('ok'); + assertAccountingIdentity(res); + if (res.status !== 'ok') { + return; + } + + expect(res.hasBenchmark).toBe(false); + expect(res.offsets.length).toBe(4); + + // Offset -1: A[1]=0.02, B[1]=0.01, C[6]=0.03, A[7]=0.04 -> mean = 0.025 + // sumSq = (-0.005)^2 + (-0.015)^2 + (0.005)^2 + (0.015)^2 = 0.0005 -> SE = sqrt(0.0005 / 12) + // Offset 0: A[2]=0.03, B[2]=0.02, C[7]=0.02, A[8]=0.06 -> mean = 0.0325 + // Offset +1: A[3]=0.04, B[3]=0.01, C[8]=0.01, A[9]=0.08 -> mean = 0.035 + // Offset +2: A[4]=0.05, B[4]=0.03, C[9]=0.04, A[10]=0.01 -> mean = 0.0325 + const expectedAar = [0.025, 0.0325, 0.035, 0.0325]; + const expectedSe = [ + Math.sqrt(0.0005 / 12), + Math.sqrt(0.001075 / 12), + Math.sqrt(0.0033 / 12), + Math.sqrt(0.000875 / 12), + ]; + const expectedCaar = [0.025, 0.0575, 0.0925, 0.125]; + const expectedCaarZero = [null, 0.0325, 0.0675, 0.1]; + + // Per-event running CAR[-1..k]: + // k = -1: [0.02, 0.01, 0.03, 0.04] -> sorted [0.01, 0.02, 0.03, 0.04] + // k = 0: [0.05, 0.03, 0.05, 0.10] -> sorted [0.03, 0.05, 0.05, 0.10] + // k = +1: [0.09, 0.04, 0.06, 0.18] -> sorted [0.04, 0.06, 0.09, 0.18] + // k = +2: [0.14, 0.07, 0.10, 0.19] -> sorted [0.07, 0.10, 0.14, 0.19] + const expectedCarPercentiles = [ + { p5: 0.0115, p25: 0.0175, p50: 0.025, p75: 0.0325, p95: 0.0385 }, + { p5: 0.033, p25: 0.045, p50: 0.05, p75: 0.0625, p95: 0.0925 }, + { p5: 0.043, p25: 0.055, p50: 0.075, p75: 0.1125, p95: 0.1665 }, + { p5: 0.0745, p25: 0.0925, p50: 0.12, p75: 0.1525, p95: 0.1825 }, + ]; + // Per-event running post-event CAR[0..k]: + // k = 0: [0.03, 0.02, 0.02, 0.06] -> sorted [0.02, 0.02, 0.03, 0.06] + // k = +1: [0.07, 0.03, 0.03, 0.14] -> sorted [0.03, 0.03, 0.07, 0.14] + // k = +2: [0.12, 0.06, 0.07, 0.15] -> sorted [0.06, 0.07, 0.12, 0.15] + const expectedPostCarPercentiles = [ + null, + { p5: 0.02, p25: 0.02, p50: 0.025, p75: 0.0375, p95: 0.0555 }, + { p5: 0.03, p25: 0.03, p50: 0.05, p75: 0.0875, p95: 0.1295 }, + { p5: 0.0615, p25: 0.0675, p50: 0.095, p75: 0.1275, p95: 0.1455 }, + ]; + + for (let w = 0; w < 4; w++) { + const off = res.offsets[w]!; + expect(off.offset).toBe(w - 1); + expect(off.n).toBe(4); + expect(Math.abs(off.aar - expectedAar[w]!)).toBeLessThan(1e-12); + expect(Math.abs(off.standardError - expectedSe[w]!)).toBeLessThan(1e-12); + expect(Math.abs(off.caar - expectedCaar[w]!)).toBeLessThan(1e-12); + + const expCarP = expectedCarPercentiles[w]!; + expect(Math.abs(off.carPercentiles.p5 - expCarP.p5)).toBeLessThan(1e-12); + expect(Math.abs(off.carPercentiles.p25 - expCarP.p25)).toBeLessThan(1e-12); + expect(Math.abs(off.carPercentiles.p50 - expCarP.p50)).toBeLessThan(1e-12); + expect(Math.abs(off.carPercentiles.p75 - expCarP.p75)).toBeLessThan(1e-12); + expect(Math.abs(off.carPercentiles.p95 - expCarP.p95)).toBeLessThan(1e-12); + + const expPostP = expectedPostCarPercentiles[w]!; + if (expectedCaarZero[w] === null || expPostP === null) { + expect(off.caarFromZero).toBeNull(); + expect(off.postCarPercentiles).toBeNull(); + } else { + expect(Math.abs((off.caarFromZero as number) - expectedCaarZero[w]!)).toBeLessThan(1e-12); + expect(off.postCarPercentiles).not.toBeNull(); + const postP = off.postCarPercentiles!; + expect(Math.abs(postP.p5 - expPostP.p5)).toBeLessThan(1e-12); + expect(Math.abs(postP.p25 - expPostP.p25)).toBeLessThan(1e-12); + expect(Math.abs(postP.p50 - expPostP.p50)).toBeLessThan(1e-12); + expect(Math.abs(postP.p75 - expPostP.p75)).toBeLessThan(1e-12); + expect(Math.abs(postP.p95 - expPostP.p95)).toBeLessThan(1e-12); + } + } + + // Per-event CAR[0..+2] in canonical (dayIndex ASC, entityId ASC) order + expect(res.eventCars.entityIds).toEqual(['A', 'B', 'C', 'A']); + expect(Array.from(res.eventCars.dayIndices)).toEqual([2, 2, 7, 8]); + const expectedCars = [0.12, 0.06, 0.07, 0.15]; + for (let i = 0; i < 4; i++) { + expect(Math.abs(res.eventCars.cars[i]! - expectedCars[i]!)).toBeLessThan(1e-12); + } + + // Clustered by date: + // 2022-01-05 (day 2): mean(0.12, 0.06) = 0.09 (count 2) + // 2023-01-04 (day 7): 0.07 (count 1) + // 2023-01-05 (day 8): 0.15 (count 1) + expect(res.clustered.nDates).toBe(3); + expect(res.clustered.dates).toEqual(['2022-01-05', '2023-01-04', '2023-01-05']); + expect(Array.from(res.clustered.eventCounts)).toEqual([2, 1, 1]); + const expectedClustered = [0.09, 0.07, 0.15]; + for (let i = 0; i < 3; i++) { + expect(Math.abs(res.clustered.meanCars[i]! - expectedClustered[i]!)).toBeLessThan(1e-12); + } + expect(Math.abs(res.clustered.carMean - 0.31 / 3)).toBeLessThan(1e-12); + const expectedNw = neweyWestMeanTest(expectedClustered, 0); + expect(res.clustered.neweyWest.status).toBe('ok'); + expect(expectedNw.status).toBe('ok'); + if (res.clustered.neweyWest.status === 'ok' && expectedNw.status === 'ok') { + expect(res.clustered.neweyWest.lag).toBe(expectedNw.lag); + expect( + Math.abs(res.clustered.neweyWest.longRunVariance - expectedNw.longRunVariance) + ).toBeLessThan(1e-12); + expect( + Math.abs(res.clustered.neweyWest.standardError - expectedNw.standardError) + ).toBeLessThan(1e-12); + expect(Math.abs(res.clustered.neweyWest.tStat - expectedNw.tStat)).toBeLessThan(1e-12); + } + assertNoNaNDeep(res); + }); + + test('matches hand-computed AAR, SE, CAAR, percentiles, CAR, and clustered stats with benchmark to 1e-12', () => { + const res = eventStudy( + { sessionDates, entityReturns, benchmarkReturns: bench, events }, + { preDays: 1, postDays: 2, minEvents: 4, neweyWestLag: 0 } + ); + expect(res.status).toBe('ok'); + assertAccountingIdentity(res); + if (res.status !== 'ok') { + return; + } + + expect(res.hasBenchmark).toBe(true); + expect(res.offsets.length).toBe(4); + + // Abnormal returns AR = r - bench at each offset: + // Offset -1: [0.015, 0.005, 0.025, 0.030] -> mean = 0.01875, sumSq = 0.00036875 + // Offset 0: [0.020, 0.010, 0.010, 0.050] -> mean = 0.0225, sumSq = 0.001075 + // Offset +1: [0.030, 0.000, 0.000, 0.070] -> mean = 0.025, sumSq = 0.0033 + // Offset +2: [0.040, 0.020, 0.030, 0.005] -> mean = 0.02375, sumSq = 0.00066875 + const expectedAar = [0.01875, 0.0225, 0.025, 0.02375]; + const expectedSe = [ + Math.sqrt(0.00036875 / 12), + Math.sqrt(0.001075 / 12), + Math.sqrt(0.0033 / 12), + Math.sqrt(0.00066875 / 12), + ]; + const expectedCaar = [0.01875, 0.04125, 0.06625, 0.09]; + const expectedCaarZero = [null, 0.0225, 0.0475, 0.07125]; + + // Per-event running benchmark-adjusted CAR[-1..k]: + // k = -1: [0.015, 0.005, 0.025, 0.030] -> sorted [0.005, 0.015, 0.025, 0.030] + // k = 0: [0.035, 0.015, 0.035, 0.080] -> sorted [0.015, 0.035, 0.035, 0.080] + // k = +1: [0.065, 0.015, 0.035, 0.150] -> sorted [0.015, 0.035, 0.065, 0.150] + // k = +2: [0.105, 0.035, 0.065, 0.155] -> sorted [0.035, 0.065, 0.105, 0.155] + const expectedCarPercentiles = [ + { p5: 0.0065, p25: 0.0125, p50: 0.02, p75: 0.02625, p95: 0.02925 }, + { p5: 0.018, p25: 0.03, p50: 0.035, p75: 0.04625, p95: 0.07325 }, + { p5: 0.018, p25: 0.03, p50: 0.05, p75: 0.08625, p95: 0.13725 }, + { p5: 0.0395, p25: 0.0575, p50: 0.085, p75: 0.1175, p95: 0.1475 }, + ]; + // Per-event running benchmark-adjusted post-event CAR[0..k]: + // k = 0: [0.02, 0.01, 0.01, 0.05] -> sorted [0.01, 0.01, 0.02, 0.05] + // k = +1: [0.05, 0.01, 0.01, 0.12] -> sorted [0.01, 0.01, 0.05, 0.12] + // k = +2: [0.09, 0.03, 0.04, 0.125] -> sorted [0.03, 0.04, 0.09, 0.125] + const expectedPostCarPercentiles = [ + null, + { p5: 0.01, p25: 0.01, p50: 0.015, p75: 0.0275, p95: 0.0455 }, + { p5: 0.01, p25: 0.01, p50: 0.03, p75: 0.0675, p95: 0.1095 }, + { p5: 0.0315, p25: 0.0375, p50: 0.065, p75: 0.09875, p95: 0.11975 }, + ]; + + for (let w = 0; w < 4; w++) { + const off = res.offsets[w]!; + expect(off.offset).toBe(w - 1); + expect(off.n).toBe(4); + expect(Math.abs(off.aar - expectedAar[w]!)).toBeLessThan(1e-12); + expect(Math.abs(off.standardError - expectedSe[w]!)).toBeLessThan(1e-12); + expect(Math.abs(off.caar - expectedCaar[w]!)).toBeLessThan(1e-12); + + const expCarP = expectedCarPercentiles[w]!; + expect(Math.abs(off.carPercentiles.p5 - expCarP.p5)).toBeLessThan(1e-12); + expect(Math.abs(off.carPercentiles.p25 - expCarP.p25)).toBeLessThan(1e-12); + expect(Math.abs(off.carPercentiles.p50 - expCarP.p50)).toBeLessThan(1e-12); + expect(Math.abs(off.carPercentiles.p75 - expCarP.p75)).toBeLessThan(1e-12); + expect(Math.abs(off.carPercentiles.p95 - expCarP.p95)).toBeLessThan(1e-12); + + const expPostP = expectedPostCarPercentiles[w]!; + if (expectedCaarZero[w] === null || expPostP === null) { + expect(off.caarFromZero).toBeNull(); + expect(off.postCarPercentiles).toBeNull(); + } else { + expect(Math.abs((off.caarFromZero as number) - expectedCaarZero[w]!)).toBeLessThan(1e-12); + expect(off.postCarPercentiles).not.toBeNull(); + const postP = off.postCarPercentiles!; + expect(Math.abs(postP.p5 - expPostP.p5)).toBeLessThan(1e-12); + expect(Math.abs(postP.p25 - expPostP.p25)).toBeLessThan(1e-12); + expect(Math.abs(postP.p50 - expPostP.p50)).toBeLessThan(1e-12); + expect(Math.abs(postP.p75 - expPostP.p75)).toBeLessThan(1e-12); + expect(Math.abs(postP.p95 - expPostP.p95)).toBeLessThan(1e-12); + } + } + + // Per-event benchmark-adjusted CAR[0..+2]: + // E1: 0.12 - (0.01+0.01+0.01) = 0.09 + // E2: 0.06 - (0.01+0.01+0.01) = 0.03 + // E3: 0.07 - (0.01+0.01+0.01) = 0.04 + // E4: 0.15 - (0.01+0.01+0.005) = 0.125 + const expectedCars = [0.09, 0.03, 0.04, 0.125]; + for (let i = 0; i < 4; i++) { + expect(Math.abs(res.eventCars.cars[i]! - expectedCars[i]!)).toBeLessThan(1e-12); + } + + // Clustered: day 2 -> mean(0.09, 0.03) = 0.06, day 7 -> 0.04, day 8 -> 0.125 + expect(res.clustered.nDates).toBe(3); + expect(res.clustered.dates).toEqual(['2022-01-05', '2023-01-04', '2023-01-05']); + expect(Array.from(res.clustered.eventCounts)).toEqual([2, 1, 1]); + const expectedClustered = [0.06, 0.04, 0.125]; + for (let i = 0; i < 3; i++) { + expect(Math.abs(res.clustered.meanCars[i]! - expectedClustered[i]!)).toBeLessThan(1e-12); + } + expect(Math.abs(res.clustered.carMean - 0.075)).toBeLessThan(1e-12); + const expectedNw = neweyWestMeanTest(expectedClustered, 0); + expect(res.clustered.neweyWest.status).toBe('ok'); + expect(expectedNw.status).toBe('ok'); + if (res.clustered.neweyWest.status === 'ok' && expectedNw.status === 'ok') { + expect(res.clustered.neweyWest.lag).toBe(expectedNw.lag); + expect( + Math.abs(res.clustered.neweyWest.longRunVariance - expectedNw.longRunVariance) + ).toBeLessThan(1e-12); + expect( + Math.abs(res.clustered.neweyWest.standardError - expectedNw.standardError) + ).toBeLessThan(1e-12); + expect(Math.abs(res.clustered.neweyWest.tStat - expectedNw.tStat)).toBeLessThan(1e-12); + } + assertNoNaNDeep(res); + }); +}); + +describe('eventStudy date clustering', () => { + test('10 events on one date + 1 event each on 5 other dates yields nDates = 6 and matches neweyWestMeanTest on 6 clustered means', () => { + const sessionDates = generateTradingDates(20, 2022); + const entityReturns = new Map(); + const events: EventStudyEvent[] = []; + + // 10 entities all having an event on dayIndex = 3 + for (let e = 0; e < 10; e++) { + const series = new Float64Array(20); + series[3] = 0.05 + e * 0.001; // CAR[0..0] = 0.05 + 0.001*e -> mean on day 3 = 0.0545 + entityReturns.set(`E${e}`, series); + events.push({ entityId: `E${e}`, dayIndex: 3 }); + } + + // 5 single-event dates on dayIndex = 5, 7, 9, 11, 13 + const otherDays = [5, 7, 9, 11, 13]; + const otherCars = [0.01, -0.02, 0.03, 0.04, -0.01]; + for (let i = 0; i < otherDays.length; i++) { + const id = `S${i}`; + const series = new Float64Array(20); + series[otherDays[i]!] = otherCars[i]!; + entityReturns.set(id, series); + events.push({ entityId: id, dayIndex: otherDays[i]! }); + } + + const res = eventStudy( + { sessionDates, entityReturns, events }, + { preDays: 1, postDays: 0, minEvents: 5 } + ); + expect(res.status).toBe('ok'); + if (res.status !== 'ok') { + return; + } + + expect(res.diagnostics.eventsUsed).toBe(15); + expect(res.clustered.nDates).toBe(6); + expect(Array.from(res.clustered.eventCounts)).toEqual([10, 1, 1, 1, 1, 1]); + + const expectedClustered = [0.0545, 0.01, -0.02, 0.03, 0.04, -0.01]; + for (let i = 0; i < 6; i++) { + expect(Math.abs(res.clustered.meanCars[i]! - expectedClustered[i]!)).toBeLessThan(1e-12); + } + + const nwClustered = neweyWestMeanTest(expectedClustered); + const nwUnclustered = neweyWestMeanTest(res.eventCars.cars); + expect(res.clustered.neweyWest.status).toBe('ok'); + expect(nwClustered.status).toBe('ok'); + expect(nwUnclustered.status).toBe('ok'); + if ( + res.clustered.neweyWest.status === 'ok' && + nwClustered.status === 'ok' && + nwUnclustered.status === 'ok' + ) { + expect(res.clustered.neweyWest.lag).toBe(nwClustered.lag); + expect(Math.abs(res.clustered.neweyWest.tStat - nwClustered.tStat)).toBeLessThan(1e-12); + expect(Math.abs(res.clustered.neweyWest.standardError - nwClustered.standardError)).toBeLessThan( + 1e-12 + ); + // Confirm clustering materially differs from unclustered 15-observation test + expect(Math.abs(res.clustered.neweyWest.tStat - nwUnclustered.tStat)).toBeGreaterThan(0.5); + } + }); +}); + +describe('eventStudy diagnostics and NaN scoping', () => { + test('accounts for every drop bucket, collapses duplicates, and ignores out-of-window NaNs', () => { + const sessionDates = generateTradingDates(12, 2023); + const s1 = new Float64Array([ + Number.NaN, // index 0 (out of window for dayIndex=4 with pre=2, post=2) + 0.01, + 0.02, + 0.03, + 0.04, + 0.05, + 0.06, + 0.01, + 0.02, + 0.03, + Number.NaN, // index 10 (out of window for dayIndex=4) + 0.01, + ]); + const s2 = new Float64Array([ + 0.01, + 0.02, + 0.03, + 0.04, + Number.NaN, // index 4 -> drops event on dayIndex=5 (window 3..7) + 0.01, + 0.02, + 0.03, + 0.04, + 0.05, + 0.01, + 0.02, + ]); + const bench = new Float64Array([ + Number.NaN, // index 0 (out of window for dayIndex=4) + 0.001, + 0.001, + 0.001, + 0.001, + 0.001, + 0.001, + 0.001, + Number.NaN, // index 8 -> drops event on dayIndex=7 (window 5..9) + 0.001, + 0.001, + 0.001, + ]); + + const entityReturns = new Map([ + [1, s1], + [2, s2], + ]); + + const events: EventStudyEvent[] = [ + // Valid usable events (3 total across 3 dates) + { entityId: 1, dayIndex: 4 }, // window 2..6 (index 0 and 10 NaNs are outside window!) + { entityId: 1, dayIndex: 5 }, // window 3..7 + { entityId: 1, dayIndex: 3 }, // window 1..5 + // Duplicate valid event -> duplicateEventsCollapsed (1) + { entityId: 1, dayIndex: 4 }, + // Unknown entities (2 distinct: number 99 and string "99", plus 1 duplicate of number 99) + { entityId: 99, dayIndex: 4 }, + { entityId: '99', dayIndex: 4 }, + { entityId: 99, dayIndex: 4 }, // duplicateEventsCollapsed (2) + // Window out of range: off start, off end, dayIndex >= T, plus duplicate off-start + { entityId: 1, dayIndex: 1 }, // 1 - 2 < 0 + { entityId: 1, dayIndex: 10 }, // 10 + 2 >= 12 + { entityId: 1, dayIndex: 25 }, // dayIndex >= T + { entityId: 1, dayIndex: 1 }, // duplicateEventsCollapsed (3) + // Missing returns: entity NaN in window, benchmark NaN in window, plus duplicate missing + { entityId: 2, dayIndex: 5 }, // s2[4] is NaN + { entityId: 1, dayIndex: 7 }, // bench[8] is NaN + { entityId: 2, dayIndex: 5 }, // duplicateEventsCollapsed (4) + ]; + + const res = eventStudy( + { sessionDates, entityReturns, benchmarkReturns: bench, events }, + { preDays: 2, postDays: 2, minEvents: 3 } + ); + + expect(res.status).toBe('ok'); + assertAccountingIdentity(res); + expect(res.diagnostics).toEqual({ + eventsIn: 14, + eventsUsed: 3, + droppedUnknownEntity: 2, + droppedWindowOutOfRange: 3, + droppedMissingReturns: 2, + duplicateEventsCollapsed: 4, + }); + }); +}); + +describe('eventStudy recency gate', () => { + function runRecencyScenario(preCars: readonly number[], postCars: readonly number[]) { + const preDates = generateTradingDates(preCars.length, 2022); + const postDates = generateTradingDates(postCars.length, 2023); + const sessionDates = [...preDates, ...postDates]; + const series = new Float64Array(sessionDates.length); + const events: EventStudyEvent[] = []; + + for (let i = 0; i < preCars.length; i++) { + series[i] = preCars[i]!; + events.push({ entityId: 1, dayIndex: i }); + } + for (let i = 0; i < postCars.length; i++) { + const idx = preCars.length + i; + series[idx] = postCars[i]!; + events.push({ entityId: 1, dayIndex: idx }); + } + + const res = eventStudy( + { sessionDates, entityReturns: new Map([[1, series]]), events }, + { + preDays: 0, + postDays: 0, + minEvents: 2, + recencySplitDate: RECENCY_SPLIT_DATE, + recencyMinRatio: RECENCY_MIN_RATIO, + } + ); + expect(res.status).toBe('ok'); + if (res.status !== 'ok') { + throw new Error('Expected ok'); + } + return res.recency; + } + + test('passes positive and negative effects meeting recencyMinRatio and exact boundary', () => { + const posPass = runRecencyScenario([0.08, 0.12], [0.06, 0.08]); + expect(posPass.gate.pass).toBe(true); + expect(posPass.gate.reason).toBe('passed'); + expect(Math.abs((posPass.gate.ratio as number) - 0.7)).toBeLessThan(1e-12); + expect(Math.abs((posPass.pre.mean as number) - 0.1)).toBeLessThan(1e-12); + expect(Math.abs((posPass.post.mean as number) - 0.07)).toBeLessThan(1e-12); + + const posBoundary = runRecencyScenario([0.08], [0.04]); + expect(posBoundary.gate.pass).toBe(true); + expect(posBoundary.gate.reason).toBe('passed'); + expect(posBoundary.gate.ratio).toBe(0.5); + + // Negative event effect (e.g. dilutive offering / short spike): preserves negative sign + const negPass = runRecencyScenario([-0.08, -0.12], [-0.06, -0.08]); + expect(negPass.gate.pass).toBe(true); + expect(negPass.gate.reason).toBe('passed'); + expect(Math.abs((negPass.gate.ratio as number) - 0.7)).toBeLessThan(1e-12); + expect(Math.abs((negPass.pre.mean as number) - -0.1)).toBeLessThan(1e-12); + expect(Math.abs((negPass.post.mean as number) - -0.07)).toBeLessThan(1e-12); + + const negBoundary = runRecencyScenario([-0.08], [-0.04]); + expect(negBoundary.gate.pass).toBe(true); + expect(negBoundary.gate.reason).toBe('passed'); + expect(negBoundary.gate.ratio).toBe(0.5); + }); + + test('fails with explicit reasons for sign flip, decay below ratio, zero pre-mean, and empty windows', () => { + // Sign flips: pos -> neg, neg -> pos, pos -> 0, neg -> 0 + const posToNeg = runRecencyScenario([0.08], [-0.04]); + expect(posToNeg.gate.pass).toBe(false); + expect(posToNeg.gate.reason).toBe('sign_flipped'); + + const negToPos = runRecencyScenario([-0.08], [0.04]); + expect(negToPos.gate.pass).toBe(false); + expect(negToPos.gate.reason).toBe('sign_flipped'); + + const posToZero = runRecencyScenario([0.08], [0]); + expect(posToZero.gate.pass).toBe(false); + expect(posToZero.gate.reason).toBe('sign_flipped'); + + const negToZero = runRecencyScenario([-0.08], [0]); + expect(negToZero.gate.pass).toBe(false); + expect(negToZero.gate.reason).toBe('sign_flipped'); + + // Decay below ratio (both signs) + const posDecay = runRecencyScenario([0.08], [0.039]); + expect(posDecay.gate.pass).toBe(false); + expect(posDecay.gate.reason).toBe('post_below_ratio_threshold'); + + const negDecay = runRecencyScenario([-0.08], [-0.039]); + expect(negDecay.gate.pass).toBe(false); + expect(negDecay.gate.reason).toBe('post_below_ratio_threshold'); + + // Zero pre-mean (exact and float-cancelled) + const zeroPre = runRecencyScenario([0], [0.05]); + expect(zeroPre.gate.pass).toBe(false); + expect(zeroPre.gate.reason).toBe('zero_pre_mean'); + expect(zeroPre.gate.ratio).toBeNull(); + + const cancelledNegPre = runRecencyScenario([-0.1, -0.2, 0.3], [-0.05]); + expect(cancelledNegPre.gate.pass).toBe(false); + expect(cancelledNegPre.gate.reason).toBe('zero_pre_mean'); + expect(cancelledNegPre.gate.ratio).toBeNull(); + + // Empty pre / post windows + const emptyPre = runRecencyScenario([], [0.05, 0.06]); + expect(emptyPre.gate.pass).toBe(false); + expect(emptyPre.gate.reason).toBe('empty_pre_window'); + + const emptyPost = runRecencyScenario([0.05, 0.06], []); + expect(emptyPost.gate.pass).toBe(false); + expect(emptyPost.gate.reason).toBe('empty_post_window'); + }); + + test('assigns complete CAR[0..postDays] to its event-date cohort across the split boundary', () => { + // Late-2022 event on 2022-12-30 has postDays=2 spanning 2023-01-03 and 2023-01-04. + // Its full CAR[0..2] (0.01 + 0.02 + 0.03 = 0.06) is assigned to the pre-2023 cohort by event date. + const sessionDates = [ + '2022-12-29', + '2022-12-30', + '2023-01-03', + '2023-01-04', + '2023-01-05', + '2023-01-06', + ]; + const series = new Float64Array([0.0, 0.01, 0.02, 0.03, 0.01, 0.0]); + const res = eventStudy( + { + sessionDates, + entityReturns: new Map([[1, series]]), + events: [ + { entityId: 1, dayIndex: 1 }, // 2022-12-30 (< 2023-01-01): CAR[0..2] = 0.01+0.02+0.03 = 0.06 + { entityId: 1, dayIndex: 2 }, // 2023-01-03 (>= 2023-01-01): CAR[0..2] = 0.02+0.03+0.01 = 0.06 + ], + }, + { + preDays: 0, + postDays: 2, + minEvents: 2, + recencySplitDate: RECENCY_SPLIT_DATE, + recencyMinRatio: RECENCY_MIN_RATIO, + } + ); + + expect(res.status).toBe('ok'); + if (res.status !== 'ok') { + return; + } + + expect(res.recency.pre.count).toBe(1); + expect(res.recency.post.count).toBe(1); + expect(Math.abs((res.recency.pre.mean as number) - 0.06)).toBeLessThan(1e-12); + expect(Math.abs((res.recency.post.mean as number) - 0.06)).toBeLessThan(1e-12); + expect(res.recency.gate.pass).toBe(true); + expect(res.recency.gate.reason).toBe('passed'); + expect(Math.abs((res.recency.gate.ratio as number) - 1.0)).toBeLessThan(1e-12); + }); +}); + +describe('eventStudy insufficient data, zero variance, and validation errors', () => { + const baseDates = ['2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06']; + const baseMap = new Map([ + ['A', new Float64Array([0.01, 0.02, 0.03, 0.04])], + ['B', new Float64Array([0.01, 0.02, 0.03, 0.04])], + ]); + + test('returns insufficient_data for below_min_events and too_few_event_dates without throwing', () => { + const belowMin = eventStudy( + { + sessionDates: baseDates, + entityReturns: baseMap, + events: [ + { entityId: 'A', dayIndex: 1 }, + { entityId: 'B', dayIndex: 2 }, + ], + }, + { preDays: 0, postDays: 0, minEvents: 5 } + ); + expect(belowMin.status).toBe('insufficient_data'); + assertAccountingIdentity(belowMin); + if (belowMin.status === 'insufficient_data') { + expect(belowMin.reason).toBe('below_min_events'); + expect(belowMin.eventsUsed).toBe(2); + expect(belowMin.nDates).toBe(2); + } + + const oneDate = eventStudy( + { + sessionDates: baseDates, + entityReturns: baseMap, + events: [ + { entityId: 'A', dayIndex: 1 }, + { entityId: 'B', dayIndex: 1 }, + ], + }, + { preDays: 0, postDays: 0, minEvents: 2 } + ); + expect(oneDate.status).toBe('insufficient_data'); + assertAccountingIdentity(oneDate); + if (oneDate.status === 'insufficient_data') { + expect(oneDate.reason).toBe('too_few_event_dates'); + expect(oneDate.eventsUsed).toBe(2); + expect(oneDate.nDates).toBe(1); + } + }); + + test('zero-variance clustered CARs return status ok with insufficient neweyWest and zero NaNs', () => { + const constantReturns = new Map([ + ['A', new Float64Array([0.02, 0.02, 0.02, 0.02])], + ]); + const res = eventStudy( + { + sessionDates: baseDates, + entityReturns: constantReturns, + events: [ + { entityId: 'A', dayIndex: 1 }, + { entityId: 'A', dayIndex: 2 }, + ], + }, + { preDays: 0, postDays: 0, minEvents: 2 } + ); + expect(res.status).toBe('ok'); + if (res.status === 'ok') { + expect(res.clustered.neweyWest.status).toBe('insufficient_data'); + expect(res.offsets[0]!.standardError).toBe(0); + assertNoNaNDeep(res); + } + }); + + test('throws every EventStudyErrorCode on malformed inputs and options', () => { + const validInput: EventStudyInput = { + sessionDates: baseDates, + entityReturns: baseMap, + events: [ + { entityId: 'A', dayIndex: 1 }, + { entityId: 'B', dayIndex: 2 }, + ], + }; + + // INVALID_OPTION + expectEventStudyError(() => eventStudy(validInput, { preDays: -1 }), 'INVALID_OPTION'); + expectEventStudyError(() => eventStudy(validInput, { preDays: 1.5 }), 'INVALID_OPTION'); + expectEventStudyError(() => eventStudy(validInput, { postDays: -1 }), 'INVALID_OPTION'); + expectEventStudyError(() => eventStudy(validInput, { minEvents: 0 }), 'INVALID_OPTION'); + expectEventStudyError(() => eventStudy(validInput, { neweyWestLag: -1 }), 'INVALID_OPTION'); + expectEventStudyError(() => eventStudy(validInput, { recencyMinRatio: 0 }), 'INVALID_OPTION'); + expectEventStudyError( + () => eventStudy(validInput, { recencyMinRatio: Number.POSITIVE_INFINITY }), + 'INVALID_OPTION' + ); + + // INVALID_DATE + expectEventStudyError( + () => eventStudy(validInput, { recencySplitDate: '2023-02-29' }), + 'INVALID_DATE' + ); + expectEventStudyError( + () => eventStudy({ ...validInput, sessionDates: ['2023-02-29'] }), + 'INVALID_DATE' + ); + + // UNSORTED_DATES & DUPLICATE_DATE + expectEventStudyError( + () => eventStudy({ ...validInput, sessionDates: ['2022-01-04', '2022-01-03'] }), + 'UNSORTED_DATES' + ); + expectEventStudyError( + () => eventStudy({ ...validInput, sessionDates: ['2022-01-03', '2022-01-03'] }), + 'DUPLICATE_DATE' + ); + + // LENGTH_MISMATCH + expectEventStudyError( + () => + eventStudy({ + ...validInput, + entityReturns: new Map([['A', [0.01, 0.02]]]), + }), + 'LENGTH_MISMATCH' + ); + expectEventStudyError( + () => + eventStudy({ + ...validInput, + benchmarkReturns: [0.01, 0.02], + }), + 'LENGTH_MISMATCH' + ); + + // NON_FINITE_RETURN (even outside any event window) + expectEventStudyError( + () => + eventStudy({ + ...validInput, + entityReturns: new Map([ + ['A', [0.01, 0.02, 0.03, Number.POSITIVE_INFINITY]], + ]), + }), + 'NON_FINITE_RETURN' + ); + expectEventStudyError( + () => + eventStudy({ + ...validInput, + benchmarkReturns: [Number.NEGATIVE_INFINITY, 0.01, 0.02, 0.03], + }), + 'NON_FINITE_RETURN' + ); + + // INVALID_EVENT + expectEventStudyError( + () => + eventStudy({ + ...validInput, + events: [{ entityId: 'A', dayIndex: -1 }], + }), + 'INVALID_EVENT' + ); + expectEventStudyError( + () => + eventStudy({ + ...validInput, + events: [{ entityId: 'A', dayIndex: 1.25 }], + }), + 'INVALID_EVENT' + ); + expectEventStudyError( + () => + eventStudy({ + ...validInput, + events: [{ entityId: Number.NaN, dayIndex: 1 }], + }), + 'INVALID_EVENT' + ); + expectEventStudyError( + () => + eventStudy({ + ...validInput, + entityReturns: new Map([[Number.NaN, [0.01, 0.02, 0.03, 0.04]]]), + }), + 'INVALID_EVENT' + ); + }); +}); + +describe('eventStudy determinism and differential parity', () => { + test('produces bit-identical output under shuffled events and reversed entityReturns Map', () => { + const rng = createMulberry32(987654321); + const T = 60; + const E = 20; + const sessionDates = generateTradingDates(T, 2022); + const entries: Array<[EntityId, Float64Array]> = []; + for (let e = 0; e < E; e++) { + const id: EntityId = e % 2 === 0 ? e : `SYM_${e}`; + const arr = new Float64Array(T); + for (let t = 0; t < T; t++) { + arr[t] = (rng() - 0.49) * 0.04; + } + entries.push([id, arr]); + } + const bench = new Float64Array(T); + for (let t = 0; t < T; t++) { + bench[t] = (rng() - 0.5) * 0.01; + } + + const events: EventStudyEvent[] = []; + for (let i = 0; i < 120; i++) { + const id = entries[Math.floor(rng() * E)]![0]; + const dayIndex = 5 + Math.floor(rng() * (T - 12)); + events.push({ entityId: id, dayIndex }); + } + + const shuffledEvents = [...events]; + for (let i = shuffledEvents.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const tmp = shuffledEvents[i]!; + shuffledEvents[i] = shuffledEvents[j]!; + shuffledEvents[j] = tmp; + } + + const mapForward = new Map(entries); + const mapReverse = new Map([...entries].reverse()); + + const resA = eventStudy( + { sessionDates, entityReturns: mapForward, benchmarkReturns: bench, events }, + { preDays: 3, postDays: 5 } + ); + const resB = eventStudy( + { + sessionDates, + entityReturns: mapReverse, + benchmarkReturns: bench, + events: shuffledEvents, + }, + { preDays: 3, postDays: 5 } + ); + + expect(resA).toEqual(resB); + expect(resA.status).toBe('ok'); + expect(resB.status).toBe('ok'); + if (resA.status === 'ok' && resB.status === 'ok') { + for (let w = 0; w < resA.offsets.length; w++) { + const a = resA.offsets[w]!; + const b = resB.offsets[w]!; + expect(Object.is(a.aar, b.aar)).toBe(true); + expect(Object.is(a.standardError, b.standardError)).toBe(true); + expect(Object.is(a.caar, b.caar)).toBe(true); + expect(Object.is(a.caarFromZero, b.caarFromZero)).toBe(true); + expect(Object.is(a.carPercentiles.p5, b.carPercentiles.p5)).toBe(true); + expect(Object.is(a.carPercentiles.p50, b.carPercentiles.p50)).toBe(true); + expect(Object.is(a.carPercentiles.p95, b.carPercentiles.p95)).toBe(true); + } + for (let i = 0; i < resA.eventCars.cars.length; i++) { + expect(Object.is(resA.eventCars.cars[i], resB.eventCars.cars[i])).toBe(true); + } + for (let i = 0; i < resA.clustered.meanCars.length; i++) { + expect(Object.is(resA.clustered.meanCars[i], resB.clustered.meanCars[i])).toBe(true); + } + expect(Object.is(resA.clustered.carMean, resB.clustered.carMean)).toBe(true); + } + }); + + test('agrees with independent naive reference to 1e-12 across 200 seeded random panels', () => { + const rng = createMulberry32(20260403); + + for (let trial = 0; trial < 200; trial++) { + const T = 15 + Math.floor(rng() * 35); + const E = 3 + Math.floor(rng() * 12); + const preDays = Math.floor(rng() * 5); + const postDays = Math.floor(rng() * 6); + const minEvents = 2 + Math.floor(rng() * 4); + const useBench = rng() < 0.5; + const driftSign = rng() < 0.5 ? 1 : -1; + // Mix small (<65) and larger (>=65) event counts to exercise both percentile paths + const nEvents = trial % 5 === 0 ? 80 + Math.floor(rng() * 40) : 4 + Math.floor(rng() * 30); + + const sessionDates = generateTradingDates(T, 2022); + const entityReturns = new Map(); + const entityIds: EntityId[] = []; + + for (let e = 0; e < E; e++) { + const id: EntityId = e % 3 === 0 ? e : `E${e}`; + entityIds.push(id); + const arr = new Float64Array(T); + for (let t = 0; t < T; t++) { + arr[t] = rng() < 0.04 ? Number.NaN : driftSign * 0.002 + (rng() - 0.5) * 0.05; + } + entityReturns.set(id, arr); + } + + let benchmarkReturns: Float64Array | undefined; + if (useBench) { + benchmarkReturns = new Float64Array(T); + for (let t = 0; t < T; t++) { + benchmarkReturns[t] = rng() < 0.02 ? Number.NaN : (rng() - 0.5) * 0.02; + } + } + + const events: EventStudyEvent[] = []; + for (let i = 0; i < nEvents; i++) { + if (rng() < 0.05) { + events.push({ entityId: 'UNKNOWN', dayIndex: Math.floor(rng() * (T + 3)) }); + } else if (events.length > 0 && rng() < 0.1) { + events.push({ ...events[Math.floor(rng() * events.length)]! }); + } else { + const id = entityIds[Math.floor(rng() * E)]!; + const dayIndex = Math.floor(rng() * (T + 2)); + events.push({ entityId: id, dayIndex }); + } + } + + const input: EventStudyInput = { + sessionDates, + entityReturns, + benchmarkReturns, + events, + }; + const opts: EventStudyOptions = { preDays, postDays, minEvents }; + + const actual = eventStudy(input, opts); + const ref = naiveEventStudyReference(input, opts); + + assertAccountingIdentity(actual); + expect(actual.status).toBe(ref.status); + expect(actual.diagnostics).toEqual(ref.diagnostics); + + if (actual.status === 'insufficient_data') { + expect(actual.reason).toBe(ref.reason); + continue; + } + + assertNoNaNDeep(actual); + expect(actual.offsets.length).toBe(ref.offsets!.length); + for (let w = 0; w < actual.offsets.length; w++) { + const a = actual.offsets[w]!; + const r = ref.offsets![w]!; + expect(a.offset).toBe(r.offset); + expect(a.n).toBe(r.n); + expect(Math.abs(a.aar - r.aar)).toBeLessThan(1e-12); + expect(Math.abs(a.standardError - r.standardError)).toBeLessThan(1e-12); + expect(Math.abs(a.caar - r.caar)).toBeLessThan(1e-12); + if (r.caarFromZero === null) { + expect(a.caarFromZero).toBeNull(); + expect(a.postCarPercentiles).toBeNull(); + } else { + expect(Math.abs((a.caarFromZero as number) - r.caarFromZero)).toBeLessThan(1e-12); + for (const key of ['p5', 'p25', 'p50', 'p75', 'p95'] as const) { + expect( + Math.abs(a.postCarPercentiles![key] - r.postCarPercentiles![key]) + ).toBeLessThan(1e-12); + } + } + for (const key of ['p5', 'p25', 'p50', 'p75', 'p95'] as const) { + expect(Math.abs(a.carPercentiles[key] - r.carPercentiles[key])).toBeLessThan(1e-12); + } + } + + expect(actual.eventCars.cars.length).toBe(ref.eventCars!.length); + for (let i = 0; i < ref.eventCars!.length; i++) { + expect(Math.abs(actual.eventCars.cars[i]! - ref.eventCars![i]!)).toBeLessThan(1e-12); + } + + expect(actual.clustered.dates).toEqual(ref.clusteredDates!); + expect(Array.from(actual.clustered.eventCounts)).toEqual(ref.clusteredCounts!); + for (let i = 0; i < ref.clusteredMeanCars!.length; i++) { + expect( + Math.abs(actual.clustered.meanCars[i]! - ref.clusteredMeanCars![i]!) + ).toBeLessThan(1e-12); + } + expect(Math.abs(actual.clustered.carMean - ref.carMean!)).toBeLessThan(1e-12); + } + }); +}); + +describe('eventStudy benchmark', () => { + test( + '2,000 entities x 5,040 sessions, 200,000 events, window -10..+20 completes <= 5,000 ms', + () => { + const ENTITIES = 2_000; + const SESSIONS = 5_040; + const EVENTS = 200_000; + const PRE_DAYS = 10; + const POST_DAYS = 20; + + const rng = createMulberry32(20260404); + const sessionDates = generateTradingDates(SESSIONS, 2006); + const benchmarkReturns = new Float64Array(SESSIONS); + for (let t = 0; t < SESSIONS; t++) { + benchmarkReturns[t] = (rng() - 0.5) * 0.015; + } + + const entityReturns = new Map(); + for (let e = 0; e < ENTITIES; e++) { + const arr = new Float64Array(SESSIONS); + for (let t = 0; t < SESSIONS; t++) { + arr[t] = (rng() - 0.499) * 0.03; + } + entityReturns.set(e, arr); + } + + // Generate 200,000 distinct in-range (entityId, dayIndex) pairs deterministically: + // 100 distinct event days per entity across [PRE_DAYS, SESSIONS - POST_DAYS - 1]. + const minDay = PRE_DAYS; + const validSpan = SESSIONS - POST_DAYS - minDay; // 5010 + const eventsPerEntity = EVENTS / ENTITIES; // 100 + const stride = Math.floor(validSpan / eventsPerEntity); // 50 + const events: EventStudyEvent[] = new Array(EVENTS); + let idx = 0; + for (let e = 0; e < ENTITIES; e++) { + const offset = Math.floor(rng() * stride); + for (let k = 0; k < eventsPerEntity; k++) { + events[idx++] = { + entityId: e, + dayIndex: minDay + k * stride + offset, + }; + } + } + + const t0 = performance.now(); + const res = eventStudy( + { sessionDates, entityReturns, benchmarkReturns, events }, + { preDays: PRE_DAYS, postDays: POST_DAYS } + ); + const elapsedMs = performance.now() - t0; + const eventsPerSec = Math.round((EVENTS / elapsedMs) * 1000); + + process.stdout.write( + `[event-study benchmark] events=${EVENTS} window=-${PRE_DAYS}..+${POST_DAYS} elapsedMs=${elapsedMs.toFixed(2)} events/s=${eventsPerSec}\n` + ); + + expect(res.status).toBe('ok'); + assertAccountingIdentity(res); + if (res.status === 'ok') { + expect(res.diagnostics.eventsUsed).toBe(EVENTS); + expect(res.offsets.length).toBe(PRE_DAYS + POST_DAYS + 1); + } + expect(elapsedMs).toBeLessThanOrEqual(5_000); + }, + 15_000 + ); +}); diff --git a/libs/calculations/test/signal-analysis-qa.test.ts b/libs/calculations/test/signal-analysis-qa.test.ts new file mode 100644 index 00000000..7a0954c0 --- /dev/null +++ b/libs/calculations/test/signal-analysis-qa.test.ts @@ -0,0 +1,541 @@ +import { describe, expect, test } from 'bun:test'; +import { + analyzeSignalPanel, + crossSectionIc, + evaluateRecencyGate, + neweyWestMeanTest, + SignalAnalysisError, + summarizeIcSeries, + type EntityId, + type SignalAnalysisOptions, + type SignalCrossSection, + type SignalPanelAnalysis, +} from '@stock-bot/calculations'; + +// QA reference: a deliberately naive, allocation-heavy implementation written from the +// T-82 spec (not from the module under test). The optimized panel path must match it +// date by date so a failure names the first diverging date and stage. + +function createMulberry32(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) / 4294967296; + }; +} + +interface Row { + readonly id: EntityId; + readonly s: number; + readonly r: number; +} + +function refCompareIds(a: EntityId, b: EntityId): number { + if (typeof a === 'number' && typeof b === 'number') { + return a - b; + } + if (typeof a === 'string' && typeof b === 'string') { + return a < b ? -1 : a > b ? 1 : 0; + } + return typeof a === 'number' ? -1 : 1; +} + +function refPearson(x: readonly number[], y: readonly number[]): number | null { + const n = x.length; + const mx = x.reduce((a, v) => a + v, 0) / n; + const my = y.reduce((a, v) => a + v, 0) / n; + let sxy = 0; + let sxx = 0; + let syy = 0; + for (let i = 0; i < n; i++) { + const dx = (x[i] as number) - mx; + const dy = (y[i] as number) - my; + sxy += dx * dy; + sxx += dx * dx; + syy += dy * dy; + } + if (sxx === 0 || syy === 0) { + return null; + } + return sxy / Math.sqrt(sxx * syy); +} + +function refAverageRanks(values: readonly number[]): number[] { + const idx = values.map((_, i) => i).sort((a, b) => (values[a] as number) - (values[b] as number)); + const ranks = new Array(values.length).fill(0); + let i = 0; + while (i < idx.length) { + let j = i; + while (j + 1 < idx.length && values[idx[j + 1] as number] === values[idx[i] as number]) { + j++; + } + for (let k = i; k <= j; k++) { + ranks[idx[k] as number] = (i + j) / 2 + 1; + } + i = j + 1; + } + return ranks; +} + +interface RefDate { + readonly date: string; + readonly ic: { pearson: number; rank: number } | null; + readonly buckets: number[] | null; + readonly top: Set | null; + readonly bottom: Set | null; +} + +function refAnalyze( + panel: readonly SignalCrossSection[], + minCross: number, + q: number, + cutoff?: string +): RefDate[] { + const out: RefDate[] = []; + for (const slice of panel) { + if (cutoff !== undefined && slice.date >= cutoff) { + continue; + } + const rows: Row[] = []; + for (let i = 0; i < slice.signal.length; i++) { + const s = slice.signal[i] as number; + const r = slice.forwardReturn[i] as number; + if (Number.isFinite(s) && Number.isFinite(r)) { + rows.push({ id: slice.ids[i] as EntityId, s, r }); + } + } + rows.sort((a, b) => (a.s !== b.s ? a.s - b.s : refCompareIds(a.id, b.id))); + const m = rows.length; + + let ic: RefDate['ic'] = null; + if (m >= minCross) { + const xs = rows.map(row => row.s); + const ys = rows.map(row => row.r); + const p = refPearson(xs, ys); + const rk = p === null ? null : refPearson(refAverageRanks(xs), refAverageRanks(ys)); + ic = p === null || rk === null ? null : { pearson: p, rank: rk }; + } + + let buckets: number[] | null = null; + let top: Set | null = null; + let bottom: Set | null = null; + if (m >= q) { + buckets = []; + for (let b = 0; b < q; b++) { + const members = rows.slice(Math.floor((b * m) / q), Math.floor(((b + 1) * m) / q)); + buckets.push(members.reduce((a, row) => a + row.r, 0) / members.length); + if (b === 0) { + bottom = new Set(members.map(row => row.id)); + } + if (b === q - 1) { + top = new Set(members.map(row => row.id)); + } + } + } + out.push({ date: slice.date, ic, buckets, top, bottom }); + } + return out; +} + +function turnoverOf(curr: Set, prev: Set): number { + let overlap = 0; + for (const id of curr) { + if (prev.has(id)) { + overlap++; + } + } + return 1 - overlap / curr.size; +} + +function compareToReference( + panel: readonly SignalCrossSection[], + options: SignalAnalysisOptions, + res: SignalPanelAnalysis +): void { + const ref = refAnalyze( + panel, + options.minCrossSection ?? 5, + options.quantiles ?? 5, + options.vaultCutoffDate + ); + const refIc = ref.filter(d => d.ic !== null); + expect(res.dates).toEqual(refIc.map(d => d.date)); + refIc.forEach((d, i) => { + const ic = d.ic as { pearson: number; rank: number }; + const label = `${d.date} IC`; + expect([label, Math.abs((res.pearsonIcSeries[i] as number) - ic.pearson) < 1e-12]).toEqual([ + label, + true, + ]); + expect([label, Math.abs((res.rankIcSeries[i] as number) - ic.rank) < 1e-12]).toEqual([ + label, + true, + ]); + }); + + const refQ = ref.filter(d => d.buckets !== null); + expect(res.quantiles.dates).toEqual(refQ.map(d => d.date)); + refQ.forEach((d, i) => { + const buckets = d.buckets as number[]; + buckets.forEach((value, b) => { + const label = `${d.date} bucket ${b}`; + const actual = (res.quantiles.perBucketSeries[b] as Float64Array)[i] as number; + expect([label, Math.abs(actual - value) < 1e-12]).toEqual([label, true]); + }); + const spread = (buckets[buckets.length - 1] as number) - (buckets[0] as number); + expect(Math.abs((res.quantiles.spreadSeries[i] as number) - spread)).toBeLessThan(1e-12); + }); + + const refTurnDates: string[] = []; + for (let i = 1; i < refQ.length; i++) { + const curr = refQ[i] as RefDate; + const prev = refQ[i - 1] as RefDate; + refTurnDates.push(curr.date); + const k = i - 1; + const top = turnoverOf(curr.top as Set, prev.top as Set); + const bottom = turnoverOf(curr.bottom as Set, prev.bottom as Set); + expect([curr.date, res.turnover.topSeries[k]]).toEqual([curr.date, top]); + expect([curr.date, res.turnover.bottomSeries[k]]).toEqual([curr.date, bottom]); + } + expect(res.turnover.dates).toEqual(refTurnDates); +} + +function buildRandomPanel(seed: number, nDates: number, stringIds: boolean): SignalCrossSection[] { + const rnd = createMulberry32(seed); + const panel: SignalCrossSection[] = []; + const universe = 40; + for (let t = 0; t < nDates; t++) { + // Mix of tiny (skipped), uneven (m % q != 0) and normal cross-sections. + const n = 2 + Math.floor(rnd() * 30); + const pool = Array.from({ length: universe }, (_, i) => i); + for (let i = pool.length - 1; i > 0; i--) { + const j = Math.floor(rnd() * (i + 1)); + [pool[i], pool[j]] = [pool[j] as number, pool[i] as number]; + } + const ids: EntityId[] = []; + const signal: number[] = []; + const forwardReturn: number[] = []; + for (let i = 0; i < n; i++) { + const raw = pool[i] as number; + ids.push(stringIds ? `T${String(raw).padStart(3, '0')}` : raw * 1000 + 70000); + // Coarse grid -> heavy ties in both signal and returns. + const s = Math.round(rnd() * 6) / 2; + let r = Math.round((s * 0.01 + (rnd() - 0.5) * 0.04) * 200) / 200; + const u = rnd(); + if (u < 0.04) { + r = Number.NaN; + } else if (u < 0.06) { + r = Number.NEGATIVE_INFINITY; + } + signal.push(rnd() < 0.03 ? Number.NaN : s); + forwardReturn.push(r); + } + // 48 sorted dates per year starting 2021 (day 1/8/15/22 of each month). + const year = 2021 + Math.floor(t / 48); + const month = Math.floor((t % 48) / 4) + 1; + const dayOfMonth = (t % 4) * 7 + 1; + const day = `${year}-${String(month).padStart(2, '0')}-${String(dayOfMonth).padStart(2, '0')}`; + panel.push({ date: day, ids, signal, forwardReturn }); + } + return panel; +} + +describe('signal-analysis QA: optimized panel matches a naive reference loop', () => { + for (const [seed, stringIds] of [ + [101, false], + [202, true], + [303, false], + ] as const) { + test(`seed ${seed} (${stringIds ? 'string' : 'numeric >= 65536'} ids, ties, NaN/Inf, uneven buckets)`, () => { + const panel = buildRandomPanel(seed, 160, stringIds); + const options: SignalAnalysisOptions = { + minCrossSection: 6, + quantiles: 4, + vaultCutoffDate: '2023-09-01', + }; + const res = analyzeSignalPanel(panel, options); + expect(res.diagnostics.vaultExcludedDates).toBeGreaterThan(0); + expect(res.diagnostics.quantileSkippedDates).toBeGreaterThan(0); + expect(res.rankIcSeries.length).toBeGreaterThan(30); + expect(res.turnover.count).toBeGreaterThan(30); + compareToReference(panel, options, res); + + // Per-date Pearson/rank-IC agree with the standalone crossSectionIc entry point. + let k = 0; + for (const slice of panel) { + if (slice.date >= '2023-09-01') { + break; + } + const single = crossSectionIc(slice.signal, slice.forwardReturn, { minCrossSection: 6 }); + if (single.status === 'ok') { + expect(Math.abs(single.pearsonIc - (res.pearsonIcSeries[k] as number))).toBeLessThan( + 1e-12 + ); + expect(Math.abs(single.rankIc - (res.rankIcSeries[k] as number))).toBeLessThan(1e-12); + k++; + } + } + expect(k).toBe(res.rankIcSeries.length); + + // Diagnostics accounting closes. + const d = res.diagnostics; + expect(d.validObservations + d.droppedPairs).toBe(d.totalObservations); + expect(d.icValidDates + d.icSkippedBelowMin + d.icSkippedZeroVariance).toBe(d.eligibleDates); + expect(d.quantileValidDates + d.quantileSkippedDates).toBe(d.eligibleDates); + expect(d.eligibleDates + d.vaultExcludedDates).toBe(d.totalDates); + expect(res.recency.pre.count + res.recency.post.count).toBe(res.rankIcSeries.length); + }); + } + + test('uneven bucket sizes (7 names, q = 5) use floor(b*m/q) boundaries and |A_t| as turnover denominator', () => { + const panel: SignalCrossSection[] = [ + { + date: '2022-03-01', + ids: [1, 2, 3, 4, 5, 6, 7], + signal: [1, 2, 3, 4, 5, 6, 7], + forwardReturn: [1, 2, 3, 4, 5, 6, 7], + }, + // Top bucket (2 names) keeps id 7 only -> 0.5; bottom (1 name) id 2 replaces id 1 -> 1. + { + date: '2022-03-02', + ids: [1, 2, 3, 4, 5, 6, 7], + signal: [3, 1, 2, 4, 7, 5, 6], + forwardReturn: [1, 2, 3, 4, 5, 6, 7], + }, + ]; + const res = analyzeSignalPanel(panel, { quantiles: 5 }); + // Buckets: [0,1) [1,2) [2,4) [4,5) [5,7) + expect(Array.from(res.quantiles.perBucketSeries, s => s[0])).toEqual([1, 2, 3.5, 5, 6.5]); + expect(res.quantiles.spreadSeries[0]).toBe(5.5); + expect(Array.from(res.turnover.topSeries)).toEqual([0.5]); + expect(Array.from(res.turnover.bottomSeries)).toEqual([1]); + }); + + test('turnover links to the previous valid quantile date across a skipped date', () => { + const ids = [1, 2, 3, 4]; + const panel: SignalCrossSection[] = [ + { date: '2022-03-01', ids, signal: [1, 2, 3, 4], forwardReturn: [0, 0, 0, 1] }, + { + date: '2022-03-02', + ids, + signal: [1, Number.NaN, Number.NaN, Number.NaN], + forwardReturn: [0, 0, 0, 0], + }, + { date: '2022-03-03', ids, signal: [1, 2, 3, 4], forwardReturn: [0, 0, 0, 1] }, + ]; + const res = analyzeSignalPanel(panel, { quantiles: 2, minCrossSection: 2 }); + expect(res.quantiles.skippedDates).toBe(1); + expect(res.turnover.dates).toEqual(['2022-03-03']); + expect(Array.from(res.turnover.topSeries)).toEqual([0]); + }); +}); + +describe('signal-analysis QA: ids, determinism and isolation', () => { + test('typed-array inputs give bit-identical results to plain arrays and inputs are not mutated', () => { + const panel = buildRandomPanel(404, 40, false); + const typed: SignalCrossSection[] = panel.map(slice => ({ + date: slice.date, + ids: Uint32Array.from(slice.ids as number[]), + signal: Float64Array.from(slice.signal), + forwardReturn: Float64Array.from(slice.forwardReturn), + })); + const snapshot = JSON.stringify( + panel.map(s => [s.ids, Array.from(s.signal, String), Array.from(s.forwardReturn, String)]) + ); + const a = analyzeSignalPanel(panel); + const b = analyzeSignalPanel(typed); + const c = analyzeSignalPanel(panel); + expect(b).toEqual(a); + expect(c).toEqual(a); + expect( + JSON.stringify( + panel.map(s => [s.ids, Array.from(s.signal, String), Array.from(s.forwardReturn, String)]) + ) + ).toBe(snapshot); + }); + + test('duplicate ids are rejected on both the small-int fast path and the Set path, only among valid rows', () => { + const base = { date: '2022-01-03', signal: [1, 2, 3, 4, 5], forwardReturn: [1, 2, 3, 4, 5] }; + const cases: readonly (readonly EntityId[])[] = [ + [1, 2, 3, 4, 1], + [70000, 2, 3, 70000, 5], + [-1, 2, 3, 4, -1], + [1.5, 2, 3, 4, 1.5], + ['A', 'B', 'C', 'D', 'A'], + ]; + for (const ids of cases) { + expect(() => analyzeSignalPanel([{ ...base, ids }])).toThrow(SignalAnalysisError); + try { + analyzeSignalPanel([{ ...base, ids }]); + } catch (err) { + expect((err as SignalAnalysisError).code).toBe('DUPLICATE_ID'); + } + } + // Same id on an invalid (dropped) row is allowed; same ids across dates are allowed. + const ok = analyzeSignalPanel([ + { + date: '2022-01-03', + ids: [1, 2, 3, 4, 5, 1], + signal: [1, 2, 3, 4, 5, Number.NaN], + forwardReturn: [1, 2, 3, 4, 5, 9], + }, + { + date: '2022-01-04', + ids: [1, 2, 3, 4, 5], + signal: [1, 2, 3, 4, 5], + forwardReturn: [1, 2, 3, 4, 5], + }, + ]); + expect(ok.diagnostics.droppedPairs).toBe(1); + // Number 1 and string '1' are distinct entities. + expect(() => analyzeSignalPanel([{ ...base, ids: [1, '1', 2, 3, 4] }])).not.toThrow(); + }); + + test('mixed numeric/string ids tie-break numbers before strings deterministically', () => { + const ids: EntityId[] = ['b', 3, 'a', 1, 2, 'c']; + const signal = [0, 0, 0, 0, 0, 0]; + const forwardReturn = [10, 20, 30, 40, 50, 60]; + // Order: 1, 2, 3, 'a', 'b', 'c' -> returns 40, 50, 20, 30, 10, 60 + const res = analyzeSignalPanel([{ date: '2022-01-03', ids, signal, forwardReturn }], { + quantiles: 3, + }); + expect(Array.from(res.quantiles.perBucketSeries, s => s[0])).toEqual([45, 25, 35]); + expect(res.diagnostics.icSkippedZeroVariance).toBe(1); + }); + + test('empty panel returns typed empty results with no NaN', () => { + const res = analyzeSignalPanel([]); + expect(res.rankIcSeries.length).toBe(0); + expect(res.rankIc.mean).toBeNull(); + expect(res.quantiles.bucketMeanReturns).toEqual([null, null, null, null, null]); + expect(res.turnover.meanTopTurnover).toBeNull(); + expect(res.recency.gate).toEqual({ pass: false, reason: 'empty_pre_window', ratio: null }); + expect(JSON.stringify(res)).not.toContain('NaN'); + }); +}); + +describe('signal-analysis QA: Newey-West and summaries', () => { + function refNeweyWest(x: readonly number[], lag: number): number { + const n = x.length; + const mu = x.reduce((a, v) => a + v, 0) / n; + let lrv = 0; + for (let l = -Math.min(lag, n - 1); l <= Math.min(lag, n - 1); l++) { + let g = 0; + for (let t = Math.abs(l); t < n; t++) { + g += ((x[t] as number) - mu) * ((x[t - Math.abs(l)] as number) - mu); + } + lrv += (1 - Math.abs(l) / (lag + 1)) * (g / (n - 1)); + } + return mu / Math.sqrt(lrv / n); + } + + test('matches a symmetric-sum Bartlett reference for every lag including lag >= T', () => { + const rnd = createMulberry32(7); + const x = Array.from({ length: 23 }, () => rnd() - 0.4); + for (const lag of [0, 1, 2, 5, 22, 23, 100]) { + const res = neweyWestMeanTest(x, lag); + expect(res.status).toBe('ok'); + if (res.status === 'ok') { + expect(res.lag).toBe(lag); + expect(Math.abs(res.tStat - refNeweyWest(x, lag))).toBeLessThan(1e-10); + } + } + }); + + test('summary ICIR, hit rate and std follow their definitions; zero counts as a miss', () => { + const s = summarizeIcSeries([0.1, 0, -0.05, 0.2], { lag: 0 }); + const mean = 0.0625; + const sd = Math.sqrt([0.1, 0, -0.05, 0.2].reduce((a, v) => a + (v - mean) ** 2, 0) / 3); + expect(Math.abs((s.mean as number) - mean)).toBeLessThan(1e-15); + expect(Math.abs((s.std as number) - sd)).toBeLessThan(1e-15); + expect(Math.abs((s.icir as number) - mean / sd)).toBeLessThan(1e-12); + expect(s.hitRate).toBe(0.5); + const constant = summarizeIcSeries([0.03, 0.03, 0.03]); + expect(constant.std).toBe(0); + expect(constant.icir).toBeNull(); + expect(constant.neweyWest.status).toBe('insufficient_data'); + }); +}); + +describe('signal-analysis QA: recency gate and validation edges', () => { + test('custom recencySplitDate and recencyMinRatio are honoured', () => { + const dates = ['2019-06-01', '2020-06-01', '2021-06-01']; + const res = evaluateRecencyGate(dates, [0.1, 0.09, 0.09], { + recencySplitDate: '2020-06-01', + recencyMinRatio: 0.95, + }); + expect(res.splitDate).toBe('2020-06-01'); + expect(res.pre.count).toBe(1); + expect(res.post.count).toBe(2); + expect(res.gate.reason).toBe('post_below_ratio_threshold'); + expect( + evaluateRecencyGate(dates, [0.1, 0.09, 0.09], { recencySplitDate: '2020-06-01' }).gate.pass + ).toBe(true); + }); + + test('vault cutoff equal to the split date leaves an empty post window (typed non-pass)', () => { + const res = evaluateRecencyGate(['2022-12-30', '2023-01-02'], [0.1, 0.1], { + vaultCutoffDate: '2023-01-01', + }); + expect(res.vaultExcludedDates).toBe(1); + expect(res.gate).toEqual({ pass: false, reason: 'empty_post_window', ratio: null }); + }); + + test('analyzeSignalPanel recency matches evaluateRecencyGate on its own rank-IC output', () => { + const panel = buildRandomPanel(505, 200, true); + const res = analyzeSignalPanel(panel, { lag: 3 }); + const direct = evaluateRecencyGate(res.dates, res.rankIcSeries, { lag: 3 }); + expect(res.recency).toEqual(direct); + }); + + test('leap-year and calendar validation of dates and options', () => { + const slice = { ids: [1, 2, 3, 4, 5], signal: [1, 2, 3, 4, 5], forwardReturn: [1, 2, 3, 4, 5] }; + for (const date of ['2000-02-29', '2024-02-29']) { + expect(() => analyzeSignalPanel([{ ...slice, date }])).not.toThrow(); + } + for (const date of [ + '1900-02-29', + '2023-13-01', + '2023-00-10', + '2023-04-31', + '2023-01-00', + ' 2023-01-01', + '2023/01/01', + ]) { + try { + analyzeSignalPanel([{ ...slice, date }]); + throw new Error(`expected INVALID_DATE for ${date}`); + } catch (err) { + expect([date, (err as SignalAnalysisError).code]).toEqual([date, 'INVALID_DATE']); + } + } + const badOptions: readonly SignalAnalysisOptions[] = [ + { minCrossSection: 1 }, + { minCrossSection: 5.5 }, + { quantiles: 1 }, + { quantiles: Number.NaN }, + { lag: 1.5 }, + { lag: -1 }, + { recencyMinRatio: 0 }, + { recencyMinRatio: Number.POSITIVE_INFINITY }, + { recencySplitDate: '2023-1-1' }, + { vaultCutoffDate: '2025-02-30' }, + ]; + for (const options of badOptions) { + expect(() => analyzeSignalPanel([{ ...slice, date: '2022-01-03' }], options)).toThrow( + SignalAnalysisError + ); + } + expect(() => neweyWestMeanTest([1, 2, 3], -1)).toThrow(SignalAnalysisError); + expect(() => summarizeIcSeries([1, 2, 3], { lag: 0.5 })).toThrow(SignalAnalysisError); + expect(() => crossSectionIc([1, 2], [1, 2], { minCrossSection: 1 })).toThrow( + SignalAnalysisError + ); + expect(() => evaluateRecencyGate(['2023-01-02', '2023-01-01'], [0, 0])).toThrow( + SignalAnalysisError + ); + expect(() => evaluateRecencyGate(['2023-02-29'], [0])).toThrow(SignalAnalysisError); + }); +}); diff --git a/libs/calculations/test/signal-analysis.test.ts b/libs/calculations/test/signal-analysis.test.ts new file mode 100644 index 00000000..5fcfd64e --- /dev/null +++ b/libs/calculations/test/signal-analysis.test.ts @@ -0,0 +1,856 @@ +import { describe, expect, test } from 'bun:test'; +import * as rootExports from '@stock-bot/calculations'; +import * as analyticsExports from '@stock-bot/calculations/analytics'; +import { + DEFAULT_MIN_CROSS_SECTION, + DEFAULT_QUANTILE_COUNT, + RECENCY_MIN_RATIO, + RECENCY_SPLIT_DATE, + SignalAnalysisError, + analyzeSignalPanel, + crossSectionIc, + defaultNeweyWestLag, + evaluateRecencyGate, + neweyWestMeanTest, + summarizeIcSeries, + type SignalCrossSection, +} from '@stock-bot/calculations'; + +function createMulberry32(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) / 4294967296; + }; +} + +function assertAllFiniteFloat64(series: Float64Array): void { + for (let i = 0; i < series.length; i++) { + expect(Number.isFinite(series[i])).toBe(true); + } +} + +function assertNoNaNDeep(value: unknown): void { + if (typeof value === 'number') { + expect(Number.isFinite(value)).toBe(true); + return; + } + if (value instanceof Float64Array) { + assertAllFiniteFloat64(value); + return; + } + if (Array.isArray(value)) { + for (const item of value) { + assertNoNaNDeep(item); + } + return; + } + if (value !== null && typeof value === 'object') { + for (const entry of Object.values(value)) { + assertNoNaNDeep(entry); + } + } +} + +describe('signal-analysis exports', () => { + test('both root and analytics entrypoints export the complete signal-analysis surface', () => { + const names = [ + 'DEFAULT_MIN_CROSS_SECTION', + 'DEFAULT_QUANTILE_COUNT', + 'RECENCY_SPLIT_DATE', + 'RECENCY_MIN_RATIO', + 'SignalAnalysisError', + 'crossSectionIc', + 'defaultNeweyWestLag', + 'neweyWestMeanTest', + 'summarizeIcSeries', + 'evaluateRecencyGate', + 'analyzeSignalPanel', + ] as const; + + for (const name of names) { + expect(rootExports[name]).toBeDefined(); + expect(analyticsExports[name]).toBe(rootExports[name]); + } + + expect(DEFAULT_MIN_CROSS_SECTION).toBe(5); + expect(DEFAULT_QUANTILE_COUNT).toBe(5); + expect(RECENCY_SPLIT_DATE).toBe('2023-01-01'); + expect(RECENCY_MIN_RATIO).toBe(0.5); + }); +}); + +describe('crossSectionIc', () => { + test('matches hand-computed 5-name Pearson IC and Spearman rank-IC to 1e-12', () => { + // signal = [1, 2, 3, 4, 10], forwardReturn = [2, 1, 4, 3, 5] + // Pearson = 18 / sqrt(500) = 9 / (5 * sqrt(5)); Spearman = 0.8 + const res = crossSectionIc([1, 2, 3, 4, 10], [2, 1, 4, 3, 5]); + expect(res.status).toBe('ok'); + if (res.status === 'ok') { + expect(res.validCount).toBe(5); + expect(res.droppedPairs).toBe(0); + expect(Math.abs(res.pearsonIc - 9 / (5 * Math.sqrt(5)))).toBeLessThan(1e-12); + expect(Math.abs(res.rankIc - 0.8)).toBeLessThan(1e-12); + } + }); + + test('uses average ranks for tied signals and matches hand-computed fixture to 1e-12', () => { + // signal = [1, 2, 2, 4, 5], forwardReturn = [10, 20, 40, 30, 50] + // Pearson = 4 / (3 * sqrt(3)); Spearman = 8 / sqrt(95) + const res = crossSectionIc([1, 2, 2, 4, 5], [10, 20, 40, 30, 50]); + expect(res.status).toBe('ok'); + if (res.status === 'ok') { + expect(res.validCount).toBe(5); + expect(res.droppedPairs).toBe(0); + expect(Math.abs(res.pearsonIc - 4 / (3 * Math.sqrt(3)))).toBeLessThan(1e-12); + expect(Math.abs(res.rankIc - 8 / Math.sqrt(95))).toBeLessThan(1e-12); + } + }); + + test('returns rank-IC = +1 for strictly increasing and -1 for reversed signals', () => { + const pos = crossSectionIc([1, 2, 3, 4, 5], [10, 12, 100, 101, 500]); + expect(pos.status).toBe('ok'); + if (pos.status === 'ok') { + expect(Math.abs(pos.rankIc - 1)).toBeLessThan(1e-12); + } + + const neg = crossSectionIc([5, 4, 3, 2, 1], [10, 12, 100, 101, 500]); + expect(neg.status).toBe('ok'); + if (neg.status === 'ok') { + expect(Math.abs(neg.rankIc - -1)).toBeLessThan(1e-12); + } + }); + + test('drops non-finite pairs and skips below minCrossSection or zero variance without NaN', () => { + const withNaNs = crossSectionIc( + [1, Number.NaN, 2, 3, Number.POSITIVE_INFINITY, 4, 10], + [2, 5, 1, 4, 9, 3, 5] + ); + expect(withNaNs.status).toBe('ok'); + if (withNaNs.status === 'ok') { + expect(withNaNs.validCount).toBe(5); + expect(withNaNs.droppedPairs).toBe(2); + expect(Math.abs(withNaNs.rankIc - 0.8)).toBeLessThan(1e-12); + } + + const tooSmall = crossSectionIc( + [1, 2, 3, 4, Number.NaN], + [2, 1, 4, 3, 5] + ); + expect(tooSmall).toEqual({ + status: 'skipped', + reason: 'below_min_cross_section', + validCount: 4, + droppedPairs: 1, + }); + + const zeroVar = crossSectionIc([0.1, 0.1, 0.1, 0.1, 0.1], [1, 2, 3, 4, 5]); + expect(zeroVar).toEqual({ + status: 'skipped', + reason: 'zero_variance', + validCount: 5, + droppedPairs: 0, + }); + }); +}); + +describe('neweyWestMeanTest and summarizeIcSeries', () => { + test('defaultNeweyWestLag matches floor(4 * (T/100)^(2/9))', () => { + expect(defaultNeweyWestLag(0)).toBe(0); + expect(defaultNeweyWestLag(1)).toBe(0); + expect(defaultNeweyWestLag(100)).toBe(4); + expect(defaultNeweyWestLag(252)).toBe(Math.floor(4 * Math.pow(252 / 100, 2 / 9))); + expect(defaultNeweyWestLag(5040)).toBe(Math.floor(4 * Math.pow(5040 / 100, 2 / 9))); + }); + + test('lag = 0 equals plain mean / (sd / sqrt(T)) to 1e-12', () => { + const series = [0.05, 0.02, -0.01, 0.04, 0.03, 0.06, 0.01]; + const summary = summarizeIcSeries(series, { lag: 0 }); + expect(summary.count).toBe(7); + expect(summary.mean).not.toBeNull(); + expect(summary.std).not.toBeNull(); + expect(summary.neweyWest.status).toBe('ok'); + + if (summary.mean !== null && summary.std !== null && summary.neweyWest.status === 'ok') { + const plainSe = summary.std / Math.sqrt(series.length); + const plainT = summary.mean / plainSe; + expect(summary.neweyWest.lag).toBe(0); + expect(Math.abs(summary.neweyWest.standardError - plainSe)).toBeLessThan(1e-12); + expect(Math.abs(summary.neweyWest.tStat - plainT)).toBeLessThan(1e-12); + } + }); + + test('matches hand-computed Bartlett-weighted lag = 2 fixture to 1e-12', () => { + // series = [1, 2, 3, 6, 8], T = 5, mean = 4 + // longRunVariance = 37/3, se = sqrt(37/15), t = 4 / sqrt(37/15) + const res = neweyWestMeanTest([1, 2, 3, 6, 8], 2); + expect(res.status).toBe('ok'); + if (res.status === 'ok') { + const expectedLrv = 37 / 3; + const expectedSe = Math.sqrt(37 / 15); + const expectedT = 4 / expectedSe; + expect(res.lag).toBe(2); + expect(Math.abs(res.longRunVariance - expectedLrv)).toBeLessThan(1e-12); + expect(Math.abs(res.standardError - expectedSe)).toBeLessThan(1e-12); + expect(Math.abs(res.tStat - expectedT)).toBeLessThan(1e-12); + } + }); + + test('positively autocorrelated AR(1) series has smaller |t| with positive lag than lag = 0', () => { + const nextUniform = createMulberry32(42); + const n = 200; + const ar1 = new Float64Array(n); + let x = 0.05; + for (let t = 0; t < n; t++) { + const shock = (nextUniform() - 0.5) * 0.04; + x = 0.01 + 0.85 * x + shock; + ar1[t] = x; + } + + const nw0 = neweyWestMeanTest(ar1, 0); + const nwDefault = neweyWestMeanTest(ar1); + expect(nw0.status).toBe('ok'); + expect(nwDefault.status).toBe('ok'); + if (nw0.status === 'ok' && nwDefault.status === 'ok') { + expect(nwDefault.lag).toBeGreaterThan(0); + expect(Math.abs(nwDefault.tStat)).toBeLessThan(Math.abs(nw0.tStat)); + } + }); + + test('returns typed insufficient_data for T < 2 and constant or non-positive variance series', () => { + expect(neweyWestMeanTest([])).toEqual({ + status: 'insufficient_data', + reason: 'too_few_observations', + lag: null, + }); + expect(neweyWestMeanTest([0.05])).toEqual({ + status: 'insufficient_data', + reason: 'too_few_observations', + lag: null, + }); + expect(neweyWestMeanTest([0.1, 0.1, 0.1, 0.1], 2)).toEqual({ + status: 'insufficient_data', + reason: 'non_positive_variance', + lag: 2, + }); + + const emptySummary = summarizeIcSeries([]); + expect(emptySummary.count).toBe(0); + expect(emptySummary.mean).toBeNull(); + expect(emptySummary.std).toBeNull(); + expect(emptySummary.icir).toBeNull(); + expect(emptySummary.hitRate).toBeNull(); + expect(emptySummary.neweyWest.status).toBe('insufficient_data'); + assertNoNaNDeep(emptySummary); + }); +}); + +describe('analyzeSignalPanel quantiles, tie-breaking, turnover, and invariants', () => { + test('computes exact 10-name q = 5 bucket means, spreads, and spread Newey-West summary', () => { + const panel: SignalCrossSection[] = [ + { + date: '2022-06-01', + ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + signal: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], + forwardReturn: [-0.05, -0.03, -0.01, 0.01, 0.0, 0.02, 0.03, 0.05, 0.06, 0.1], + }, + { + date: '2022-06-02', + ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + signal: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], + forwardReturn: [-0.03, -0.01, 0.0, 0.02, 0.01, 0.03, 0.04, 0.06, 0.12, 0.16], + }, + ]; + + const res = analyzeSignalPanel(panel, { quantiles: 5, lag: 0 }); + expect(res.quantiles.validDates).toBe(2); + expect(res.quantiles.skippedDates).toBe(0); + + // Date 1 buckets: [-0.04, 0.00, 0.01, 0.04, 0.08], spread = 0.12 + // Date 2 buckets: [-0.02, 0.01, 0.02, 0.05, 0.14], spread = 0.16 + const expectedMeans = [-0.03, 0.005, 0.015, 0.045, 0.11]; + for (let b = 0; b < 5; b++) { + expect( + Math.abs((res.quantiles.bucketMeanReturns[b] as number) - (expectedMeans[b] as number)) + ).toBeLessThan(1e-12); + } + expect(Math.abs((res.quantiles.spreadSeries[0] as number) - 0.12)).toBeLessThan(1e-12); + expect(Math.abs((res.quantiles.spreadSeries[1] as number) - 0.16)).toBeLessThan(1e-12); + expect(Math.abs((res.quantiles.spreadSummary.mean as number) - 0.14)).toBeLessThan(1e-12); + // Spread = [0.12, 0.16] -> mean = 0.14, sd = sqrt(0.0008), se = 0.02, t = 7.0 + expect(res.quantiles.spreadSummary.neweyWest.status).toBe('ok'); + if (res.quantiles.spreadSummary.neweyWest.status === 'ok') { + expect(Math.abs(res.quantiles.spreadSummary.neweyWest.standardError - 0.02)).toBeLessThan( + 1e-12 + ); + expect(Math.abs(res.quantiles.spreadSummary.neweyWest.tStat - 7)).toBeLessThan(1e-12); + } + assertNoNaNDeep(res); + }); + + test('tie-breaking is deterministic under input permutation within a date', () => { + const ids = ['AAPL', 'MSFT', 'NVDA', 'AMZN', 'META', 'GOOG', 'TSLA', 'JPM', 'BAC', 'XOM']; + const signal = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3]; + const forwardReturn = [0.01, -0.02, 0.05, 0.03, -0.01, 0.04, 0.02, 0.06, -0.03, 0.07]; + + const basePanel: SignalCrossSection[] = [ + { date: '2022-01-03', ids, signal, forwardReturn }, + { date: '2023-01-03', ids, signal: [3, 3, 1, 2, 2, 1, 1, 2, 3, 2], forwardReturn }, + ]; + + // Permute every cross-section deterministically + const perm = [7, 2, 9, 0, 5, 1, 8, 3, 6, 4]; + const permutedPanel: SignalCrossSection[] = basePanel.map(slice => ({ + date: slice.date, + ids: perm.map(i => slice.ids[i] as string), + signal: perm.map(i => slice.signal[i] as number), + forwardReturn: perm.map(i => slice.forwardReturn[i] as number), + })); + + const a = analyzeSignalPanel(basePanel, { quantiles: 5 }); + const b = analyzeSignalPanel(permutedPanel, { quantiles: 5 }); + + expect(a).toEqual(b); + for (let i = 0; i < a.pearsonIcSeries.length; i++) { + expect(Object.is(a.pearsonIcSeries[i], b.pearsonIcSeries[i])).toBe(true); + expect(Object.is(a.rankIcSeries[i], b.rankIcSeries[i])).toBe(true); + } + }); + + test('Pearson IC and full panel analysis are bit-for-bit invariant under row swaps with sensitive float sums', () => { + const A = 0.015625; + const B = 0.0019531250000000004; + const C = -0.03515625; + const base: SignalCrossSection[] = [ + { + date: '2022-06-01', + ids: ['id-1', 'id-2', 'id-3', 'id-4', 'id-5'], + signal: [-1, -1, 1, 1, 0], + forwardReturn: [A, B, A, B, C], + }, + ]; + const swapped: SignalCrossSection[] = [ + { + date: '2022-06-01', + ids: ['id-1', 'id-3', 'id-2', 'id-4', 'id-5'], + signal: [-1, 1, -1, 1, 0], + forwardReturn: [A, A, B, B, C], + }, + ]; + + const resBase = analyzeSignalPanel(base, { quantiles: 5 }); + const resSwapped = analyzeSignalPanel(swapped, { quantiles: 5 }); + + expect(resBase).toEqual(resSwapped); + expect(Object.is(resBase.pearsonIcSeries[0], resSwapped.pearsonIcSeries[0])).toBe(true); + expect(Object.is(resBase.pearsonIc.mean, resSwapped.pearsonIc.mean)).toBe(true); + }); + + test('strictly increasing nonlinear transform preserves rank-IC, quantiles, and turnover; negating flips signs', () => { + const panel: SignalCrossSection[] = [ + { + date: '2022-05-02', + ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + signal: [-4, -3, -2, -1, 0, 1, 2, 3, 4, 5], + forwardReturn: [-0.04, -0.02, -0.01, 0.0, 0.01, 0.02, 0.01, 0.03, 0.05, 0.06], + }, + { + date: '2023-05-02', + ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + signal: [-3, -4, -1, -2, 1, 0, 3, 2, 5, 4], + forwardReturn: [-0.02, -0.03, 0.0, -0.01, 0.02, 0.01, 0.04, 0.03, 0.06, 0.05], + }, + ]; + + const transformed: SignalCrossSection[] = panel.map(slice => ({ + ...slice, + signal: Array.from(slice.signal, v => Math.exp(v * 0.3)), + })); + + const negated: SignalCrossSection[] = panel.map(slice => ({ + ...slice, + signal: Array.from(slice.signal, v => -v), + })); + + const baseRes = analyzeSignalPanel(panel, { quantiles: 5 }); + const expRes = analyzeSignalPanel(transformed, { quantiles: 5 }); + const negRes = analyzeSignalPanel(negated, { quantiles: 5 }); + + for (let i = 0; i < baseRes.rankIcSeries.length; i++) { + expect(Math.abs((baseRes.rankIcSeries[i] as number) - (expRes.rankIcSeries[i] as number))).toBeLessThan(1e-12); + expect(Math.abs((baseRes.rankIcSeries[i] as number) + (negRes.rankIcSeries[i] as number))).toBeLessThan(1e-12); + expect(Math.abs((baseRes.pearsonIcSeries[i] as number) + (negRes.pearsonIcSeries[i] as number))).toBeLessThan( + 1e-12 + ); + } + + expect(expRes.quantiles.spreadSeries).toEqual(baseRes.quantiles.spreadSeries); + expect(expRes.turnover.topSeries).toEqual(baseRes.turnover.topSeries); + expect(expRes.turnover.bottomSeries).toEqual(baseRes.turnover.bottomSeries); + + for (let i = 0; i < baseRes.quantiles.spreadSeries.length; i++) { + expect( + Math.abs((baseRes.quantiles.spreadSeries[i] as number) + (negRes.quantiles.spreadSeries[i] as number)) + ).toBeLessThan(1e-12); + } + expect(negRes.turnover.topSeries).toEqual(baseRes.turnover.bottomSeries); + expect(negRes.turnover.bottomSeries).toEqual(baseRes.turnover.topSeries); + }); + + test('computes exact turnover for identical (0), disjoint (1), and half-replaced (0.5) membership', () => { + // q = 2 on 4 names -> bottom = 2 names, top = 2 names + // Date 1: bottom = {1, 2}, top = {3, 4} + // Date 2: bottom = {1, 2}, top = {3, 4} -> turnover = 0 + // Date 3: bottom = {3, 4}, top = {1, 2} -> turnover = 1 + // Date 4: bottom = {3, 1}, top = {4, 2} -> turnover = 0.5 + const panel: SignalCrossSection[] = [ + { + date: '2023-01-02', + ids: [1, 2, 3, 4], + signal: [1, 2, 3, 4], + forwardReturn: [0.01, 0.02, 0.03, 0.04], + }, + { + date: '2023-01-03', + ids: [1, 2, 3, 4], + signal: [1, 2, 3, 4], + forwardReturn: [0.01, 0.02, 0.03, 0.04], + }, + { + date: '2023-01-04', + ids: [1, 2, 3, 4], + signal: [3, 4, 1, 2], + forwardReturn: [0.01, 0.02, 0.03, 0.04], + }, + { + date: '2023-01-05', + ids: [1, 2, 3, 4], + signal: [2, 4, 1, 3], + forwardReturn: [0.01, 0.02, 0.03, 0.04], + }, + ]; + + const res = analyzeSignalPanel(panel, { minCrossSection: 4, quantiles: 2 }); + // First date contributes no turnover + expect(res.turnover.count).toBe(3); + expect(res.turnover.dates).toEqual(['2023-01-03', '2023-01-04', '2023-01-05']); + expect(Array.from(res.turnover.topSeries)).toEqual([0, 1, 0.5]); + expect(Array.from(res.turnover.bottomSeries)).toEqual([0, 1, 0.5]); + expect(res.turnover.meanTopTurnover).toBe(0.5); + expect(res.turnover.meanBottomTurnover).toBe(0.5); + }); + + test('skips and counts dates with fewer than q valid names or below minCrossSection / zero variance', () => { + const panel: SignalCrossSection[] = [ + // 3 valid names (< minCrossSection 5 and < q 5) + { + date: '2022-01-03', + ids: [1, 2, 3, 4], + signal: [1, 2, 3, Number.NaN], + forwardReturn: [0.01, 0.02, 0.03, 0.04], + }, + // 5 valid names, zero signal variance (valid for quantiles, skipped for IC) + { + date: '2022-01-04', + ids: [1, 2, 3, 4, 5], + signal: [1, 1, 1, 1, 1], + forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05], + }, + // 5 valid names, non-zero variance (valid for both) + { + date: '2023-01-04', + ids: [1, 2, 3, 4, 5], + signal: [1, 2, 3, 4, 5], + forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05], + }, + ]; + + const res = analyzeSignalPanel(panel); + expect(res.diagnostics.droppedPairs).toBe(1); + expect(res.diagnostics.icValidDates).toBe(1); + expect(res.diagnostics.icSkippedBelowMin).toBe(1); + expect(res.diagnostics.icSkippedZeroVariance).toBe(1); + expect(res.diagnostics.quantileValidDates).toBe(2); + expect(res.diagnostics.quantileSkippedDates).toBe(1); + assertNoNaNDeep(res); + }); +}); + +describe('evaluateRecencyGate and vaultCutoffDate fence', () => { + test('splits 2022-12-31 into pre and 2023-01-01 into post and passes when post >= 50% of pre', () => { + const res = evaluateRecencyGate( + ['2022-12-30', '2022-12-31', '2023-01-01', '2023-01-02'], + [0.08, 0.12, 0.06, 0.08] + ); + expect(res.pre.count).toBe(2); + expect(res.post.count).toBe(2); + expect(Math.abs((res.pre.mean as number) - 0.1)).toBeLessThan(1e-12); + expect(Math.abs((res.post.mean as number) - 0.07)).toBeLessThan(1e-12); + expect(res.gate.pass).toBe(true); + expect(res.gate.reason).toBe('passed'); + expect(Math.abs((res.gate.ratio as number) - 0.7)).toBeLessThan(1e-12); + }); + + test('passes on exact 50% boundary and fails on < 50%, post <= 0, pre <= 0, or empty windows', () => { + const exactBoundary = evaluateRecencyGate( + ['2022-12-31', '2023-01-01'], + [0.08, 0.04] + ); + expect(exactBoundary.gate.pass).toBe(true); + expect(exactBoundary.gate.reason).toBe('passed'); + expect(exactBoundary.gate.ratio).toBe(0.5); + + const belowRatio = evaluateRecencyGate( + ['2022-12-31', '2023-01-01'], + [0.08, 0.039] + ); + expect(belowRatio.gate.pass).toBe(false); + expect(belowRatio.gate.reason).toBe('post_below_ratio_threshold'); + + const postZero = evaluateRecencyGate( + ['2022-12-31', '2023-01-01'], + [0.08, 0] + ); + expect(postZero.gate.pass).toBe(false); + expect(postZero.gate.reason).toBe('non_positive_post_mean'); + + const postNeg = evaluateRecencyGate( + ['2022-12-31', '2023-01-01'], + [0.08, -0.02] + ); + expect(postNeg.gate.pass).toBe(false); + expect(postNeg.gate.reason).toBe('non_positive_post_mean'); + + const preNeg = evaluateRecencyGate( + ['2022-12-31', '2023-01-01'], + [-0.08, -0.06] + ); + expect(preNeg.gate.pass).toBe(false); + expect(preNeg.gate.reason).toBe('non_positive_pre_mean'); + expect(preNeg.gate.ratio).toBeNull(); + + const preZero = evaluateRecencyGate( + ['2022-12-31', '2023-01-01'], + [0, 0.05] + ); + expect(preZero.gate.pass).toBe(false); + expect(preZero.gate.reason).toBe('non_positive_pre_mean'); + + const emptyPre = evaluateRecencyGate(['2023-01-01', '2023-01-02'], [0.05, 0.06]); + expect(emptyPre.gate.pass).toBe(false); + expect(emptyPre.gate.reason).toBe('empty_pre_window'); + + const emptyPost = evaluateRecencyGate(['2022-12-30', '2022-12-31'], [0.05, 0.06]); + expect(emptyPost.gate.pass).toBe(false); + expect(emptyPost.gate.reason).toBe('empty_post_window'); + }); + + test('rejects pre-2023 or post-2023 rank-IC means that cancel to zero within floating-point rounding', () => { + // 5-name cross-sections with exact Spearman rank-ICs: + // [2, 5, 1, 4, 3] -> 0.1, [1, 4, 5, 2, 3] -> 0.2, [5, 1, 3, 4, 2] -> -0.3 + // Exact mean = (0.1 + 0.2 - 0.3) / 3 = 0, but uncompensated float sum leaves ~1.85e-17. + const ids = [1, 2, 3, 4, 5]; + const signal = [1, 2, 3, 4, 5]; + const panelZeroPre: SignalCrossSection[] = [ + { date: '2022-12-28', ids, signal, forwardReturn: [2, 5, 1, 4, 3] }, + { date: '2022-12-29', ids, signal, forwardReturn: [1, 4, 5, 2, 3] }, + { date: '2022-12-30', ids, signal, forwardReturn: [5, 1, 3, 4, 2] }, + { date: '2023-01-03', ids, signal, forwardReturn: [2, 5, 1, 4, 3] }, + ]; + + const resZeroPre = analyzeSignalPanel(panelZeroPre); + expect(Math.abs((resZeroPre.rankIcSeries[0] as number) - 0.1)).toBeLessThan(1e-12); + expect(Math.abs((resZeroPre.rankIcSeries[1] as number) - 0.2)).toBeLessThan(1e-12); + expect(Math.abs((resZeroPre.rankIcSeries[2] as number) - -0.3)).toBeLessThan(1e-12); + expect(Math.abs((resZeroPre.rankIcSeries[3] as number) - 0.1)).toBeLessThan(1e-12); + expect(resZeroPre.recency.gate.pass).toBe(false); + expect(resZeroPre.recency.gate.reason).toBe('non_positive_pre_mean'); + expect(resZeroPre.recency.gate.ratio).toBeNull(); + + const panelZeroPost: SignalCrossSection[] = [ + { date: '2022-12-30', ids, signal, forwardReturn: [2, 5, 1, 4, 3] }, + { date: '2023-01-03', ids, signal, forwardReturn: [2, 5, 1, 4, 3] }, + { date: '2023-01-04', ids, signal, forwardReturn: [1, 4, 5, 2, 3] }, + { date: '2023-01-05', ids, signal, forwardReturn: [5, 1, 3, 4, 2] }, + ]; + const resZeroPost = analyzeSignalPanel(panelZeroPost); + expect(resZeroPost.recency.gate.pass).toBe(false); + expect(resZeroPost.recency.gate.reason).toBe('non_positive_post_mean'); + }); + + test('passes exact 50% recency boundary despite floating-point summation rounding and rejects clearly below', () => { + // 5-name cross-sections with exact Spearman rank-ICs: + // [1, 4, 5, 2, 3] -> 0.2, [1, 2, 3, 5, 4] -> 0.9, [4, 5, 2, 3, 1] -> -0.8, [2, 5, 1, 4, 3] -> 0.1 + // Pre mean = 0.2; exact post mean = (0.2 + 0.9 - 0.8) / 3 = 0.1 (exact 50% of pre), + // even though compensated float arithmetic evaluates post mean to 0.09999999999999999. + const ids = [1, 2, 3, 4, 5]; + const signal = [1, 2, 3, 4, 5]; + const panelExactHalf: SignalCrossSection[] = [ + { date: '2022-12-30', ids, signal, forwardReturn: [1, 4, 5, 2, 3] }, + { date: '2023-01-03', ids, signal, forwardReturn: [1, 4, 5, 2, 3] }, + { date: '2023-01-04', ids, signal, forwardReturn: [1, 2, 3, 5, 4] }, + { date: '2023-01-05', ids, signal, forwardReturn: [4, 5, 2, 3, 1] }, + ]; + + const resExact = analyzeSignalPanel(panelExactHalf); + expect(Math.abs((resExact.rankIcSeries[0] as number) - 0.2)).toBeLessThan(1e-12); + expect(Math.abs((resExact.rankIcSeries[1] as number) - 0.2)).toBeLessThan(1e-12); + expect(Math.abs((resExact.rankIcSeries[2] as number) - 0.9)).toBeLessThan(1e-12); + expect(Math.abs((resExact.rankIcSeries[3] as number) - -0.8)).toBeLessThan(1e-12); + expect(resExact.recency.gate.pass).toBe(true); + expect(resExact.recency.gate.reason).toBe('passed'); + expect(Math.abs((resExact.recency.gate.ratio as number) - 0.5)).toBeLessThan(1e-12); + + // Clearly below 50%: pre mean = 0.2, post mean = (0.1 + 0.9 - 0.8) / 3 = 0.2 / 3 (~33.3%) + const panelBelowHalf: SignalCrossSection[] = [ + { date: '2022-12-30', ids, signal, forwardReturn: [1, 4, 5, 2, 3] }, + { date: '2023-01-03', ids, signal, forwardReturn: [2, 5, 1, 4, 3] }, + { date: '2023-01-04', ids, signal, forwardReturn: [1, 2, 3, 5, 4] }, + { date: '2023-01-05', ids, signal, forwardReturn: [4, 5, 2, 3, 1] }, + ]; + + const resBelow = analyzeSignalPanel(panelBelowHalf); + expect(resBelow.recency.gate.pass).toBe(false); + expect(resBelow.recency.gate.reason).toBe('post_below_ratio_threshold'); + expect(Math.abs((resBelow.recency.gate.ratio as number) - 1 / 3)).toBeLessThan(1e-12); + }); + + test('vaultCutoffDate excludes dates >= cutoff, counts them, and isolates non-vault metrics', () => { + const basePanel: SignalCrossSection[] = [ + { + date: '2022-12-30', + ids: [1, 2, 3, 4, 5], + signal: [1, 2, 3, 4, 5], + forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05], + }, + { + date: '2023-01-03', + ids: [1, 2, 3, 4, 5], + signal: [1, 2, 3, 4, 5], + forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.06], + }, + ]; + + const withVault: SignalCrossSection[] = [ + ...basePanel, + // Extreme reversed data at and after vaultCutoffDate + { + date: '2025-06-01', + ids: [1, 2, 3, 4, 5], + signal: [1, 2, 3, 4, 5], + forwardReturn: [100, -100, -200, -300, -400], + }, + { + date: '2025-06-02', + ids: [1, 2, 3, 4, 5], + signal: [1, 2, 3, 4, 5], + forwardReturn: [100, -100, -200, -300, -400], + }, + ]; + + const resBase = analyzeSignalPanel(basePanel, { vaultCutoffDate: '2025-06-01' }); + const resVault = analyzeSignalPanel(withVault, { vaultCutoffDate: '2025-06-01' }); + + expect(resVault.diagnostics.totalDates).toBe(4); + expect(resVault.diagnostics.eligibleDates).toBe(2); + expect(resVault.diagnostics.vaultExcludedDates).toBe(2); + expect(resVault.recency.vaultExcludedDates).toBe(2); + expect(resVault.dates).toEqual(resBase.dates); + expect(resVault.rankIcSeries).toEqual(resBase.rankIcSeries); + expect(resVault.pearsonIcSeries).toEqual(resBase.pearsonIcSeries); + expect(resVault.quantiles.spreadSeries).toEqual(resBase.quantiles.spreadSeries); + expect(resVault.recency.gate).toEqual(resBase.recency.gate); + + const directRecency = evaluateRecencyGate( + ['2022-12-31', '2023-01-01', '2025-06-01', '2025-06-02'], + [0.08, 0.06, -0.9, -0.9], + { vaultCutoffDate: '2025-06-01' } + ); + expect(directRecency.vaultExcludedDates).toBe(2); + expect(directRecency.post.count).toBe(1); + expect(directRecency.gate.pass).toBe(true); + }); +}); + +describe('input validation errors', () => { + const validSlice: SignalCrossSection = { + date: '2023-01-03', + ids: [1, 2, 3, 4, 5], + signal: [1, 2, 3, 4, 5], + forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05], + }; + + function expectErrorCode(fn: () => unknown, code: SignalAnalysisError['code']): void { + try { + fn(); + throw new Error(`Expected SignalAnalysisError(${code}) to be thrown`); + } catch (err) { + expect(err).toBeInstanceOf(SignalAnalysisError); + expect((err as SignalAnalysisError).code).toBe(code); + } + } + + test('throws LENGTH_MISMATCH on mismatched array lengths', () => { + expectErrorCode( + () => crossSectionIc([1, 2, 3], [1, 2]), + 'LENGTH_MISMATCH' + ); + expectErrorCode( + () => + analyzeSignalPanel([ + { ...validSlice, ids: [1, 2, 3, 4] }, + ]), + 'LENGTH_MISMATCH' + ); + expectErrorCode( + () => + analyzeSignalPanel([ + { ...validSlice, forwardReturn: [0.01, 0.02] }, + ]), + 'LENGTH_MISMATCH' + ); + expectErrorCode( + () => evaluateRecencyGate(['2023-01-01'], [0.01, 0.02]), + 'LENGTH_MISMATCH' + ); + }); + + test('throws UNSORTED_DATES and DUPLICATE_DATE on bad date ordering', () => { + expectErrorCode( + () => + analyzeSignalPanel([ + { ...validSlice, date: '2023-01-04' }, + { ...validSlice, date: '2023-01-03' }, + ]), + 'UNSORTED_DATES' + ); + expectErrorCode( + () => + analyzeSignalPanel([ + { ...validSlice, date: '2023-01-03' }, + { ...validSlice, date: '2023-01-03' }, + ]), + 'DUPLICATE_DATE' + ); + expectErrorCode( + () => evaluateRecencyGate(['2023-01-04', '2023-01-03'], [0.01, 0.02]), + 'UNSORTED_DATES' + ); + expectErrorCode( + () => evaluateRecencyGate(['2023-01-03', '2023-01-03'], [0.01, 0.02]), + 'DUPLICATE_DATE' + ); + }); + + test('throws INVALID_DATE on malformed or impossible calendar dates', () => { + for (const badDate of ['2023-02-29', '2023-1-1', '2023-13-01', '2023-04-31', '2023-01-01T00:00:00Z']) { + expectErrorCode( + () => analyzeSignalPanel([{ ...validSlice, date: badDate }]), + 'INVALID_DATE' + ); + } + expectErrorCode( + () => analyzeSignalPanel([validSlice], { vaultCutoffDate: '2025-02-29' }), + 'INVALID_DATE' + ); + expectErrorCode( + () => analyzeSignalPanel([validSlice], { recencySplitDate: 'not-a-date' }), + 'INVALID_DATE' + ); + // Valid leap year date succeeds + const leap = analyzeSignalPanel([{ ...validSlice, date: '2024-02-29' }]); + expect(leap.dates).toEqual(['2024-02-29']); + }); + + test('throws DUPLICATE_ID when valid rows in a cross-section share an entity ID (including at a bucket boundary)', () => { + // Two rows for the same security with the lowest signal and different forward returns at q=5 boundary + expectErrorCode( + () => + analyzeSignalPanel( + [ + { + date: '2023-01-03', + ids: ['SEC1', 'SEC1', 'SEC2', 'SEC3', 'SEC4'], + signal: [1, 1, 2, 3, 4], + forwardReturn: [-0.05, 0.15, 0.01, 0.02, 0.03], + }, + ], + { quantiles: 5 } + ), + 'DUPLICATE_ID' + ); + + // Small integer ID fast path + expectErrorCode( + () => + analyzeSignalPanel([ + { + date: '2023-01-03', + ids: [10, 10, 20, 30, 40], + signal: [1, 2, 3, 4, 5], + forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05], + }, + ]), + 'DUPLICATE_ID' + ); + + // Large/negative numeric ID fallback path + expectErrorCode( + () => + analyzeSignalPanel([ + { + date: '2023-01-03', + ids: [100_000, 100_000, -5, 1, 2], + signal: [1, 2, 3, 4, 5], + forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05], + }, + ]), + 'DUPLICATE_ID' + ); + + // A duplicate ID whose extra row is dropped as non-finite leaves unique valid IDs and succeeds + const resWithDroppedDup = analyzeSignalPanel([ + { + date: '2023-01-03', + ids: ['SEC1', 'SEC1', 'SEC2', 'SEC3', 'SEC4', 'SEC5'], + signal: [1, Number.NaN, 2, 3, 4, 5], + forwardReturn: [0.01, 0.99, 0.02, 0.03, 0.04, 0.05], + }, + ]); + expect(resWithDroppedDup.diagnostics.validObservations).toBe(5); + expect(resWithDroppedDup.diagnostics.droppedPairs).toBe(1); + }); + + test('throws INVALID_ID on NaN numeric entity IDs in a tied cross-section', () => { + expectErrorCode( + () => + analyzeSignalPanel( + [ + { + date: '2023-01-03', + ids: [1, Number.NaN, 2, 3, 4], + signal: [1, 1, 1, 2, 3], + forwardReturn: [0.01, 0.05, -0.02, 0.03, 0.04], + }, + ], + { quantiles: 5 } + ), + 'INVALID_ID' + ); + }); + + test('throws INVALID_OPTION on invalid quantiles, lag, minCrossSection, or recencyMinRatio', () => { + expectErrorCode(() => analyzeSignalPanel([validSlice], { quantiles: 1 }), 'INVALID_OPTION'); + expectErrorCode(() => analyzeSignalPanel([validSlice], { quantiles: 2.5 }), 'INVALID_OPTION'); + expectErrorCode(() => analyzeSignalPanel([validSlice], { lag: -1 }), 'INVALID_OPTION'); + expectErrorCode(() => analyzeSignalPanel([validSlice], { lag: 1.5 }), 'INVALID_OPTION'); + expectErrorCode(() => neweyWestMeanTest([1, 2, 3], -1), 'INVALID_OPTION'); + expectErrorCode(() => neweyWestMeanTest([1, 2, 3], 0.5), 'INVALID_OPTION'); + expectErrorCode(() => analyzeSignalPanel([validSlice], { minCrossSection: 1 }), 'INVALID_OPTION'); + expectErrorCode(() => analyzeSignalPanel([validSlice], { minCrossSection: 3.2 }), 'INVALID_OPTION'); + expectErrorCode(() => analyzeSignalPanel([validSlice], { recencyMinRatio: 0 }), 'INVALID_OPTION'); + expectErrorCode(() => analyzeSignalPanel([validSlice], { recencyMinRatio: Number.NaN }), 'INVALID_OPTION'); + }); +}); diff --git a/libs/research/README.md b/libs/research/README.md new file mode 100644 index 00000000..8f0d6452 --- /dev/null +++ b/libs/research/README.md @@ -0,0 +1,76 @@ +# `@stock-bot/research` + +Browser-safe research contracts, rolling 6-month Vault holdout fencing, and append-only `trial_ledger` accounting (`design/DATA-CONTRACTS.md`, `design/VALIDATION-AND-RIGOR.md`). + +## `trial_ledger` Writer & Cluster N-hat-Deflated Sharpe Reader + +Exported from both `@stock-bot/research` and `@stock-bot/research/trial-ledger` (`libs/research/src/trial-ledger.ts`). The module is dependency-free and browser-safe; PostgreSQL access is injected via `TrialLedgerExecutor` (`{ query(text, params) }`). + +### API + +- **`canonicalExpressionHash(input)`** — Returns a 64-character lowercase SHA-256 hex digest over the recursively ASCII-key-sorted compact JSON of `{ expression, params, universe, sampleStart, sampleEnd, horizon }`. Leading/trailing/internal whitespace in `expression` is collapsed, `undefined` object keys are omitted, `-0` is normalized to `0`, and non-JSON values (`NaN`, `±Infinity`, functions, symbols, `BigInt`, cycles) are rejected with `TrialLedgerError`. +- **`buildTrialRow(input)`** — Pure validator and moment builder for a single `trial_ledger` row. Validates principal (`operator` or `agent:`), optional UUIDs, schema enums (`stage`, `universeMarket`, `horizonBucket`), 64-hex `expressionHash`, strict `YYYY-MM-DD` dates, the exclusive Vault fence, and IEEE-754 `REAL` (float32) representability and non-zero variance at `REAL` storage precision for `dailySeries`. Computes `{ nObs, sharpeUnann, skewness, kurtosis }` via `trialMoments` from `@stock-bot/calculations`. +- **`recordTrials(executor, rows)`** — Validates every row upfront (re-verifying that pre-built rows' moments match their `dailySeries`, sending zero SQL on any invalid row or batch > `MAX_TRIAL_BATCH_SIZE = 4681`) and appends the batch atomically in one parameterised multi-row `INSERT ... RETURNING trial_id, created_at`. Multi-horizon analyses (e.g. `1d`, `5d`, `20d`) record one row per horizon. +- **`loadClusterTrials(executor, { universeMarket, horizonBucket, asOf? })`** — Loads a `(universe_market, horizon_bucket)` relatedness cluster ordered by `trial_id ASC` (backed by `idx_trial_ledger_cluster`), optionally capped at `created_at <= asOf` while preserving PostgreSQL's 6-digit microsecond UTC precision across `Z` and explicit `±HH:MM` offsets. +- **`clusterDeflatedSharpe(executor, { trialId, asOf?, dsrGate?, sessionDates?, observationDatesByTrialId? })`** — Loads the target trial and its relatedness cluster and computes `{ trialId, clusterSize, effectiveTrials, meanCorrelation, pairsUsed, pairsSkipped, sr0, standardError, dsr, passesGate }`. Index alignment requires a proven shared session grid (`sessionDates` covering the trial's full `[sampleStart, sampleEnd]` range where the series length matches the session count in `[sampleStart, sampleEnd]`) or explicit per-trial `observationDatesByTrialId` (for sparse `signal_ic` / `event_study` series); trials without proven alignment or pairs with constant overlap slices are counted in `pairsSkipped` without inventing correlations. Cross-window correlations are computed directly within and across alignment groups without materializing dense `NaN` padding. + +### Vault Holdout Fence Rule + +Every row built by `buildTrialRow` or persisted by `recordTrials` requires an explicit `vaultCutoffDate` (`YYYY-MM-DD`) and delegates calendar validation and holdout enforcement to `applyVaultFence` in `libs/research/src/market-data-store.ts`. Any trial with `sampleEnd >= vaultCutoffDate` (or `sampleStart >= vaultCutoffDate`) is rejected with `TrialLedgerError('VAULT_FENCE_VIOLATION')` before any SQL is executed. + +### Local In-Memory Benchmark + +Fixed-seed (`20260403`) in-memory benchmark covering `200` trials × `5,000` daily observations (`1,000,000` observations total, `19,900` pairwise correlations) through `buildTrialRow` + `clusterDeflatedSharpe` with no PostgreSQL dependency, for both shared-window and 200-distinct-window staggered rolling clusters: + +- **Command:** `bun test libs/research/test/trial-ledger.test.ts` +- **Workload:** 200 trials × 5,000 daily observations (seed `20260403`), shared 5,000-session grid and 200-window staggered rolling grid (shifted by 1 session per trial across 5,199 sessions) +- **Measured (Bun 1.2.16):** + - **Shared window (`buildTrialRow` + `clusterDeflatedSharpe`):** `elapsedMs = 710.17 ms`, `trialsPerSec = 281.6 trials/s` (`effectiveTrials = 171.85`, `dsr = 0.011891`) + - **Staggered rolling windows (`clusterDeflatedSharpe`, 200 distinct windows, `19,900` overlapping pairs, zero `NaN` padding):** `staggeredElapsedMs = 508.77 ms`, `staggeredTrialsPerSec = 393.1 trials/s` + +## Signal Study Runners + +Exported from both `@stock-bot/research` and `@stock-bot/research/signal-study` (`libs/research/src/signal-study.ts`). Browser-safe and dependency-free; database access is injected via `TrialLedgerExecutor`. + +### API & Write-Before-Return Guarantee + +- **`analyzeSignal(executor, request)`** — Validates inputs upfront, runs `analyzeSignalPanel` under the exclusive `vaultCutoffDate` fence, appends one `stage = 'signal_ic'` row to `trial_ledger`, and computes `clusterDeflatedSharpe` for the newly recorded trial. +- **`runEventStudy(executor, request)`** — Validates inputs upfront, fences out events whose event date or post-event window end (`sessionDates[dayIndex + postDays]`) falls on or after `vaultCutoffDate`, runs `eventStudy`, appends one `stage = 'event_study'` row to `trial_ledger`, and computes `clusterDeflatedSharpe`. +- **Write-before-return & partial-failure semantics:** + - If `recordTrials` (`INSERT`) fails, the error propagates directly and no analysis or study result is returned. + - If `recordTrials` succeeds but `clusterDeflatedSharpe` (`SELECT`) fails, the runner throws `SignalStudyError` with `code: 'dsr_read_failed'`, exposing the already-written `trialId` and original `cause`. The `INSERT` is never retried. + - Validation errors and `status: 'insufficient_data'` paths (too few observations, `below_min_events`, `too_few_event_dates`, or zero-variance series at `REAL` precision) issue **zero** SQL queries. + +### Logged Series by Stage + +| Runner | `trial_ledger.stage` | Logged `daily_series` | Observation Dates | +| --- | --- | --- | --- | +| `analyzeSignal` (default `ledgerSeries: 'rank_ic'`) | `'signal_ic'` | `analysis.rankIcSeries` | `analysis.dates` | +| `analyzeSignal` (`ledgerSeries: 'quantile_spread'`) | `'signal_ic'` | `analysis.quantiles.spreadSeries` | `analysis.quantiles.dates` | +| `runEventStudy` | `'event_study'` | `study.clustered.meanCars` | `study.clustered.dates` | + +### Vault Holdout & Cluster DSR Behavior + +- **`analyzeSignal`** delegates to `analyzeSignalPanel`'s exclusive `vaultCutoffDate` fence, excluding all cross-sections with `date >= vaultCutoffDate` (reported in `analysis.diagnostics.vaultExcludedDates`) so `sampleEnd < vaultCutoffDate`. Callers assembling pre-computed forward-return panels remain responsible for ensuring forward-return horizons do not consume post-cutoff prices. +- **`runEventStudy`** validates return-array shapes against the original `sessionDates` calendar, drops every event where `sessionDates[dayIndex] >= vaultCutoffDate` or `sessionDates[dayIndex + postDays] >= vaultCutoffDate` (reported in `vaultExcludedEvents`), and passes only the pre-cutoff calendar and matching return prefixes to `eventStudy` without mutating caller inputs so held-out Vault-tail values (including non-finite returns) never leak into or fail pre-Vault studies. +- **Count-based DSR fallback:** Because `analyzeSignal` and `runEventStudy` supply `observationDatesByTrialId` only for the newly written trial and no shared session grid for historical trials in the cluster, `clusterDeflatedSharpe` skips unaligned historical correlation pairs (`pairsUsed === 0`, `pairsSkipped === clusterSize * (clusterSize - 1) / 2`) and falls back conservatively to count-based `effectiveTrials === clusterSize`. Callers needing correlation-aware `effectiveTrials` across historical trials should invoke `clusterDeflatedSharpe` directly with a trusted `sessionDates` calendar or per-trial `observationDatesByTrialId`. + +### `SignalStudyError` Codes + +| Code | Meaning | +| --- | --- | +| `'invalid_request'` | Invalid executor, request envelope, expression, principal, UUID, market, or horizon bucket (0 SQL queries) | +| `'empty_panel'` | Empty `panel` or empty `input.sessionDates` (0 SQL queries) | +| `'invalid_date'` | Malformed or non-calendar `YYYY-MM-DD` date in `vaultCutoffDate`, panel, or `sessionDates` (0 SQL queries) | +| `'unsorted_dates'` | Panel or `sessionDates` not strictly ascending (0 SQL queries) | +| `'duplicate_date'` | Duplicate date in panel or `sessionDates` (0 SQL queries) | +| `'invalid_panel'` | Malformed cross-section vectors/IDs, return arrays, or event descriptors (0 SQL queries) | +| `'invalid_option'` | Invalid `ledgerSeries`, `dsrGate`, or analyzer/event-study options (0 SQL queries) | +| `'dsr_read_failed'` | Trial row was inserted (`error.trialId` is set), but `clusterDeflatedSharpe` failed (`error.cause` holds the original error) | + +### Local In-Memory Benchmark (`analyzeSignal`) + +Fixed-seed (`20260402`) end-to-end `analyzeSignal` benchmark covering `5,040` business dates × `3,000` listings (`15,120,000` observations) with an in-memory `TrialLedgerExecutor`: + +- **Command:** `bun run libs/research/scripts/benchmark-signal-study.ts` +- **Observed (Bun 1.2.16):** `elapsedMs = 1691.13 ms`, `rowsPerSec = 8,940,793 rows/s` (`2,980 dates/s`, `nObs = 5040`, `meanRankIc = 0.057294`, `recencyGatePassed = true`) diff --git a/libs/research/package.json b/libs/research/package.json index 5c40161b..dd8dd698 100644 --- a/libs/research/package.json +++ b/libs/research/package.json @@ -10,11 +10,15 @@ ".": "./src/index.ts", "./dataset-contracts": "./src/dataset-contracts.ts", "./datasets": "./src/datasets.ts", + "./market-data-store": "./src/market-data-store.ts", "./results": "./src/results.ts", - "./strategy-api": "./src/strategy-api.ts" + "./signal-study": "./src/signal-study.ts", + "./strategy-api": "./src/strategy-api.ts", + "./trial-ledger": "./src/trial-ledger.ts" }, "scripts": { - "build": "tsc" + "build": "tsc", + "test": "bun test" }, "dependencies": { "@stock-bot/types": "workspace:*", diff --git a/libs/research/scripts/benchmark-signal-study.ts b/libs/research/scripts/benchmark-signal-study.ts new file mode 100644 index 00000000..02fe33f3 --- /dev/null +++ b/libs/research/scripts/benchmark-signal-study.ts @@ -0,0 +1,228 @@ +import type { SignalCrossSection } from '@stock-bot/calculations'; +import { analyzeSignal } from '../src/signal-study'; +import type { TrialLedgerExecutor } from '../src/trial-ledger'; + +const SEED = 20260402; +const DATES = 5040; +const NAMES_PER_DATE = 3000; +const VAULT_CUTOFF_DATE = '2026-06-01'; + +function createMulberry32(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) / 4294967296; + }; +} + +function createStandardNormal(seed: number): () => number { + const nextUniform = createMulberry32(seed); + let spare: number | null = null; + return () => { + if (spare !== null) { + const value = spare; + spare = null; + return value; + } + let u1 = nextUniform(); + while (u1 <= 1e-12) { + u1 = nextUniform(); + } + const u2 = nextUniform(); + const radius = Math.sqrt(-2 * Math.log(u1)); + const theta = 2 * Math.PI * u2; + spare = radius * Math.sin(theta); + return radius * Math.cos(theta); + }; +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function generateBusinessDates(count: number, startYear: number): string[] { + const dates: string[] = new Array(count); + let year = startYear; + let month = 1; + let day = 1; + // 2006-01-01 was a Sunday (dow = 0) + let dow = 0; + let produced = 0; + + while (produced < count) { + if (dow !== 0 && dow !== 6) { + const yyyy = String(year).padStart(4, '0'); + const mm = String(month).padStart(2, '0'); + const dd = String(day).padStart(2, '0'); + dates[produced++] = `${yyyy}-${mm}-${dd}`; + } + + dow = (dow + 1) % 7; + day++; + const baseDays = DAYS_IN_MONTH[month] ?? 31; + const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays; + if (day > maxDay) { + day = 1; + month++; + if (month > 12) { + month = 1; + year++; + } + } + } + + return dates; +} + +interface StoredRow { + 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 createInMemoryExecutor(): TrialLedgerExecutor { + const rows: StoredRow[] = []; + let nextId = 0; + + return { + async query>(text: string, params?: readonly unknown[]) { + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + const p = params ?? []; + const trialId = ++nextId; + const createdAt = new Date(Date.UTC(2026, 4, 1, 0, 0, trialId)); + const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v)); + const row: StoredRow = { + 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(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 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 }; + }, + }; +} + +const randn = createStandardNormal(SEED); +const isoDates = generateBusinessDates(DATES, 2006); +const sharedIds = new Int32Array(NAMES_PER_DATE); +for (let i = 0; i < NAMES_PER_DATE; i++) { + sharedIds[i] = i + 1; +} + +const panel: SignalCrossSection[] = new Array(DATES); +for (let t = 0; t < DATES; t++) { + const signal = new Float64Array(NAMES_PER_DATE); + const forwardReturn = new Float64Array(NAMES_PER_DATE); + for (let i = 0; i < NAMES_PER_DATE; i++) { + const s = randn(); + signal[i] = s; + forwardReturn[i] = 0.0004 + 0.0012 * s + 0.02 * randn(); + } + panel[t] = { + date: isoDates[t] as string, + ids: sharedIds, + signal, + forwardReturn, + }; +} + +const executor = createInMemoryExecutor(); +const started = performance.now(); +const result = await analyzeSignal(executor, { + principalId: 'operator', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'rank(ret_20d) - zscore(vol_20d)', + params: { lookback: 20 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + panel, + vaultCutoffDate: VAULT_CUTOFF_DATE, +}); +const elapsedMs = performance.now() - started; + +if (result.status !== 'ok') { + throw new Error(`Unexpected benchmark status: ${result.status} (${result.reason})`); +} + +const totalObservations = DATES * NAMES_PER_DATE; +const elapsedSec = elapsedMs / 1000; +const datesPerSec = DATES / elapsedSec; +const rowsPerSec = totalObservations / elapsedSec; + +console.log( + JSON.stringify( + { + seed: SEED, + dates: DATES, + namesPerDate: NAMES_PER_DATE, + totalObservations, + elapsedMs: Number(elapsedMs.toFixed(2)), + datesPerSec: Math.round(datesPerSec), + rowsPerSec: Math.round(rowsPerSec), + trialId: result.trial.trialId, + nObs: result.trial.nObs, + effectiveTrials: Number(result.deflatedSharpe.effectiveTrials.toFixed(4)), + dsr: result.deflatedSharpe.dsr !== null ? Number(result.deflatedSharpe.dsr.toFixed(6)) : null, + meanRankIc: Number((result.analysis.rankIc.mean ?? 0).toFixed(6)), + recencyGatePassed: result.analysis.recency.gate.pass, + }, + null, + 2 + ) +); diff --git a/libs/research/src/index.ts b/libs/research/src/index.ts index 94c42ab2..fd3691a2 100644 --- a/libs/research/src/index.ts +++ b/libs/research/src/index.ts @@ -1,2 +1,5 @@ // The default entrypoint is browser safe; server validation is an explicit subpath. export * from './dataset-contracts'; +export * from './market-data-store'; +export * from './signal-study'; +export * from './trial-ledger'; diff --git a/libs/research/src/market-data-store.ts b/libs/research/src/market-data-store.ts new file mode 100644 index 00000000..4e13dc96 --- /dev/null +++ b/libs/research/src/market-data-store.ts @@ -0,0 +1,555 @@ +/** + * `MarketDataStore` contract (`design/DATA-CONTRACTS.md` §4), rolling 6-month + * UTC Vault holdout fence (`design/VALIDATION-AND-RIGOR.md` §3.3), and + * per-connection DuckDB resource budget (`design/DATA-CONTRACTS.md` §3.A). + * + * This module is intentionally pure, dependency-free, and browser-safe (no + * `node:*` imports, no bare `process` global, no database or filesystem I/O) + * so both server adapters and shared browser packages can import it. + * + * Provisional supporting types: + * - `design/DATA-CONTRACTS.md` §4 names `BarBatch`, `Table`, `UniverseRef`, + * and `EventKind` without fixing their full wire shapes. The definitions + * below are minimal provisional shapes; `listing_id` / `listingIds` use + * JavaScript `number` (matching Parquet `INT32`). + * + * Contract interpretation note for `applyVaultFence`: + * - `design/DATA-CONTRACTS.md` §4 specifies that non-vault queries clamp `to` + * and `asOf` to `< VAULT_CUTOFF_TS` and reject `from >= VAULT_CUTOFF_TS` + * with `VaultHoldoutFenceError`. + * - All bounds are interpreted as inclusive UTC instants in integer epoch + * milliseconds. + * - Date-only `YYYY-MM-DD` strings expand in UTC to `00:00:00.000Z` for `from` + * (and `computeVaultCutoffTs`) and to `23:59:59.999Z` for `to` and `asOf`. + * - Full ISO-8601 timestamps must carry an explicit UTC offset (`Z` or + * `±HH:MM`); naive datetimes without a timezone are rejected. Fractional + * seconds finer than milliseconds are truncated toward zero to integer ms. + * - Under `'vault_fenced'` (the default when `scope` is omitted): + * - `fromMs >= vaultCutoffTs` throws `VaultHoldoutFenceError`. + * - `toMs >= vaultCutoffTs` clamps to `vaultCutoffTs - 1` (`clampedTo: true`). + * - `asOfMs >= vaultCutoffTs` clamps to `vaultCutoffTs - 1` (`clampedAsOf: true`). + * - Omitted `asOf` resolves to `vaultCutoffTs - 1` (`clampedAsOf: false`) so + * adapters always enforce a bounded `known_at <= asOf` predicate. + * - Under `'vault_evaluation_only'`: + * - Fails closed with `VaultScopeNotAuthorizedError` unless + * `ctx.vaultOperatorAuthorized === true`. + * - When authorized, no Vault clamping is applied and omitted `asOf` + * defaults to `toMs`. + */ + +const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; +const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const DATE_ONLY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/; +const ISO_INSTANT_PATTERN = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$/; +const DUCKDB_MEMORY_LIMIT_PATTERN = /^(\d+(?:\.\d+)?)(MB|GB|MiB|GiB)$/; +const DUCKDB_THREADS_PATTERN = /^[1-9]\d*$/; +const MIN_DUCKDB_THREADS = 1; +const MAX_DUCKDB_THREADS = 64; + +export const DEFAULT_DUCKDB_MEMORY_LIMIT = '6GB'; +export const DEFAULT_DUCKDB_THREADS = 4; +export const DEFAULT_DUCKDB_TEMP_DIRECTORY = '/mnt/data/stockbot/tmp/duckdb'; + +export type DataScope = 'vault_fenced' | 'vault_evaluation_only'; + +/** Provisional event kinds referenced by `MarketDataStore.events` (§4). */ +export type EventKind = 'filing' | 'earnings' | 'ceo_post' | 'corporate_action'; + +/** Provisional universe identifier referenced by `MarketDataStore` (§4). */ +export type UniverseRef = string; + +/** Provisional OHLCV bar record for `BarBatch` (`listingId` is `INT32`). */ +export interface BarRecord { + readonly listingId: number; + readonly ts: number; + readonly open: number; + readonly high: number; + readonly low: number; + readonly close: number; + readonly volume: number; + readonly vwap?: number | null; + readonly knownAt: number; +} + +/** Provisional batch yielded by `MarketDataStore.bars` (§4). */ +export interface BarBatch { + readonly rows: readonly BarRecord[]; +} + +/** Provisional scalar cell value for tabular `MarketDataStore` results (§4). */ +export type TableCell = string | number | boolean | null; + +/** Provisional row map for tabular `MarketDataStore` results (§4). */ +export type TableRow = Readonly>; + +/** Provisional tabular result returned by `MarketDataStore` methods (§4). */ +export interface Table { + readonly columns: readonly string[]; + readonly rows: readonly TableRow[]; +} + +/** + * Unified read contract for curated daily/PIT (DuckDB + Parquet) and intraday + * (QuestDB) market data (`design/DATA-CONTRACTS.md` §4). + */ +export interface MarketDataStore { + bars(q: { + listingIds: number[]; + timeframe: '1m' | '5m' | '1h' | '1d'; + from: string; + to: string; + adjustment: 'raw' | 'split' | 'total'; + asOf?: string; + scope?: DataScope; + }): AsyncIterable; + + crossSection(q: { + features: string[]; + date: string; + universe: UniverseRef; + asOf?: string; + }): Promise; + + fundamentalsAsOf(q: { + listingIds: number[]; + fields: string[]; + asOf: string; + allowEstimatedLag?: boolean; + }): Promise
; + + events(q: { + kinds: EventKind[]; + listingIds?: number[]; + from: string; + to: string; + asOf?: string; + }): Promise
; + + shortsAsOf(q: { listingIds: number[]; from: string; to: string; asOf?: string }): Promise
; + macroAsOf(q: { + countries: string[]; + indicators: string[]; + from: string; + to: string; + asOf?: string; + }): Promise
; + fx(q: { pair: 'USD.CAD'; timeframe: '1m' | '1d'; from: string; to: string }): Promise
; + universe(q: { ref: UniverseRef; date: string }): Promise; +} + +export interface VaultFenceQuery { + readonly from: string; + readonly to: string; + readonly asOf?: string; + readonly scope?: DataScope; +} + +export interface VaultFenceContext { + readonly vaultCutoffTs: number; + readonly vaultOperatorAuthorized?: boolean; +} + +export interface FencedTimeRange { + readonly fromMs: number; + readonly toMs: number; + readonly asOfMs: number; + readonly scope: DataScope; + readonly clampedTo: boolean; + readonly clampedAsOf: boolean; +} + +export interface DuckDbConnectionBudget { + readonly memoryLimit: string; + readonly threads: number; + readonly tempDirectory: string; + readonly statements: string[]; +} + +/** Thrown when market-data query bounds, timestamps, or DuckDB budget inputs are invalid. */ +export class MarketDataStoreValidationError extends Error { + override readonly name = 'MarketDataStoreValidationError'; + readonly field?: string; + + constructor(message: string, field?: string) { + super(message); + this.field = field; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Thrown when a fenced query starts at or after the rolling 6-month Vault cutoff. */ +export class VaultHoldoutFenceError extends Error { + override readonly name = 'VaultHoldoutFenceError'; + readonly from: string; + readonly fromMs: number; + readonly vaultCutoffTs: number; + + constructor(from: string, fromMs: number, vaultCutoffTs: number, message?: string) { + super( + message ?? + `Query start "${from}" (${fromMs}) reaches or exceeds Vault cutoff (${vaultCutoffTs}).` + ); + this.from = from; + this.fromMs = fromMs; + this.vaultCutoffTs = vaultCutoffTs; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Thrown when `'vault_evaluation_only'` is requested without explicit operator authorization. */ +export class VaultScopeNotAuthorizedError extends Error { + override readonly name = 'VaultScopeNotAuthorizedError'; + + constructor(message?: string) { + super( + message ?? + "Data scope 'vault_evaluation_only' requires explicit human operator authorization." + ); + Object.setPrototypeOf(this, new.target.prototype); + } +} + +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; + } + const days = DAYS_IN_MONTH[monthIndex]; + if (days === undefined) { + throw new MarketDataStoreValidationError(`Invalid UTC month index: ${monthIndex}.`); + } + return days; +} + +function utcDateMs( + year: number, + monthIndex: number, + day: number, + hours: number, + minutes: number, + seconds: number, + ms: number +): number { + if (year >= 0 && year <= 99) { + const date = new Date(0); + date.setUTCFullYear(year, monthIndex, day); + date.setUTCHours(hours, minutes, seconds, ms); + return date.getTime(); + } + return Date.UTC(year, monthIndex, day, hours, minutes, seconds, ms); +} + +function validateEpochMs(value: number, field: string): number { + if ( + typeof value !== 'number' || + !Number.isFinite(value) || + !Number.isSafeInteger(value) || + Math.abs(value) > MAX_ECMASCRIPT_EPOCH_MS + ) { + throw new MarketDataStoreValidationError( + `Invalid epoch millisecond timestamp for "${field}": ${String(value)}.`, + field + ); + } + return value === 0 ? 0 : value; +} + +function parseTimestampMs(raw: string, boundKind: 'start' | 'end', field: string): number { + if (typeof raw !== 'string' || raw.length === 0) { + throw new MarketDataStoreValidationError( + `Expected a non-empty ISO-8601 date or timestamp for "${field}".`, + field + ); + } + + const dateMatch = DATE_ONLY_PATTERN.exec(raw); + if (dateMatch !== null) { + const year = Number(dateMatch[1]); + const month = Number(dateMatch[2]); + const day = Number(dateMatch[3]); + if (month < 1 || month > 12) { + throw new MarketDataStoreValidationError( + `Invalid calendar month in "${field}": "${raw}".`, + field + ); + } + const maxDay = daysInUtcMonth(year, month - 1); + if (day < 1 || day > maxDay) { + throw new MarketDataStoreValidationError( + `Invalid calendar day in "${field}": "${raw}".`, + field + ); + } + const ms = + boundKind === 'start' + ? utcDateMs(year, month - 1, day, 0, 0, 0, 0) + : utcDateMs(year, month - 1, day, 23, 59, 59, 999); + return validateEpochMs(ms, field); + } + + const instantMatch = ISO_INSTANT_PATTERN.exec(raw); + if (instantMatch !== null) { + const year = Number(instantMatch[1]); + const month = Number(instantMatch[2]); + const day = Number(instantMatch[3]); + const hours = Number(instantMatch[4]); + const minutes = Number(instantMatch[5]); + const seconds = Number(instantMatch[6]); + const fractional = instantMatch[7]; + const tzToken = instantMatch[8]; + const tzSign = instantMatch[9]; + const tzHoursRaw = instantMatch[10]; + const tzMinutesRaw = instantMatch[11]; + + if (month < 1 || month > 12) { + throw new MarketDataStoreValidationError( + `Invalid calendar month in "${field}": "${raw}".`, + field + ); + } + const maxDay = daysInUtcMonth(year, month - 1); + if (day < 1 || day > maxDay) { + throw new MarketDataStoreValidationError( + `Invalid calendar day in "${field}": "${raw}".`, + field + ); + } + if (hours > 23 || minutes > 59 || seconds > 59) { + throw new MarketDataStoreValidationError( + `Invalid time-of-day in "${field}": "${raw}".`, + field + ); + } + + let ms = 0; + if (fractional !== undefined) { + const msDigits = fractional.slice(0, 3).padEnd(3, '0'); + ms = Number(msDigits); + } + + let offsetMs = 0; + if (tzToken !== 'Z') { + const offsetHours = Number(tzHoursRaw); + const offsetMinutes = Number(tzMinutesRaw); + if (offsetHours > 23 || offsetMinutes > 59) { + throw new MarketDataStoreValidationError( + `Invalid timezone offset in "${field}": "${raw}".`, + field + ); + } + const sign = tzSign === '+' ? 1 : -1; + offsetMs = sign * (offsetHours * 60 + offsetMinutes) * 60_000; + } + + const epochMs = utcDateMs(year, month - 1, day, hours, minutes, seconds, ms) - offsetMs; + return validateEpochMs(epochMs, field); + } + + throw new MarketDataStoreValidationError( + `Invalid ISO-8601 date or UTC timestamp for "${field}": "${raw}".`, + field + ); +} + +/** + * Computes the rolling 6-month Vault cutoff (`maxIngestedTs - 6 calendar months` + * in UTC). Month-end dates clamp to the last day of the target month while + * preserving the UTC time-of-day. + */ +export function computeVaultCutoffTs(maxIngestedTs: number | string | Date): number { + let epochMs: number; + if (typeof maxIngestedTs === 'number') { + epochMs = validateEpochMs(maxIngestedTs, 'maxIngestedTs'); + } else if (typeof maxIngestedTs === 'string') { + epochMs = parseTimestampMs(maxIngestedTs, 'start', 'maxIngestedTs'); + } else if (maxIngestedTs instanceof Date) { + epochMs = validateEpochMs(maxIngestedTs.getTime(), 'maxIngestedTs'); + } else { + throw new MarketDataStoreValidationError( + 'Invalid `maxIngestedTs`: expected a finite integer epoch-ms, ISO-8601 string, or Date.', + 'maxIngestedTs' + ); + } + + const date = new Date(epochMs); + const year = date.getUTCFullYear(); + const month = date.getUTCMonth(); + const day = date.getUTCDate(); + const hours = date.getUTCHours(); + const minutes = date.getUTCMinutes(); + const seconds = date.getUTCSeconds(); + const ms = date.getUTCMilliseconds(); + + const totalMonths = year * 12 + month - 6; + const targetYear = Math.floor(totalMonths / 12); + const targetMonth = ((totalMonths % 12) + 12) % 12; + const targetDay = Math.min(day, daysInUtcMonth(targetYear, targetMonth)); + + const cutoffMs = utcDateMs(targetYear, targetMonth, targetDay, hours, minutes, seconds, ms); + return validateEpochMs(cutoffMs, 'maxIngestedTs'); +} + +/** + * Enforces the rolling 6-month Vault holdout fence and normalizes query time + * bounds to inclusive UTC epoch milliseconds before an adapter builds SQL. + */ +export function applyVaultFence(query: VaultFenceQuery, ctx: VaultFenceContext): FencedTimeRange { + const cutoffMs = validateEpochMs(ctx.vaultCutoffTs, 'vaultCutoffTs'); + if (cutoffMs <= -MAX_ECMASCRIPT_EPOCH_MS) { + throw new MarketDataStoreValidationError( + `Vault cutoff timestamp is out of representable range: ${cutoffMs}.`, + 'vaultCutoffTs' + ); + } + + const rawScope: unknown = query.scope; + let scope: DataScope; + if (rawScope === undefined) { + scope = 'vault_fenced'; + } else if (rawScope === 'vault_fenced' || rawScope === 'vault_evaluation_only') { + scope = rawScope; + } else { + throw new MarketDataStoreValidationError( + `Unknown DataScope "${String(rawScope)}". Expected 'vault_fenced' or 'vault_evaluation_only'.`, + 'scope' + ); + } + + if (scope === 'vault_evaluation_only' && ctx.vaultOperatorAuthorized !== true) { + throw new VaultScopeNotAuthorizedError(); + } + + const fromMs = parseTimestampMs(query.from, 'start', 'from'); + const toMs = parseTimestampMs(query.to, 'end', 'to'); + const parsedAsOfMs = + query.asOf !== undefined ? parseTimestampMs(query.asOf, 'end', 'asOf') : undefined; + + if (fromMs > toMs) { + throw new MarketDataStoreValidationError( + `Query start "${query.from}" (${fromMs}) must not be after end "${query.to}" (${toMs}).`, + 'from' + ); + } + + if (scope === 'vault_evaluation_only') { + return { + fromMs, + toMs, + asOfMs: parsedAsOfMs ?? toMs, + scope, + clampedTo: false, + clampedAsOf: false, + }; + } + + if (fromMs >= cutoffMs) { + throw new VaultHoldoutFenceError(query.from, fromMs, cutoffMs); + } + + const maxAllowedMs = cutoffMs - 1; + const clampedTo = toMs >= cutoffMs; + const effectiveToMs = clampedTo ? maxAllowedMs : toMs; + const clampedAsOf = parsedAsOfMs !== undefined && parsedAsOfMs >= cutoffMs; + const effectiveAsOfMs = + parsedAsOfMs === undefined ? maxAllowedMs : clampedAsOf ? maxAllowedMs : parsedAsOfMs; + + return { + fromMs, + toMs: effectiveToMs, + asOfMs: effectiveAsOfMs, + scope, + clampedTo, + clampedAsOf, + }; +} + +function readDefaultEnv(): Readonly> { + const globalRecord = globalThis as { + process?: { env?: Readonly> }; + }; + return globalRecord.process?.env ?? {}; +} + +function hasForbiddenTempDirChar(value: string): boolean { + for (let i = 0; i < value.length; i += 1) { + const code = value.charCodeAt(i); + if (code <= 0x1f || code === 0x7f || code === 0x27 || code === 0x3b) { + return true; + } + } + return false; +} + +/** + * Resolves and strictly validates per-connection DuckDB budget settings from + * environment variables (`STOCKBOT_DUCKDB_MEMORY_LIMIT`, + * `STOCKBOT_DUCKDB_THREADS`, `STOCKBOT_DUCKDB_TEMP_DIRECTORY`), returning the + * exact `SET` SQL statements to execute at connection open. + */ +export function resolveDuckDbConnectionBudget( + env?: Readonly> +): DuckDbConnectionBudget { + const sourceEnv = env ?? readDefaultEnv(); + + const rawMemoryLimit = sourceEnv.STOCKBOT_DUCKDB_MEMORY_LIMIT; + let memoryLimit = DEFAULT_DUCKDB_MEMORY_LIMIT; + if (rawMemoryLimit !== undefined) { + const match = DUCKDB_MEMORY_LIMIT_PATTERN.exec(rawMemoryLimit); + const amount = match !== null ? Number(match[1]) : Number.NaN; + if (match === null || !Number.isFinite(amount) || amount <= 0) { + throw new MarketDataStoreValidationError( + `Invalid STOCKBOT_DUCKDB_MEMORY_LIMIT "${rawMemoryLimit}". Expected a positive number followed by MB, GB, MiB, or GiB.`, + 'STOCKBOT_DUCKDB_MEMORY_LIMIT' + ); + } + memoryLimit = rawMemoryLimit; + } + + const rawThreads = sourceEnv.STOCKBOT_DUCKDB_THREADS; + let threads = DEFAULT_DUCKDB_THREADS; + if (rawThreads !== undefined) { + const parsedThreads = DUCKDB_THREADS_PATTERN.test(rawThreads) ? Number(rawThreads) : Number.NaN; + if ( + !Number.isSafeInteger(parsedThreads) || + parsedThreads < MIN_DUCKDB_THREADS || + parsedThreads > MAX_DUCKDB_THREADS + ) { + throw new MarketDataStoreValidationError( + `Invalid STOCKBOT_DUCKDB_THREADS "${rawThreads}". Expected an integer between ${MIN_DUCKDB_THREADS} and ${MAX_DUCKDB_THREADS}.`, + 'STOCKBOT_DUCKDB_THREADS' + ); + } + threads = parsedThreads; + } + + const rawTempDir = sourceEnv.STOCKBOT_DUCKDB_TEMP_DIRECTORY; + let tempDirectory = DEFAULT_DUCKDB_TEMP_DIRECTORY; + if (rawTempDir !== undefined) { + if ( + rawTempDir.length === 0 || + !rawTempDir.startsWith('/') || + hasForbiddenTempDirChar(rawTempDir) + ) { + throw new MarketDataStoreValidationError( + `Invalid STOCKBOT_DUCKDB_TEMP_DIRECTORY "${rawTempDir}". Expected an absolute path without quotes, semicolons, or control characters.`, + 'STOCKBOT_DUCKDB_TEMP_DIRECTORY' + ); + } + tempDirectory = rawTempDir; + } + + return { + memoryLimit, + threads, + tempDirectory, + statements: [ + `SET memory_limit = '${memoryLimit}';`, + `SET threads = ${threads};`, + `SET temp_directory = '${tempDirectory}';`, + ], + }; +} diff --git a/libs/research/src/signal-study.ts b/libs/research/src/signal-study.ts new file mode 100644 index 00000000..fe41e25f --- /dev/null +++ b/libs/research/src/signal-study.ts @@ -0,0 +1,876 @@ +/** + * Signal-analysis and event-study runners that join pure `@stock-bot/calculations` + * analytics with mandatory append-only `trial_ledger` logging and relatedness-cluster + * N-hat-deflated Sharpe evaluation (`design/MILESTONES.md` M1, `design/VALIDATION-AND-RIGOR.md`). + * + * Browser-safe and dependency-free: zero `node:*` imports, zero `pg` dependency, + * zero bare `process` access. SQL execution is injected via {@link TrialLedgerExecutor}. + */ + +import { + DEFAULT_EVENT_POST_DAYS, + EventStudyError, + SignalAnalysisError, + analyzeSignalPanel, + eventStudy, + type EntityId, + type EventStudyEvent, + type EventStudyInput, + type EventStudyOptions, + type EventStudyResult, + type NumericSeries, + type SignalAnalysisOptions, + type SignalCrossSection, + type SignalPanelAnalysis, +} from '@stock-bot/calculations'; +import { MarketDataStoreValidationError, applyVaultFence } from './market-data-store'; +import { + TrialLedgerError, + buildTrialRow, + canonicalExpressionHash, + clusterDeflatedSharpe, + recordTrials, + type BuiltTrialRow, + type CanonicalExpressionInput, + type ClusterDeflatedSharpeResult, + type HorizonBucket, + type TrialLedgerExecutor, + type TrialStage, + type UniverseMarket, +} from './trial-ledger'; + +export type SignalStudyErrorCode = + | 'invalid_request' + | 'empty_panel' + | 'invalid_date' + | 'unsorted_dates' + | 'duplicate_date' + | 'invalid_panel' + | 'invalid_option' + | 'dsr_read_failed'; + +export interface SignalStudyErrorOptions { + readonly trialId?: number; + readonly cause?: unknown; +} + +/** Typed validation and orchestration error thrown by {@link analyzeSignal} and {@link runEventStudy}. */ +export class SignalStudyError extends Error { + readonly code: SignalStudyErrorCode; + readonly trialId?: number; + override readonly cause?: unknown; + + constructor(code: SignalStudyErrorCode, message: string, options?: SignalStudyErrorOptions) { + super(message, options?.cause !== undefined ? { cause: options.cause } : undefined); + this.name = 'SignalStudyError'; + this.code = code; + if (options?.trialId !== undefined) { + this.trialId = options.trialId; + } + if (options?.cause !== undefined) { + this.cause = options.cause; + } + Object.setPrototypeOf(this, new.target.prototype); + } +} + +export type SignalLedgerSeries = 'rank_ic' | 'quantile_spread'; + +export type SignalStudyExpression = Omit; + +export type AnalyzeSignalOptions = Omit; + +export interface StudyTrialSummary { + readonly trialId: number; + readonly createdAt: string; + readonly expressionHash: string; + readonly sampleStart: string; + readonly sampleEnd: string; + readonly nObs: number; +} + +export interface AnalyzeSignalRequest { + readonly principalId: string; + readonly campaignId?: string | null; + readonly hypothesisId?: string | null; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly expression: SignalStudyExpression; + readonly panel: readonly SignalCrossSection[]; + readonly vaultCutoffDate: string; + readonly options?: AnalyzeSignalOptions; + readonly ledgerSeries?: SignalLedgerSeries; + readonly dsrGate?: number; +} + +export type AnalyzeSignalInsufficientDataReason = 'too_few_observations' | 'zero_variance_series'; + +export type AnalyzeSignalResult = + | { + readonly status: 'ok'; + readonly analysis: SignalPanelAnalysis; + readonly trial: StudyTrialSummary; + readonly deflatedSharpe: ClusterDeflatedSharpeResult; + } + | { + readonly status: 'insufficient_data'; + readonly analysis: SignalPanelAnalysis; + readonly reason: AnalyzeSignalInsufficientDataReason; + }; + +export interface RunEventStudyRequest { + readonly principalId: string; + readonly campaignId?: string | null; + readonly hypothesisId?: string | null; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly expression: SignalStudyExpression; + readonly input: EventStudyInput; + readonly vaultCutoffDate: string; + readonly options?: EventStudyOptions; + readonly dsrGate?: number; +} + +export type RunEventStudyInsufficientDataReason = + | 'below_min_events' + | 'too_few_event_dates' + | 'too_few_observations' + | 'zero_variance_series'; + +export type RunEventStudyResult = + | { + readonly status: 'ok'; + readonly study: Extract; + readonly vaultExcludedEvents: number; + readonly trial: StudyTrialSummary; + readonly deflatedSharpe: ClusterDeflatedSharpeResult; + } + | { + readonly status: 'insufficient_data'; + readonly study: EventStudyResult; + readonly vaultExcludedEvents: number; + readonly reason: RunEventStudyInsufficientDataReason; + }; + +const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const PROBE_SAMPLE_START = '2000-01-01'; +const PROBE_SAMPLE_END = '2000-01-02'; +const PROBE_VAULT_CUTOFF = '2000-01-03'; +const PROBE_DAILY_SERIES: readonly number[] = [0, 1]; + +type NumericTypedArray = + | Float64Array + | Float32Array + | Int32Array + | Uint32Array + | Int16Array + | Uint16Array + | Int8Array + | Uint8Array + | Uint8ClampedArray; + +const NUMERIC_TYPED_ARRAY_TAGS = new Set([ + '[object Float64Array]', + '[object Float32Array]', + '[object Int32Array]', + '[object Uint32Array]', + '[object Int16Array]', + '[object Uint16Array]', + '[object Int8Array]', + '[object Uint8Array]', + '[object Uint8ClampedArray]', +]); + +function isNumericTypedArray(value: unknown): value is NumericTypedArray { + if (!ArrayBuffer.isView(value)) { + return false; + } + const tag = Object.prototype.toString.call(value); + if (!NUMERIC_TYPED_ARRAY_TAGS.has(tag)) { + return false; + } + return typeof (value as { subarray?: unknown }).subarray === 'function'; +} + +function isSupportedVector(value: unknown): value is readonly unknown[] | NumericTypedArray { + return Array.isArray(value) || isNumericTypedArray(value); +} + +function isReadonlyMapLike(value: unknown): value is ReadonlyMap { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return false; + } + const candidate = value as { + get?: unknown; + has?: unknown; + [Symbol.iterator]?: unknown; + }; + return ( + typeof candidate.get === 'function' && + typeof candidate.has === 'function' && + typeof candidate[Symbol.iterator] === 'function' + ); +} + +function sliceNumericSeries(series: NumericSeries, length: number): NumericSeries { + if (series.length === length) { + return series; + } + if (Array.isArray(series)) { + return series.slice(0, length); + } + if (isNumericTypedArray(series)) { + return series.subarray(0, length) as unknown as NumericSeries; + } + return series; +} + +interface BaseStudyRequest { + readonly principalId: string; + readonly campaignId?: string | null; + readonly hypothesisId?: string | null; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly expression: SignalStudyExpression; + readonly vaultCutoffDate: string; + readonly dsrGate?: number; +} + +function assertStrictCalendarDate(value: unknown, field: string): string { + if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) { + throw new SignalStudyError( + 'invalid_date', + `Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".` + ); + } + try { + applyVaultFence( + { from: value, to: value, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ); + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + throw new SignalStudyError('invalid_date', `Invalid "${field}": ${error.message}`, { + cause: error, + }); + } + throw error; + } + return value; +} + +function mapTrialLedgerError(error: TrialLedgerError): SignalStudyError { + const code: SignalStudyErrorCode = + error.code === 'INVALID_DATE' ? 'invalid_date' : 'invalid_request'; + return new SignalStudyError(code, error.message, { cause: error }); +} + +function mapSignalAnalysisError(error: SignalAnalysisError): SignalStudyError { + switch (error.code) { + case 'UNSORTED_DATES': + return new SignalStudyError('unsorted_dates', error.message, { cause: error }); + case 'DUPLICATE_DATE': + return new SignalStudyError('duplicate_date', error.message, { cause: error }); + case 'INVALID_DATE': + return new SignalStudyError('invalid_date', error.message, { cause: error }); + case 'INVALID_OPTION': + return new SignalStudyError('invalid_option', error.message, { cause: error }); + case 'LENGTH_MISMATCH': + case 'DUPLICATE_ID': + case 'INVALID_ID': + return new SignalStudyError('invalid_panel', error.message, { cause: error }); + } +} + +function mapEventStudyError(error: EventStudyError): SignalStudyError { + switch (error.code) { + case 'UNSORTED_DATES': + return new SignalStudyError('unsorted_dates', error.message, { cause: error }); + case 'DUPLICATE_DATE': + return new SignalStudyError('duplicate_date', error.message, { cause: error }); + case 'INVALID_DATE': + return new SignalStudyError('invalid_date', error.message, { cause: error }); + case 'INVALID_OPTION': + return new SignalStudyError('invalid_option', error.message, { cause: error }); + case 'INVALID_TIMESTAMP': + case 'UNSORTED_TIMESTAMPS': + case 'LENGTH_MISMATCH': + case 'INVALID_EVENT': + case 'NON_FINITE_RETURN': + return new SignalStudyError('invalid_panel', error.message, { cause: error }); + } +} + +function validateBaseRequest( + executor: unknown, + request: unknown, + stage: TrialStage +): asserts request is BaseStudyRequest { + if ( + typeof executor !== 'object' || + executor === null || + typeof (executor as { query?: unknown }).query !== 'function' + ) { + throw new SignalStudyError( + 'invalid_request', + 'Expected a TrialLedgerExecutor object with a query(text, params) method.' + ); + } + + if (typeof request !== 'object' || request === null) { + throw new SignalStudyError('invalid_request', 'Study request must be a non-null object.'); + } + + const req = request as Partial; + assertStrictCalendarDate(req.vaultCutoffDate, 'vaultCutoffDate'); + + if (req.dsrGate !== undefined && (typeof req.dsrGate !== 'number' || !Number.isFinite(req.dsrGate))) { + throw new SignalStudyError( + 'invalid_option', + `Invalid dsrGate "${String(req.dsrGate)}": expected a finite number.` + ); + } + + if (typeof req.expression !== 'object' || req.expression === null) { + throw new SignalStudyError('invalid_request', 'request.expression must be a non-null object.'); + } + + // Probe canonicalExpressionHash and buildTrialRow upfront so metadata/expression errors + // fail fast before heavy math and before any SQL query is issued. + try { + const probeHash = canonicalExpressionHash({ + expression: req.expression.expression, + params: req.expression.params, + universe: req.expression.universe, + sampleStart: PROBE_SAMPLE_START, + sampleEnd: PROBE_SAMPLE_END, + horizon: req.expression.horizon, + }); + buildTrialRow({ + principalId: req.principalId as string, + campaignId: req.campaignId, + hypothesisId: req.hypothesisId, + stage, + universeMarket: req.universeMarket as UniverseMarket, + horizonBucket: req.horizonBucket as HorizonBucket, + expressionHash: probeHash, + sampleStart: PROBE_SAMPLE_START, + sampleEnd: PROBE_SAMPLE_END, + vaultCutoffDate: PROBE_VAULT_CUTOFF, + dailySeries: PROBE_DAILY_SERIES, + }); + } catch (error) { + if (error instanceof TrialLedgerError) { + throw mapTrialLedgerError(error); + } + throw error; + } +} + +async function persistTrialAndEvaluateDsr( + executor: TrialLedgerExecutor, + row: BuiltTrialRow, + seriesDates: readonly string[], + dsrGate: number | undefined +): Promise<{ + readonly trial: StudyTrialSummary; + readonly deflatedSharpe: ClusterDeflatedSharpeResult; +}> { + // Write-before-return guarantee: if INSERT fails, propagate directly with no result returned. + const receipts = await recordTrials(executor, [row]); + const receipt = receipts[0]; + if (receipt === undefined) { + throw new SignalStudyError( + 'invalid_request', + 'recordTrials returned no receipt after inserting a trial row.' + ); + } + + // Never retry the insert if the subsequent DSR read fails; surface trialId and cause. + // Only the newly written trial's observation dates are known here (no shared session grid + // for earlier cluster trials), so clusterDeflatedSharpe skips unaligned historical pairs + // (pairsUsed = 0) and falls back conservatively to count-based effectiveTrials = clusterSize. + let deflatedSharpe: ClusterDeflatedSharpeResult; + try { + deflatedSharpe = await clusterDeflatedSharpe(executor, { + trialId: receipt.trialId, + ...(dsrGate !== undefined ? { dsrGate } : {}), + observationDatesByTrialId: { [String(receipt.trialId)]: seriesDates }, + }); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new SignalStudyError( + 'dsr_read_failed', + `Trial ${receipt.trialId} was recorded in trial_ledger, but clusterDeflatedSharpe failed: ${detail}`, + { trialId: receipt.trialId, cause: error } + ); + } + + return { + trial: { + trialId: receipt.trialId, + createdAt: receipt.createdAt, + expressionHash: row.expressionHash, + sampleStart: row.sampleStart, + sampleEnd: row.sampleEnd, + nObs: row.nObs, + }, + deflatedSharpe, + }; +} + +/** + * Runs cross-sectional signal analysis (`analyzeSignalPanel`) under an exclusive + * `vaultCutoffDate` fence, appends a `stage = 'signal_ic'` row to `trial_ledger`, + * and returns the analysis together with its trial receipt and cluster N-hat-deflated Sharpe. + */ +export async function analyzeSignal( + executor: TrialLedgerExecutor, + request: AnalyzeSignalRequest +): Promise { + validateBaseRequest(executor, request, 'signal_ic'); + + const ledgerSeries: SignalLedgerSeries = + request.ledgerSeries === undefined ? 'rank_ic' : request.ledgerSeries; + if (ledgerSeries !== 'rank_ic' && ledgerSeries !== 'quantile_spread') { + throw new SignalStudyError( + 'invalid_option', + `Invalid ledgerSeries "${String(ledgerSeries)}": expected 'rank_ic' or 'quantile_spread'.` + ); + } + + if ( + request.options !== undefined && + (typeof request.options !== 'object' || request.options === null) + ) { + throw new SignalStudyError('invalid_option', 'request.options must be a non-null object.'); + } + + if (!Array.isArray(request.panel)) { + throw new SignalStudyError('invalid_panel', 'request.panel must be an array of cross-sections.'); + } + if (request.panel.length === 0) { + throw new SignalStudyError('empty_panel', 'request.panel must contain at least one cross-section.'); + } + + for (let i = 0; i < request.panel.length; i += 1) { + const slice: unknown = request.panel[i]; + if (typeof slice !== 'object' || slice === null) { + throw new SignalStudyError('invalid_panel', `panel[${i}] must be a non-null object.`); + } + const candidate = slice as Partial; + if (!isSupportedVector(candidate.ids)) { + throw new SignalStudyError( + 'invalid_panel', + `panel[${i}].ids must be an array or typed array of entity IDs.` + ); + } + if (!isSupportedVector(candidate.signal)) { + throw new SignalStudyError( + 'invalid_panel', + `panel[${i}].signal must be an array or numeric typed array.` + ); + } + if (!isSupportedVector(candidate.forwardReturn)) { + throw new SignalStudyError( + 'invalid_panel', + `panel[${i}].forwardReturn must be an array or numeric typed array.` + ); + } + } + + let analysis: SignalPanelAnalysis; + try { + analysis = analyzeSignalPanel(request.panel, { + ...request.options, + vaultCutoffDate: request.vaultCutoffDate, + }); + } catch (error) { + if (error instanceof SignalAnalysisError) { + throw mapSignalAnalysisError(error); + } + throw error; + } + + const series = + ledgerSeries === 'rank_ic' ? analysis.rankIcSeries : analysis.quantiles.spreadSeries; + const seriesDates = ledgerSeries === 'rank_ic' ? analysis.dates : analysis.quantiles.dates; + + if (series.length < 2 || seriesDates.length < 2) { + return { + status: 'insufficient_data', + analysis, + reason: 'too_few_observations', + }; + } + + const sampleStart = seriesDates[0]; + const sampleEnd = seriesDates[seriesDates.length - 1]; + if (sampleStart === undefined || sampleEnd === undefined) { + return { + status: 'insufficient_data', + analysis, + reason: 'too_few_observations', + }; + } + + let row: BuiltTrialRow; + try { + const expressionHash = canonicalExpressionHash({ + expression: request.expression.expression, + params: request.expression.params, + universe: request.expression.universe, + sampleStart, + sampleEnd, + horizon: request.expression.horizon, + }); + row = buildTrialRow({ + principalId: request.principalId, + campaignId: request.campaignId, + hypothesisId: request.hypothesisId, + stage: 'signal_ic', + universeMarket: request.universeMarket, + horizonBucket: request.horizonBucket, + expressionHash, + sampleStart, + sampleEnd, + vaultCutoffDate: request.vaultCutoffDate, + dailySeries: series, + }); + } catch (error) { + if (error instanceof TrialLedgerError) { + if (error.code === 'SERIES_TOO_SHORT') { + return { + status: 'insufficient_data', + analysis, + reason: 'too_few_observations', + }; + } + if (error.code === 'ZERO_VARIANCE_SERIES') { + return { + status: 'insufficient_data', + analysis, + reason: 'zero_variance_series', + }; + } + throw mapTrialLedgerError(error); + } + throw error; + } + + const { trial, deflatedSharpe } = await persistTrialAndEvaluateDsr( + executor, + row, + seriesDates, + request.dsrGate + ); + + return { + status: 'ok', + analysis, + trial, + deflatedSharpe, + }; +} + +/** + * Runs a Vault-fenced event study (`eventStudy`), excluding every event whose event date + * or post-event window end (`sessionDates[dayIndex + postDays]`) falls on or after + * `vaultCutoffDate`, appends a `stage = 'event_study'` row to `trial_ledger`, and returns + * the study together with its trial receipt and cluster N-hat-deflated Sharpe. + */ +export async function runEventStudy( + executor: TrialLedgerExecutor, + request: RunEventStudyRequest +): Promise { + validateBaseRequest(executor, request, 'event_study'); + + if (typeof request.input !== 'object' || request.input === null) { + throw new SignalStudyError('invalid_request', 'request.input must be a non-null object.'); + } + + if ( + request.options !== undefined && + (typeof request.options !== 'object' || request.options === null) + ) { + throw new SignalStudyError('invalid_option', 'request.options must be a non-null object.'); + } + + const postDays = + request.options?.postDays === undefined ? DEFAULT_EVENT_POST_DAYS : request.options.postDays; + if (typeof postDays !== 'number' || !Number.isInteger(postDays) || postDays < 0) { + throw new SignalStudyError( + 'invalid_option', + `postDays must be an integer >= 0, received ${String(postDays)}.` + ); + } + + const { sessionDates, entityReturns, benchmarkReturns, events } = request.input; + if (!Array.isArray(sessionDates)) { + throw new SignalStudyError( + 'invalid_panel', + 'request.input.sessionDates must be an array of YYYY-MM-DD dates.' + ); + } + if (sessionDates.length === 0) { + throw new SignalStudyError( + 'empty_panel', + 'request.input.sessionDates must contain at least one session date.' + ); + } + if (!Array.isArray(events)) { + throw new SignalStudyError('invalid_panel', 'request.input.events must be an array.'); + } + + // Validate sessionDates ordering and calendar validity before vault fencing, and locate + // the exclusive pre-cutoff prefix boundary. + let prevDate = ''; + let preCutoffLength = 0; + for (let i = 0; i < sessionDates.length; i += 1) { + const currentDate = assertStrictCalendarDate(sessionDates[i], `sessionDates[${i}]`); + if (i > 0) { + if (currentDate === prevDate) { + throw new SignalStudyError( + 'duplicate_date', + `Duplicate date "${currentDate}" at sessionDates[${i}].` + ); + } + if (currentDate < prevDate) { + throw new SignalStudyError( + 'unsorted_dates', + `sessionDates must be strictly ascending: "${currentDate}" < "${prevDate}" at index ${i}.` + ); + } + } + if (currentDate < request.vaultCutoffDate) { + preCutoffLength += 1; + } + prevDate = currentDate; + } + + const totalSessions = sessionDates.length; + + // Validate return series shapes against the full calendar before slicing to the pre-cutoff + // prefix so excluded Vault-tail values (e.g. non-finite returns) never leak into or break + // the pre-Vault study. Require the ReadonlyMap lookup interface (get/has/iterator) so + // serialized pair arrays with duplicate keys are rejected rather than coerced into a Map. + if (!isReadonlyMapLike(entityReturns)) { + throw new SignalStudyError( + 'invalid_panel', + 'request.input.entityReturns must be a ReadonlyMap of entityId to return series.' + ); + } + + const needsVaultTrim = preCutoffLength < totalSessions; + let fencedBenchmarkReturns: NumericSeries | undefined; + if (benchmarkReturns !== undefined) { + if (!isSupportedVector(benchmarkReturns)) { + throw new SignalStudyError( + 'invalid_panel', + 'request.input.benchmarkReturns must be an array or numeric typed array.' + ); + } + if (benchmarkReturns.length !== totalSessions) { + throw new SignalStudyError( + 'invalid_panel', + `benchmarkReturns length (${benchmarkReturns.length}) does not match sessionDates length (${totalSessions}).` + ); + } + fencedBenchmarkReturns = needsVaultTrim + ? sliceNumericSeries(benchmarkReturns, preCutoffLength) + : benchmarkReturns; + } + + const fencedEntityReturns = needsVaultTrim ? new Map() : null; + for (const entry of entityReturns) { + if (!Array.isArray(entry) || entry.length < 2) { + throw new SignalStudyError( + 'invalid_panel', + 'request.input.entityReturns entries must be [entityId, series] pairs.' + ); + } + const entityId: unknown = entry[0]; + const series: unknown = entry[1]; + const validEntityId = + typeof entityId === 'string' || (typeof entityId === 'number' && !Number.isNaN(entityId)); + if (!validEntityId) { + throw new SignalStudyError( + 'invalid_panel', + 'entityReturns key must be a string or non-NaN number.' + ); + } + if (!isSupportedVector(series)) { + throw new SignalStudyError( + 'invalid_panel', + `entityReturns[${String(entityId)}] must be an array or numeric typed array.` + ); + } + if (series.length !== totalSessions) { + throw new SignalStudyError( + 'invalid_panel', + `entityReturns[${String(entityId)}] length (${series.length}) does not match sessionDates length (${totalSessions}).` + ); + } + if (fencedEntityReturns !== null) { + if (fencedEntityReturns.has(entityId)) { + throw new SignalStudyError( + 'invalid_panel', + `Duplicate entityId "${String(entityId)}" in request.input.entityReturns.` + ); + } + fencedEntityReturns.set( + entityId, + sliceNumericSeries(series as NumericSeries, preCutoffLength) + ); + } + } + + // Validate each event and fence out any event touching or extending into the Vault window. + const fencedEvents: EventStudyEvent[] = []; + let vaultExcludedEvents = 0; + for (let i = 0; i < events.length; i += 1) { + const evt: unknown = events[i]; + if (typeof evt !== 'object' || evt === null) { + throw new SignalStudyError('invalid_panel', `events[${i}] must be a non-null object.`); + } + const candidate = evt as Partial; + const entityId = candidate.entityId; + const validId = + typeof entityId === 'string' || (typeof entityId === 'number' && !Number.isNaN(entityId)); + if (!validId) { + throw new SignalStudyError( + 'invalid_panel', + `events[${i}].entityId must be a string or non-NaN number.` + ); + } + const dayIndex = candidate.dayIndex; + if (typeof dayIndex !== 'number' || !Number.isInteger(dayIndex) || dayIndex < 0) { + throw new SignalStudyError( + 'invalid_panel', + `events[${i}].dayIndex must be a non-negative integer, received ${String(dayIndex)}.` + ); + } + + const eventDate = sessionDates[dayIndex]; + const postWindowEndDate = sessionDates[dayIndex + postDays]; + if ( + (eventDate !== undefined && eventDate >= request.vaultCutoffDate) || + (postWindowEndDate !== undefined && postWindowEndDate >= request.vaultCutoffDate) + ) { + vaultExcludedEvents += 1; + continue; + } + + fencedEvents.push({ entityId, dayIndex }); + } + + const fencedSessionDates = needsVaultTrim ? sessionDates.slice(0, preCutoffLength) : sessionDates; + const fencedInput: EventStudyInput = { + sessionDates: fencedSessionDates, + entityReturns: fencedEntityReturns ?? entityReturns, + ...(fencedBenchmarkReturns !== undefined ? { benchmarkReturns: fencedBenchmarkReturns } : {}), + events: fencedEvents, + }; + + let study: EventStudyResult; + try { + study = eventStudy(fencedInput, request.options); + } catch (error) { + if (error instanceof EventStudyError) { + throw mapEventStudyError(error); + } + throw error; + } + + if (study.status === 'insufficient_data') { + return { + status: 'insufficient_data', + study, + vaultExcludedEvents, + reason: study.reason, + }; + } + + const series = study.clustered.meanCars; + const seriesDates = study.clustered.dates; + if (series.length < 2 || seriesDates.length < 2) { + return { + status: 'insufficient_data', + study, + vaultExcludedEvents, + reason: 'too_few_observations', + }; + } + + const sampleStart = seriesDates[0]; + const sampleEnd = seriesDates[seriesDates.length - 1]; + if (sampleStart === undefined || sampleEnd === undefined) { + return { + status: 'insufficient_data', + study, + vaultExcludedEvents, + reason: 'too_few_observations', + }; + } + + let row: BuiltTrialRow; + try { + const expressionHash = canonicalExpressionHash({ + expression: request.expression.expression, + params: request.expression.params, + universe: request.expression.universe, + sampleStart, + sampleEnd, + horizon: request.expression.horizon, + }); + row = buildTrialRow({ + principalId: request.principalId, + campaignId: request.campaignId, + hypothesisId: request.hypothesisId, + stage: 'event_study', + universeMarket: request.universeMarket, + horizonBucket: request.horizonBucket, + expressionHash, + sampleStart, + sampleEnd, + vaultCutoffDate: request.vaultCutoffDate, + dailySeries: series, + }); + } catch (error) { + if (error instanceof TrialLedgerError) { + if (error.code === 'SERIES_TOO_SHORT') { + return { + status: 'insufficient_data', + study, + vaultExcludedEvents, + reason: 'too_few_observations', + }; + } + if (error.code === 'ZERO_VARIANCE_SERIES') { + return { + status: 'insufficient_data', + study, + vaultExcludedEvents, + reason: 'zero_variance_series', + }; + } + throw mapTrialLedgerError(error); + } + throw error; + } + + const { trial, deflatedSharpe } = await persistTrialAndEvaluateDsr( + executor, + row, + seriesDates, + request.dsrGate + ); + + return { + status: 'ok', + study, + vaultExcludedEvents, + trial, + deflatedSharpe, + }; +} diff --git a/libs/research/src/trial-ledger.ts b/libs/research/src/trial-ledger.ts new file mode 100644 index 00000000..bc89a636 --- /dev/null +++ b/libs/research/src/trial-ledger.ts @@ -0,0 +1,1775 @@ +/** + * Append-only `trial_ledger` writer and relatedness-cluster N-hat-deflated Sharpe + * reader (`design/VALIDATION-AND-RIGOR.md` §2.B–§2.C, `database/postgres/init/36-trial-ledger.sql`). + * + * Browser-safe and dependency-free: zero `node:*` imports, zero `pg` dependency, + * zero bare `process` access. SQL execution is injected via {@link TrialLedgerExecutor}. + */ + +import { + DSR_VALIDATION_GATE, + deflatedSharpeRatio, + effectiveIndependentTrials, + passesDsrGate, + trialMoments, +} from '@stock-bot/calculations'; +import { + MarketDataStoreValidationError, + VaultHoldoutFenceError, + applyVaultFence, +} from './market-data-store'; + +export const TRIAL_STAGES = ['signal_ic', 'event_study', 'screen', 'engine_backtest'] as const; +export type TrialStage = (typeof TRIAL_STAGES)[number]; + +export const UNIVERSE_MARKETS = ['US_EQ', 'CA_EQ', 'US_CA_EQ', 'FX'] as const; +export type UniverseMarket = (typeof UNIVERSE_MARKETS)[number]; + +export const HORIZON_BUCKETS = ['intraday', 'swing_1_10d', 'position_10d_plus'] as const; +export type HorizonBucket = (typeof HORIZON_BUCKETS)[number]; + +/** Maximum rows per single parameterised INSERT (`floor(65535 / 14)` PG protocol bind cap). */ +export const MAX_TRIAL_BATCH_SIZE = 4681; + +export type TrialLedgerErrorCode = + | 'INVALID_PRINCIPAL' + | 'INVALID_UUID' + | 'INVALID_STAGE' + | 'INVALID_UNIVERSE_MARKET' + | 'INVALID_HORIZON_BUCKET' + | 'INVALID_EXPRESSION_HASH' + | 'INVALID_EXPRESSION_INPUT' + | 'INVALID_DATE' + | 'INVALID_SAMPLE_WINDOW' + | 'VAULT_FENCE_VIOLATION' + | 'SERIES_TOO_SHORT' + | 'INVALID_SERIES_VALUE' + | 'ZERO_VARIANCE_SERIES' + | 'BATCH_TOO_LARGE' + | 'INVALID_TRIAL_ID' + | 'TRIAL_NOT_FOUND' + | 'INVALID_ROW'; + +/** Typed validation and lookup error thrown by `trial_ledger` helpers. */ +export class TrialLedgerError extends RangeError { + readonly code: TrialLedgerErrorCode; + + constructor(code: TrialLedgerErrorCode, message: string) { + super(message); + this.name = 'TrialLedgerError'; + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +export interface TrialLedgerQueryResult> { + readonly rows: readonly Row[]; + readonly rowCount?: number | null; +} + +/** + * Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module + * has no runtime dependency on `pg` and is unit-testable with a fake executor. + */ +export interface TrialLedgerExecutor { + query>( + text: string, + params?: readonly unknown[] + ): Promise>; +} + +export interface CanonicalExpressionInput { + readonly expression: string; + readonly params: unknown; + readonly universe: unknown; + readonly sampleStart: string; + readonly sampleEnd: string; + readonly horizon: string | number; +} + +export interface TrialRowInput { + readonly principalId: string; + readonly campaignId?: string | null; + readonly hypothesisId?: string | null; + readonly stage: TrialStage; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly expressionHash: string; + readonly sampleStart: string; + readonly sampleEnd: string; + readonly dailySeries: readonly number[] | Float32Array | Float64Array; + readonly vaultCutoffDate: string; + readonly dailyRiskFree?: number; +} + +export interface BuiltTrialRow { + readonly principalId: string; + readonly campaignId: string | null; + readonly hypothesisId: string | null; + readonly stage: TrialStage; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly expressionHash: string; + readonly sampleStart: string; + readonly sampleEnd: string; + readonly vaultCutoffDate: string; + readonly dailyRiskFree?: number; + readonly nObs: number; + readonly sharpeUnann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly dailySeries: readonly number[]; +} + +export interface RecordedTrialReceipt { + readonly trialId: number; + readonly createdAt: string; +} + +export interface LoadClusterTrialsQuery { + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly asOf?: string | Date; +} + +export interface TrialLedgerRow { + readonly trialId: number; + readonly createdAt: string; + readonly principalId: string; + readonly campaignId: string | null; + readonly stage: TrialStage; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly hypothesisId: string | null; + readonly expressionHash: string; + readonly sampleStart: string; + readonly sampleEnd: string; + readonly nObs: number; + readonly sharpeUnann: number; + readonly skewness: number; + readonly kurtosis: number; + readonly dailySeries: readonly number[]; +} + +export interface ClusterDeflatedSharpeQuery { + readonly trialId: number | bigint | string; + readonly asOf?: string | Date; + readonly dsrGate?: number; + /** + * Optional strictly-ascending `YYYY-MM-DD` trading calendar for the cluster's market. + * A trial without explicit observation dates is index-aligned only when `sessionDates` + * covers the trial's full `[sampleStart, sampleEnd]` range (`sessionDates[0] <= sampleStart` + * and `sessionDates[last] >= sampleEnd`) and its `dailySeries` length exactly matches the + * number of sessions in `[sampleStart, sampleEnd]`. + */ + readonly sessionDates?: readonly string[]; + /** + * Optional per-trial strictly-ascending `YYYY-MM-DD` observation dates for sparse series + * (e.g. `signal_ic` or `event_study`) that may omit dates within `[sampleStart, sampleEnd]`. + */ + readonly observationDatesByTrialId?: + | ReadonlyMap + | Readonly>; +} + +export interface ClusterDeflatedSharpeResult { + readonly trialId: number; + readonly universeMarket: UniverseMarket; + readonly horizonBucket: HorizonBucket; + readonly clusterSize: number; + readonly effectiveTrials: number; + readonly meanCorrelation: number | null; + readonly pairsUsed: number; + readonly pairsSkipped: number; + readonly sr0: number | null; + readonly standardError: number | null; + readonly dsr: number | null; + readonly passesGate: boolean; +} + +const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const ISO_OFFSET_TIMESTAMP_PATTERN = + /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/; +const AGENT_PRINCIPAL_PATTERN = + /^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 UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const EXPRESSION_HASH_PATTERN = /^[0-9a-f]{64}$/; +const POSITIVE_INT_PATTERN = /^[1-9]\d*$/; +const MOMENT_MATCH_REL_TOL = 1e-12; + +const TRIAL_STAGE_SET: ReadonlySet = new Set(TRIAL_STAGES); +const UNIVERSE_MARKET_SET: ReadonlySet = new Set(UNIVERSE_MARKETS); +const HORIZON_BUCKET_SET: ReadonlySet = new Set(HORIZON_BUCKETS); + +const COLUMNS_PER_ROW = 14; +const UTC_CREATED_AT_SQL = `to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS created_at`; + +const SELECT_TRIAL_COLUMNS = ` + trial_id, + ${UTC_CREATED_AT_SQL}, + principal_id, + campaign_id, + stage, + universe_market, + horizon_bucket, + hypothesis_id, + expression_hash, + sample_start::text AS sample_start, + sample_end::text AS sample_end, + n_obs, + sharpe_unann, + skewness, + 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; +} + +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 canonicalizeJsonValue(value: unknown, path: string, seen: Set): string { + if (value === null) { + return 'null'; + } + + const valueType = typeof value; + if (valueType === 'boolean') { + return value ? 'true' : 'false'; + } + if (valueType === 'string') { + return JSON.stringify(value); + } + if (valueType === 'number') { + if (!Number.isFinite(value)) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + `Non-finite number at "${path}" is not allowed in canonicalExpressionHash.` + ); + } + return JSON.stringify(Object.is(value, -0) ? 0 : value); + } + if (valueType === 'undefined') { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + `Undefined value at "${path}" is not allowed in canonicalExpressionHash.` + ); + } + if (valueType !== 'object') { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + `Unsupported value type "${valueType}" at "${path}" in canonicalExpressionHash.` + ); + } + + const obj = value as object; + if (seen.has(obj)) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + `Circular reference detected at "${path}" in canonicalExpressionHash.` + ); + } + + if (Array.isArray(obj)) { + seen.add(obj); + try { + const parts: string[] = new Array(obj.length); + for (let i = 0; i < obj.length; i += 1) { + parts[i] = canonicalizeJsonValue(obj[i], `${path}[${i}]`, seen); + } + return `[${parts.join(',')}]`; + } finally { + seen.delete(obj); + } + } + + if (!isPlainObject(obj)) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + `Unsupported non-plain object at "${path}" in canonicalExpressionHash.` + ); + } + + seen.add(obj); + try { + const keys = Object.keys(obj).sort(compareAscii); + const entries: string[] = []; + for (let i = 0; i < keys.length; i += 1) { + const key = keys[i] as string; + const entryValue = obj[key]; + if (entryValue === undefined) { + continue; + } + entries.push(`${JSON.stringify(key)}:${canonicalizeJsonValue(entryValue, `${path}.${key}`, seen)}`); + } + return `{${entries.join(',')}}`; + } finally { + seen.delete(obj); + } +} + +function assertDateOnlyFormat(value: unknown, field: string): string { + if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) { + throw new TrialLedgerError( + 'INVALID_DATE', + `Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".` + ); + } + return value; +} + +function validateSampleWindowUnfenced(sampleStart: unknown, sampleEnd: unknown): { + sampleStart: string; + sampleEnd: string; +} { + const start = assertDateOnlyFormat(sampleStart, 'sampleStart'); + const end = assertDateOnlyFormat(sampleEnd, 'sampleEnd'); + try { + applyVaultFence( + { from: start, to: end, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ); + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + if (error.message.includes('must not be after end')) { + throw new TrialLedgerError( + 'INVALID_SAMPLE_WINDOW', + `sampleStart "${start}" must not be after sampleEnd "${end}".` + ); + } + throw new TrialLedgerError('INVALID_DATE', error.message); + } + throw error; + } + return { sampleStart: start, sampleEnd: end }; +} + +function validateSampleWindowFenced( + sampleStart: unknown, + sampleEnd: unknown, + vaultCutoffDate: unknown +): { + sampleStart: string; + sampleEnd: string; + vaultCutoffDate: string; +} { + const start = assertDateOnlyFormat(sampleStart, 'sampleStart'); + const end = assertDateOnlyFormat(sampleEnd, 'sampleEnd'); + const cutoff = assertDateOnlyFormat(vaultCutoffDate, 'vaultCutoffDate'); + + let cutoffMs: number; + try { + const cutoffRange = applyVaultFence( + { from: cutoff, to: cutoff, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ); + cutoffMs = cutoffRange.fromMs; + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + throw new TrialLedgerError('INVALID_DATE', `Invalid vaultCutoffDate "${cutoff}": ${error.message}`); + } + throw error; + } + + let fenced; + try { + fenced = applyVaultFence({ from: start, to: end, scope: 'vault_fenced' }, { vaultCutoffTs: cutoffMs }); + } catch (error) { + if (error instanceof VaultHoldoutFenceError) { + throw new TrialLedgerError( + 'VAULT_FENCE_VIOLATION', + `Sample window [${start}, ${end}] violates exclusive vaultCutoffDate "${cutoff}".` + ); + } + if (error instanceof MarketDataStoreValidationError) { + if (error.message.includes('must not be after end')) { + throw new TrialLedgerError( + 'INVALID_SAMPLE_WINDOW', + `sampleStart "${start}" must not be after sampleEnd "${end}".` + ); + } + throw new TrialLedgerError('INVALID_DATE', error.message); + } + throw error; + } + + if (fenced.clampedTo) { + throw new TrialLedgerError( + 'VAULT_FENCE_VIOLATION', + `sampleEnd "${end}" must be strictly before vaultCutoffDate "${cutoff}".` + ); + } + + return { sampleStart: start, sampleEnd: end, vaultCutoffDate: cutoff }; +} + +function validatePrincipalId(value: unknown): string { + if (typeof value !== 'string' || (value !== 'operator' && !AGENT_PRINCIPAL_PATTERN.test(value))) { + throw new TrialLedgerError( + 'INVALID_PRINCIPAL', + `Invalid principalId "${String(value)}": expected 'operator' or 'agent:'.` + ); + } + return value; +} + +function validateOptionalUuid(value: unknown, field: string): string | null { + if (value === undefined || value === null) { + return null; + } + if (typeof value !== 'string' || !UUID_PATTERN.test(value)) { + throw new TrialLedgerError('INVALID_UUID', `Invalid UUID for "${field}": "${String(value)}".`); + } + return value.toLowerCase(); +} + +function validateStage(value: unknown): TrialStage { + if (typeof value !== 'string' || !TRIAL_STAGE_SET.has(value)) { + throw new TrialLedgerError( + 'INVALID_STAGE', + `Invalid stage "${String(value)}". Expected one of: ${TRIAL_STAGES.join(', ')}.` + ); + } + return value as TrialStage; +} + +function validateUniverseMarket(value: unknown): UniverseMarket { + if (typeof value !== 'string' || !UNIVERSE_MARKET_SET.has(value)) { + throw new TrialLedgerError( + 'INVALID_UNIVERSE_MARKET', + `Invalid universeMarket "${String(value)}". Expected one of: ${UNIVERSE_MARKETS.join(', ')}.` + ); + } + return value as UniverseMarket; +} + +function validateHorizonBucket(value: unknown): HorizonBucket { + if (typeof value !== 'string' || !HORIZON_BUCKET_SET.has(value)) { + throw new TrialLedgerError( + 'INVALID_HORIZON_BUCKET', + `Invalid horizonBucket "${String(value)}". Expected one of: ${HORIZON_BUCKETS.join(', ')}.` + ); + } + return value as HorizonBucket; +} + +function validateExpressionHash(value: unknown): string { + if (typeof value !== 'string' || !EXPRESSION_HASH_PATTERN.test(value)) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_HASH', + `Invalid expressionHash "${String(value)}": expected 64 lowercase hexadecimal characters.` + ); + } + return value; +} + +function validateDailySeries(value: unknown, allowZeroVariance = false): number[] { + const isTyped = value instanceof Float32Array || value instanceof Float64Array; + if (!Array.isArray(value) && !isTyped) { + throw new TrialLedgerError( + 'INVALID_SERIES_VALUE', + 'dailySeries must be an array, Float32Array, or Float64Array of finite numbers.' + ); + } + const len = value.length; + if (len < 2) { + throw new TrialLedgerError( + 'SERIES_TOO_SHORT', + `dailySeries must contain at least 2 finite observations (got ${len}).` + ); + } + + const normalized: number[] = new Array(len); + let firstReal = 0; + let allEqualReal = true; + for (let i = 0; i < len; i += 1) { + const v: unknown = value[i]; + if (typeof v !== 'number' || !Number.isFinite(v)) { + throw new TrialLedgerError( + 'INVALID_SERIES_VALUE', + `dailySeries[${i}] is not a finite number: ${String(v)}.` + ); + } + const asReal = Math.fround(v); + if (!Number.isFinite(asReal) || (v !== 0 && asReal === 0)) { + throw new TrialLedgerError( + 'INVALID_SERIES_VALUE', + `dailySeries[${i}] (${v}) is outside finite PostgreSQL REAL (float32) range.` + ); + } + if (i === 0) { + firstReal = asReal; + } else if (asReal !== firstReal) { + allEqualReal = false; + } + normalized[i] = Object.is(v, -0) ? 0 : v; + } + if (!allowZeroVariance && allEqualReal) { + throw new TrialLedgerError( + 'ZERO_VARIANCE_SERIES', + 'dailySeries has zero variance at PostgreSQL REAL (float32) storage precision.' + ); + } + return normalized; +} + +function assertExecutor(executor: unknown): asserts executor is TrialLedgerExecutor { + if ( + typeof executor !== 'object' || + executor === null || + typeof (executor as { query?: unknown }).query !== 'function' + ) { + throw new TrialLedgerError( + 'INVALID_ROW', + 'Expected a TrialLedgerExecutor object with a query(text, params) method.' + ); + } +} + +function parseTrialId(value: unknown): number { + if (typeof value === 'number') { + if (!Number.isSafeInteger(value) || value < 1) { + throw new TrialLedgerError( + 'INVALID_TRIAL_ID', + `Invalid trialId "${String(value)}": expected a positive safe integer.` + ); + } + return value; + } + if (typeof value === 'bigint') { + if (value < 1n || value > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new TrialLedgerError( + 'INVALID_TRIAL_ID', + `Invalid trialId "${value.toString()}": expected a positive safe integer.` + ); + } + return Number(value); + } + if (typeof value === 'string' && POSITIVE_INT_PATTERN.test(value)) { + const parsed = Number(value); + if (Number.isSafeInteger(parsed) && parsed >= 1) { + return parsed; + } + } + throw new TrialLedgerError( + 'INVALID_TRIAL_ID', + `Invalid trialId "${String(value)}": expected a positive safe integer.` + ); +} + +function formatUtcInstantFromMs(epochMs: number, fractionalDigits?: string): string { + const baseIso = new Date(epochMs).toISOString(); + if (fractionalDigits === undefined || fractionalDigits.length <= 3) { + return baseIso; + } + const micros = fractionalDigits.slice(3, 6).padEnd(3, '0'); + return `${baseIso.slice(0, -1)}${micros}Z`; +} + +function normalizeAsOf(asOf: unknown): string | undefined { + if (asOf === undefined) { + return undefined; + } + if (asOf instanceof Date) { + const ms = asOf.getTime(); + if (!Number.isFinite(ms)) { + throw new TrialLedgerError('INVALID_DATE', 'Invalid asOf Date instance.'); + } + return asOf.toISOString(); + } + if (typeof asOf !== 'string') { + throw new TrialLedgerError( + 'INVALID_DATE', + `Invalid asOf "${String(asOf)}": expected ISO-8601 UTC timestamp, YYYY-MM-DD date, or Date.` + ); + } + try { + const fenced = applyVaultFence( + { from: '1970-01-01', to: '1970-01-01', asOf, scope: 'vault_evaluation_only' }, + { vaultCutoffTs: 0, vaultOperatorAuthorized: true } + ); + const instantMatch = ISO_OFFSET_TIMESTAMP_PATTERN.exec(asOf); + if (instantMatch !== null) { + return formatUtcInstantFromMs(fenced.asOfMs, instantMatch[2]); + } + return new Date(fenced.asOfMs).toISOString(); + } catch (error) { + if (error instanceof MarketDataStoreValidationError) { + throw new TrialLedgerError('INVALID_DATE', error.message); + } + throw error; + } +} + +function formatUtcTimestamp(value: unknown, field: string): string { + if (value instanceof Date) { + if (!Number.isFinite(value.getTime())) { + throw new TrialLedgerError('INVALID_ROW', `Invalid timestamp for "${field}".`); + } + return value.toISOString(); + } + if (typeof value === 'string') { + const ms = Date.parse(value); + if (!Number.isFinite(ms)) { + throw new TrialLedgerError('INVALID_ROW', `Invalid timestamp string for "${field}": "${value}".`); + } + const instantMatch = ISO_OFFSET_TIMESTAMP_PATTERN.exec(value); + if (instantMatch !== null) { + return formatUtcInstantFromMs(ms, instantMatch[2]); + } + return new Date(ms).toISOString(); + } + throw new TrialLedgerError('INVALID_ROW', `Unexpected timestamp value for "${field}".`); +} + +function formatDateOnlyFromDb(value: unknown, field: string): string { + if (typeof value === 'string' && DATE_ONLY_PATTERN.test(value)) { + return value; + } + if (value instanceof Date && Number.isFinite(value.getTime())) { + return value.toISOString().slice(0, 10); + } + throw new TrialLedgerError('INVALID_ROW', `Unexpected date value for "${field}": "${String(value)}".`); +} + +function parsePgRealArray(value: unknown): number[] { + if (Array.isArray(value)) { + return validateDailySeries( + value.map(v => Number(v)), + true + ); + } + if (value instanceof Float32Array || value instanceof Float64Array) { + return validateDailySeries(value, true); + } + if (typeof value === 'string' && value.startsWith('{') && value.endsWith('}')) { + const inner = value.slice(1, -1).trim(); + if (inner.length === 0) { + throw new TrialLedgerError('SERIES_TOO_SHORT', 'Empty daily_series returned from database.'); + } + const elements = inner.split(',').map(token => Number(token)); + return validateDailySeries(elements, true); + } + throw new TrialLedgerError('INVALID_ROW', 'Unexpected daily_series value returned from database.'); +} + +function parseDbTrialRow(raw: Record): TrialLedgerRow { + const trialId = parseTrialId(raw.trial_id); + const createdAt = formatUtcTimestamp(raw.created_at, 'created_at'); + const principalId = validatePrincipalId(raw.principal_id); + const campaignId = validateOptionalUuid(raw.campaign_id, 'campaign_id'); + const stage = validateStage(raw.stage); + const universeMarket = validateUniverseMarket(raw.universe_market); + const horizonBucket = validateHorizonBucket(raw.horizon_bucket); + const hypothesisId = validateOptionalUuid(raw.hypothesis_id, 'hypothesis_id'); + const expressionHash = validateExpressionHash( + typeof raw.expression_hash === 'string' ? raw.expression_hash.trim() : raw.expression_hash + ); + const sampleStart = formatDateOnlyFromDb(raw.sample_start, 'sample_start'); + const sampleEnd = formatDateOnlyFromDb(raw.sample_end, 'sample_end'); + const nObs = Number(raw.n_obs); + const sharpeUnann = Number(raw.sharpe_unann); + const skewness = Number(raw.skewness); + const kurtosis = Number(raw.kurtosis); + if ( + !Number.isSafeInteger(nObs) || + nObs < 2 || + !Number.isFinite(sharpeUnann) || + !Number.isFinite(skewness) || + !Number.isFinite(kurtosis) + ) { + throw new TrialLedgerError('INVALID_ROW', `Corrupted numeric moments for trial_id=${trialId}.`); + } + const dailySeries = parsePgRealArray(raw.daily_series); + + return Object.freeze({ + trialId, + createdAt, + principalId, + campaignId, + stage, + universeMarket, + horizonBucket, + hypothesisId, + expressionHash, + sampleStart, + sampleEnd, + nObs, + sharpeUnann, + skewness, + kurtosis, + dailySeries: Object.freeze(dailySeries), + }); +} + +function isPreBuiltTrialRow(row: TrialRowInput | BuiltTrialRow): row is BuiltTrialRow { + return ( + 'nObs' in row || 'sharpeUnann' in row || 'skewness' in row || 'kurtosis' in row + ); +} + +function momentsClose(actual: number, expected: number): boolean { + const scale = Math.max(1, Math.abs(expected)); + return Math.abs(actual - expected) <= MOMENT_MATCH_REL_TOL * scale; +} + +function validateRowForInsert(row: TrialRowInput | BuiltTrialRow, index: number): BuiltTrialRow { + if (typeof row !== 'object' || row === null) { + throw new TrialLedgerError('INVALID_ROW', `Row at index ${index} must be a non-null object.`); + } + + if (!isPreBuiltTrialRow(row)) { + return buildTrialRow(row); + } + + const principalId = validatePrincipalId(row.principalId); + const campaignId = validateOptionalUuid(row.campaignId, 'campaignId'); + const hypothesisId = validateOptionalUuid(row.hypothesisId, 'hypothesisId'); + const stage = validateStage(row.stage); + const universeMarket = validateUniverseMarket(row.universeMarket); + const horizonBucket = validateHorizonBucket(row.horizonBucket); + const expressionHash = validateExpressionHash(row.expressionHash); + const { sampleStart, sampleEnd, vaultCutoffDate } = validateSampleWindowFenced( + row.sampleStart, + row.sampleEnd, + row.vaultCutoffDate + ); + const dailySeries = validateDailySeries(row.dailySeries); + + const dailyRiskFree = row.dailyRiskFree ?? 0; + if (typeof dailyRiskFree !== 'number' || !Number.isFinite(dailyRiskFree)) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Row at index ${index} has invalid dailyRiskFree "${String(row.dailyRiskFree)}": expected a finite number.` + ); + } + + if (!Number.isSafeInteger(row.nObs) || row.nObs !== dailySeries.length) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Row at index ${index} has nObs=${String(row.nObs)} which does not match dailySeries.length (${dailySeries.length}).` + ); + } + if ( + typeof row.sharpeUnann !== 'number' || + !Number.isFinite(row.sharpeUnann) || + typeof row.skewness !== 'number' || + !Number.isFinite(row.skewness) || + typeof row.kurtosis !== 'number' || + !Number.isFinite(row.kurtosis) + ) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Row at index ${index} has non-finite moments (sharpeUnann, skewness, kurtosis).` + ); + } + + // Recompute moments from dailySeries and verify the pre-built row matches them so stale + // template moments cannot be persisted alongside a different return/IC vector. + const computed = trialMoments(dailySeries, dailyRiskFree); + if (computed === null) { + throw new TrialLedgerError( + 'ZERO_VARIANCE_SERIES', + `Row at index ${index} has a zero-variance or degenerate dailySeries.` + ); + } + if ( + !momentsClose(row.sharpeUnann, computed.sharpeUnann) || + !momentsClose(row.skewness, computed.skewness) || + !momentsClose(row.kurtosis, computed.kurtosis) + ) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Row at index ${index} has moments (sharpeUnann, skewness, kurtosis) that do not match dailySeries.` + ); + } + + return Object.freeze({ + principalId, + campaignId, + hypothesisId, + stage, + universeMarket, + horizonBucket, + expressionHash, + sampleStart, + sampleEnd, + vaultCutoffDate, + dailyRiskFree, + nObs: computed.nObs, + sharpeUnann: computed.sharpeUnann, + skewness: computed.skewness, + kurtosis: computed.kurtosis, + dailySeries: Object.freeze(dailySeries), + }); +} + +const DAYS_IN_CALENDAR_MONTH: readonly number[] = [ + 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, +]; + +function assertValidCalendarDate(raw: unknown, field: string): string { + const dateStr = assertDateOnlyFormat(raw, field); + const year = Number(dateStr.slice(0, 4)); + const month = Number(dateStr.slice(5, 7)); + const day = Number(dateStr.slice(8, 10)); + if (month < 1 || month > 12) { + throw new TrialLedgerError('INVALID_DATE', `Invalid calendar month in "${field}": "${dateStr}".`); + } + const isLeap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; + const maxDay = month === 2 && isLeap ? 29 : (DAYS_IN_CALENDAR_MONTH[month - 1] as number); + if (day < 1 || day > maxDay) { + throw new TrialLedgerError('INVALID_DATE', `Invalid calendar day in "${field}": "${dateStr}".`); + } + return dateStr; +} + +function validateSortedDates(raw: unknown, field: string): readonly string[] { + if (!Array.isArray(raw)) { + throw new TrialLedgerError( + 'INVALID_DATE', + `Invalid "${field}": expected an array of strictly ascending YYYY-MM-DD dates.` + ); + } + const len = raw.length; + const validated: string[] = new Array(len); + for (let i = 0; i < len; i += 1) { + const dateStr = assertValidCalendarDate(raw[i], `${field}[${i}]`); + if (i > 0 && dateStr <= (validated[i - 1] as string)) { + throw new TrialLedgerError( + 'INVALID_DATE', + `Dates in "${field}" must be strictly ascending: "${dateStr}" <= "${validated[i - 1] as string}".` + ); + } + validated[i] = dateStr; + } + return validated; +} + +function normalizeObservationDatesMap( + raw: ClusterDeflatedSharpeQuery['observationDatesByTrialId'] +): Map | undefined { + if (raw === undefined) { + return undefined; + } + const result = new Map(); + if (raw instanceof Map) { + for (const [key, dates] of raw.entries()) { + const id = parseTrialId(key); + if (result.has(id)) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Duplicate trialId ${id} in observationDatesByTrialId.` + ); + } + result.set(id, validateSortedDates(dates, `observationDatesByTrialId[${id}]`)); + } + return result; + } + if (!isPlainObject(raw)) { + throw new TrialLedgerError( + 'INVALID_ROW', + 'observationDatesByTrialId must be a Map or plain object mapping trialId to YYYY-MM-DD[].' + ); + } + for (const [key, dates] of Object.entries(raw)) { + const id = parseTrialId(key); + result.set(id, validateSortedDates(dates, `observationDatesByTrialId[${id}]`)); + } + return result; +} + +function lowerBoundDate(sorted: readonly string[], target: string): number { + let lo = 0; + let hi = sorted.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if ((sorted[mid] as string) < target) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; +} + +function upperBoundDate(sorted: readonly string[], target: string): number { + let lo = 0; + let hi = sorted.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if ((sorted[mid] as string) <= target) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; +} + +interface PreparedDenseSeries { + readonly values: Float64Array; + readonly prefixSum: Float64Array; +} + +function prepareDenseSeries(series: readonly number[]): PreparedDenseSeries { + const len = series.length; + const values = new Float64Array(len); + const prefixSum = new Float64Array(len + 1); + let running = 0; + for (let t = 0; t < len; t += 1) { + const v = series[t] as number; + values[t] = v; + running += v; + prefixSum[t + 1] = running; + } + return { values, prefixSum }; +} + +function pearsonSliceCorrelation( + a: PreparedDenseSeries, + offsetA: number, + b: PreparedDenseSeries, + offsetB: number, + len: number +): number | null { + if (len < 2) { + return null; + } + + const meanA = + ((a.prefixSum[offsetA + len] as number) - (a.prefixSum[offsetA] as number)) / len; + const meanB = + ((b.prefixSum[offsetB + len] as number) - (b.prefixSum[offsetB] as number)) / len; + const aVals = a.values; + const bVals = b.values; + const firstA = aVals[offsetA] as number; + const firstB = bVals[offsetB] as number; + let allEqualA = true; + let allEqualB = true; + + let cov = 0; + let varA = 0; + let varB = 0; + + for (let t = 0; t < len; t += 1) { + const va = aVals[offsetA + t] as number; + const vb = bVals[offsetB + t] as number; + if (allEqualA && va !== firstA) { + allEqualA = false; + } + if (allEqualB && vb !== firstB) { + allEqualB = false; + } + const da = va - meanA; + const db = vb - meanB; + cov += da * db; + varA += da * da; + varB += db * db; + } + + if ( + allEqualA || + allEqualB || + !Number.isFinite(varA) || + !Number.isFinite(varB) || + varA <= 0 || + varB <= 0 + ) { + return null; + } + const denom = Math.sqrt(varA * varB); + if (!Number.isFinite(denom) || denom <= 0) { + return null; + } + const rawRho = cov / denom; + if (!Number.isFinite(rawRho)) { + return null; + } + return rawRho < -1 ? -1 : rawRho > 1 ? 1 : rawRho; +} + +function pearsonDateMergedCorrelation( + aSeries: readonly number[], + aDates: readonly string[], + aStart: number, + aEnd: number, + bSeries: readonly number[], + bDates: readonly string[], + bStart: number, + bEnd: number +): number | null { + if (aEnd - aStart < 2 || bEnd - bStart < 2) { + return null; + } + if ((aDates[aEnd - 1] as string) < (bDates[bStart] as string)) { + return null; + } + if ((bDates[bEnd - 1] as string) < (aDates[aStart] as string)) { + return null; + } + + let ia = aStart; + let ib = bStart; + let overlap = 0; + let sumA = 0; + let sumB = 0; + let firstA = 0; + let firstB = 0; + let allEqualA = true; + let allEqualB = true; + + while (ia < aEnd && ib < bEnd) { + const da = aDates[ia] as string; + const db = bDates[ib] as string; + if (da === db) { + const va = aSeries[ia - aStart] as number; + const vb = bSeries[ib - bStart] as number; + if (Number.isFinite(va) && Number.isFinite(vb)) { + if (overlap === 0) { + firstA = va; + firstB = vb; + } else { + if (va !== firstA) { + allEqualA = false; + } + if (vb !== firstB) { + allEqualB = false; + } + } + sumA += va; + sumB += vb; + overlap += 1; + } + ia += 1; + ib += 1; + } else if (da < db) { + ia += 1; + } else { + ib += 1; + } + } + + if (overlap < 2 || allEqualA || allEqualB) { + return null; + } + + const meanA = sumA / overlap; + const meanB = sumB / overlap; + let cov = 0; + let varA = 0; + let varB = 0; + + ia = aStart; + ib = bStart; + while (ia < aEnd && ib < bEnd) { + const da = aDates[ia] as string; + const db = bDates[ib] as string; + if (da === db) { + const va = aSeries[ia - aStart] as number; + const vb = bSeries[ib - bStart] as number; + if (Number.isFinite(va) && Number.isFinite(vb)) { + const diffA = va - meanA; + const diffB = vb - meanB; + cov += diffA * diffB; + varA += diffA * diffA; + varB += diffB * diffB; + } + ia += 1; + ib += 1; + } else if (da < db) { + ia += 1; + } else { + ib += 1; + } + } + + if (!Number.isFinite(varA) || !Number.isFinite(varB) || varA <= 0 || varB <= 0) { + return null; + } + const denom = Math.sqrt(varA * varB); + if (!Number.isFinite(denom) || denom <= 0) { + return null; + } + const rawRho = cov / denom; + if (!Number.isFinite(rawRho)) { + return null; + } + return rawRho < -1 ? -1 : rawRho > 1 ? 1 : rawRho; +} + +interface DenseWindowGroup { + readonly startIdx: number; + readonly endExclusive: number; + readonly seriesList: (readonly number[])[]; +} + +interface ExplicitDateTrial { + readonly series: readonly number[]; + readonly dates: readonly string[]; +} + +interface ClusterEffectiveTrials { + readonly pairsUsed: number; + readonly pairsSkipped: number; + readonly meanCorrelation: number | null; + readonly nHat: number; +} + +function computeClusterEffectiveTrials( + cluster: readonly TrialLedgerRow[], + sessionDates: readonly string[] | undefined, + observationDatesMap: ReadonlyMap | undefined +): ClusterEffectiveTrials { + const k = cluster.length; + if (k <= 1) { + return { pairsUsed: 0, pairsSkipped: 0, meanCorrelation: null, nHat: 1 }; + } + + const denseGroupByKey = new Map(); + const denseGroups: DenseWindowGroup[] = []; + const explicitTrials: ExplicitDateTrial[] = []; + let unalignedCount = 0; + + for (let i = 0; i < k; i += 1) { + const trial = cluster[i] as TrialLedgerRow; + const explicitDates = observationDatesMap?.get(trial.trialId); + if (explicitDates !== undefined) { + if (explicitDates.length !== trial.dailySeries.length) { + throw new TrialLedgerError( + 'INVALID_ROW', + `observationDatesByTrialId[${trial.trialId}] length (${explicitDates.length}) does not match dailySeries.length (${trial.dailySeries.length}).` + ); + } + const firstDate = explicitDates[0] as string; + const lastDate = explicitDates[explicitDates.length - 1] as string; + if (firstDate < trial.sampleStart || lastDate > trial.sampleEnd) { + throw new TrialLedgerError( + 'INVALID_SAMPLE_WINDOW', + `observationDatesByTrialId[${trial.trialId}] range [${firstDate}, ${lastDate}] lies outside trial window [${trial.sampleStart}, ${trial.sampleEnd}].` + ); + } + explicitTrials.push({ series: trial.dailySeries, dates: explicitDates }); + continue; + } + + if ( + sessionDates !== undefined && + sessionDates.length > 0 && + (sessionDates[0] as string) <= trial.sampleStart && + (sessionDates[sessionDates.length - 1] as string) >= trial.sampleEnd + ) { + const startIdx = lowerBoundDate(sessionDates, trial.sampleStart); + const endExclusive = upperBoundDate(sessionDates, trial.sampleEnd); + if (endExclusive - startIdx === trial.dailySeries.length) { + const key = `${startIdx}:${endExclusive}`; + let group = denseGroupByKey.get(key); + if (group === undefined) { + group = { startIdx, endExclusive, seriesList: [] }; + denseGroupByKey.set(key, group); + denseGroups.push(group); + } + group.seriesList.push(trial.dailySeries); + continue; + } + } + + unalignedCount += 1; + } + + // Fast path: all K trials are proven dense on the exact same session window. + if (denseGroups.length === 1 && (denseGroups[0] as DenseWindowGroup).seriesList.length === k) { + const eff = effectiveIndependentTrials((denseGroups[0] as DenseWindowGroup).seriesList); + return { + pairsUsed: eff.pairsUsed, + pairsSkipped: eff.pairsSkipped, + meanCorrelation: eff.meanCorrelation, + nHat: eff.nHat, + }; + } + + let rhoSum = 0; + let pairsUsed = 0; + let pairsSkipped = 0; + + // 1. Within-group correlations for dense groups (uses fast unit-vector dot-product path). + for (let g = 0; g < denseGroups.length; g += 1) { + const group = denseGroups[g] as DenseWindowGroup; + if (group.seriesList.length < 2) { + continue; + } + const eff = effectiveIndependentTrials(group.seriesList); + if (eff.meanCorrelation !== null) { + rhoSum += eff.meanCorrelation * eff.pairsUsed; + } + pairsUsed += eff.pairsUsed; + pairsSkipped += eff.pairsSkipped; + } + + // 2. Cross-group correlations between distinct dense windows (zero NaN padding). + if (denseGroups.length > 1) { + const preparedGroups: PreparedDenseSeries[][] = denseGroups.map(group => + group.seriesList.map(series => prepareDenseSeries(series)) + ); + for (let ga = 0; ga < denseGroups.length - 1; ga += 1) { + const groupA = denseGroups[ga] as DenseWindowGroup; + const prepA = preparedGroups[ga] as PreparedDenseSeries[]; + for (let gb = ga + 1; gb < denseGroups.length; gb += 1) { + const groupB = denseGroups[gb] as DenseWindowGroup; + const ovStart = groupA.startIdx > groupB.startIdx ? groupA.startIdx : groupB.startIdx; + const ovEnd = + groupA.endExclusive < groupB.endExclusive ? groupA.endExclusive : groupB.endExclusive; + const ovLen = ovEnd - ovStart; + if (ovLen < 2) { + pairsSkipped += groupA.seriesList.length * groupB.seriesList.length; + continue; + } + const offsetA = ovStart - groupA.startIdx; + const offsetB = ovStart - groupB.startIdx; + const prepB = preparedGroups[gb] as PreparedDenseSeries[]; + for (let ia = 0; ia < prepA.length; ia += 1) { + const seriesA = prepA[ia] as PreparedDenseSeries; + for (let ib = 0; ib < prepB.length; ib += 1) { + const seriesB = prepB[ib] as PreparedDenseSeries; + const rho = pearsonSliceCorrelation(seriesA, offsetA, seriesB, offsetB, ovLen); + if (rho === null) { + pairsSkipped += 1; + } else { + rhoSum += rho; + pairsUsed += 1; + } + } + } + } + } + } + + // 3. Explicit-date trial vs explicit-date trial (exact two-pointer date merge). + for (let i = 0; i < explicitTrials.length - 1; i += 1) { + const a = explicitTrials[i] as ExplicitDateTrial; + for (let j = i + 1; j < explicitTrials.length; j += 1) { + const b = explicitTrials[j] as ExplicitDateTrial; + const rho = pearsonDateMergedCorrelation( + a.series, + a.dates, + 0, + a.dates.length, + b.series, + b.dates, + 0, + b.dates.length + ); + if (rho === null) { + pairsSkipped += 1; + } else { + rhoSum += rho; + pairsUsed += 1; + } + } + } + + // 4. Explicit-date trial vs dense-grid trial (zero-slice merge against sessionDates). + if (sessionDates !== undefined && explicitTrials.length > 0 && denseGroups.length > 0) { + for (let i = 0; i < explicitTrials.length; i += 1) { + const exp = explicitTrials[i] as ExplicitDateTrial; + for (let g = 0; g < denseGroups.length; g += 1) { + const group = denseGroups[g] as DenseWindowGroup; + if ( + (exp.dates[exp.dates.length - 1] as string) < (sessionDates[group.startIdx] as string) || + (sessionDates[group.endExclusive - 1] as string) < (exp.dates[0] as string) + ) { + pairsSkipped += group.seriesList.length; + continue; + } + for (let s = 0; s < group.seriesList.length; s += 1) { + const denseSeries = group.seriesList[s] as readonly number[]; + const rho = pearsonDateMergedCorrelation( + exp.series, + exp.dates, + 0, + exp.dates.length, + denseSeries, + sessionDates, + group.startIdx, + group.endExclusive + ); + if (rho === null) { + pairsSkipped += 1; + } else { + rhoSum += rho; + pairsUsed += 1; + } + } + } + } + } + + // 5. Pairs involving trials without proven date/grid alignment are skipped in O(1). + if (unalignedCount > 0) { + const alignedCount = k - unalignedCount; + pairsSkipped += unalignedCount * alignedCount + (unalignedCount * (unalignedCount - 1)) / 2; + } + + if (pairsUsed === 0) { + return { pairsUsed: 0, pairsSkipped, meanCorrelation: null, nHat: k }; + } + + const meanCorrelation = rhoSum / pairsUsed; + const nHat = Math.max(1, 1 + (k - 1) * (1 - Math.max(0, meanCorrelation))); + return { pairsUsed, pairsSkipped, meanCorrelation, nHat }; +} + +/** + * Computes a deterministic 64-character lowercase SHA-256 hex digest over the + * canonical, ASCII-key-sorted JSON representation of + * `{ expression, params, universe, sampleStart, sampleEnd, horizon }`. + */ +export function canonicalExpressionHash(input: CanonicalExpressionInput): string { + if (typeof input !== 'object' || input === null) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash input must be a non-null object.' + ); + } + + if (typeof input.expression !== 'string') { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash requires a non-empty string expression.' + ); + } + const normalizedExpression = input.expression.trim().replace(/\s+/g, ' '); + if (normalizedExpression.length === 0) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash expression must not be empty or whitespace-only.' + ); + } + + const { sampleStart, sampleEnd } = validateSampleWindowUnfenced( + input.sampleStart, + input.sampleEnd + ); + + let normalizedHorizon: string | number; + if (typeof input.horizon === 'string') { + if (input.horizon.trim().length === 0) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash horizon string must not be empty.' + ); + } + normalizedHorizon = input.horizon; + } else if (typeof input.horizon === 'number' && Number.isFinite(input.horizon)) { + normalizedHorizon = Object.is(input.horizon, -0) ? 0 : input.horizon; + } else { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash horizon must be a non-empty string or finite number.' + ); + } + + if (input.params === undefined) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash params must be defined (use null or {} when empty).' + ); + } + if (input.universe === undefined) { + throw new TrialLedgerError( + 'INVALID_EXPRESSION_INPUT', + 'canonicalExpressionHash universe must be defined.' + ); + } + + const envelope = { + expression: normalizedExpression, + horizon: normalizedHorizon, + params: input.params, + sampleEnd, + sampleStart, + universe: input.universe, + }; + + const canonicalJson = canonicalizeJsonValue(envelope, '$', new Set()); + return sha256HexUtf8(canonicalJson); +} + +/** + * Pure validator and moment builder for a single `trial_ledger` row. + * + * Enforces the exclusive Vault holdout fence (`sampleEnd < vaultCutoffDate`) via + * {@link applyVaultFence} and computes `{ nObs, sharpeUnann, skewness, kurtosis }` + * via {@link trialMoments} from `@stock-bot/calculations`. + */ +export function buildTrialRow(input: TrialRowInput): BuiltTrialRow { + if (typeof input !== 'object' || input === null) { + throw new TrialLedgerError('INVALID_ROW', 'buildTrialRow input must be a non-null object.'); + } + + const principalId = validatePrincipalId(input.principalId); + const campaignId = validateOptionalUuid(input.campaignId, 'campaignId'); + const hypothesisId = validateOptionalUuid(input.hypothesisId, 'hypothesisId'); + const stage = validateStage(input.stage); + const universeMarket = validateUniverseMarket(input.universeMarket); + const horizonBucket = validateHorizonBucket(input.horizonBucket); + const expressionHash = validateExpressionHash(input.expressionHash); + const { sampleStart, sampleEnd, vaultCutoffDate } = validateSampleWindowFenced( + input.sampleStart, + input.sampleEnd, + input.vaultCutoffDate + ); + const dailySeries = validateDailySeries(input.dailySeries); + + const dailyRiskFree = input.dailyRiskFree ?? 0; + if (typeof dailyRiskFree !== 'number' || !Number.isFinite(dailyRiskFree)) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Invalid dailyRiskFree "${String(input.dailyRiskFree)}": expected a finite number.` + ); + } + + const moments = trialMoments(dailySeries, dailyRiskFree); + if (moments === null) { + throw new TrialLedgerError( + 'ZERO_VARIANCE_SERIES', + 'dailySeries has zero variance or degenerate moments (trialMoments returned null).' + ); + } + + return Object.freeze({ + principalId, + campaignId, + hypothesisId, + stage, + universeMarket, + horizonBucket, + expressionHash, + sampleStart, + sampleEnd, + vaultCutoffDate, + dailyRiskFree, + nObs: moments.nObs, + sharpeUnann: moments.sharpeUnann, + skewness: moments.skewness, + kurtosis: moments.kurtosis, + dailySeries: Object.freeze(dailySeries), + }); +} + +/** + * Atomically appends one or more validated rows to `trial_ledger` in a single + * parameterised multi-row `INSERT ... RETURNING trial_id, created_at`. + * + * All rows are validated upfront before any SQL is sent. + */ +export async function recordTrials( + executor: TrialLedgerExecutor, + rows: readonly (TrialRowInput | BuiltTrialRow)[] +): Promise { + assertExecutor(executor); + + if (!Array.isArray(rows)) { + throw new TrialLedgerError('INVALID_ROW', 'recordTrials rows must be an array.'); + } + if (rows.length === 0) { + return []; + } + if (rows.length > MAX_TRIAL_BATCH_SIZE) { + throw new TrialLedgerError( + 'BATCH_TOO_LARGE', + `Batch size ${rows.length} exceeds MAX_TRIAL_BATCH_SIZE (${MAX_TRIAL_BATCH_SIZE}).` + ); + } + + const validated: BuiltTrialRow[] = new Array(rows.length); + for (let i = 0; i < rows.length; i += 1) { + validated[i] = validateRowForInsert(rows[i] as TrialRowInput | BuiltTrialRow, i); + } + + const valueTuples: string[] = new Array(validated.length); + const params: unknown[] = new Array(validated.length * COLUMNS_PER_ROW); + + for (let i = 0; i < validated.length; i += 1) { + const row = validated[i] as BuiltTrialRow; + const base = i * COLUMNS_PER_ROW; + const p = base + 1; + valueTuples[i] = + `($${p}, $${p + 1}, $${p + 2}, $${p + 3}, $${p + 4}, $${p + 5}, $${p + 6}, $${p + 7}, $${p + 8}, $${p + 9}, $${p + 10}::double precision, $${p + 11}::double precision, $${p + 12}::double precision, $${p + 13}::real[])`; + + params[base] = row.principalId; + params[base + 1] = row.campaignId; + params[base + 2] = row.stage; + params[base + 3] = row.universeMarket; + params[base + 4] = row.horizonBucket; + params[base + 5] = row.hypothesisId; + params[base + 6] = row.expressionHash; + params[base + 7] = row.sampleStart; + params[base + 8] = row.sampleEnd; + params[base + 9] = row.nObs; + params[base + 10] = row.sharpeUnann; + params[base + 11] = row.skewness; + params[base + 12] = row.kurtosis; + params[base + 13] = row.dailySeries; + } + + const sql = `INSERT INTO trial_ledger ( + principal_id, campaign_id, stage, universe_market, horizon_bucket, + hypothesis_id, expression_hash, sample_start, sample_end, n_obs, + sharpe_unann, skewness, kurtosis, daily_series +) VALUES ${valueTuples.join(', ')} +RETURNING trial_id, ${UTC_CREATED_AT_SQL}`; + + const result = await executor.query>(sql, params); + if (result.rows.length !== validated.length) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Expected ${validated.length} returned receipts from trial_ledger INSERT, got ${result.rows.length}.` + ); + } + + const receipts: RecordedTrialReceipt[] = new Array(result.rows.length); + for (let i = 0; i < result.rows.length; i += 1) { + const returned = result.rows[i] as Record; + receipts[i] = { + trialId: parseTrialId(returned.trial_id), + createdAt: formatUtcTimestamp(returned.created_at, 'created_at'), + }; + } + return receipts; +} + +/** + * Loads all trials in a `(universeMarket, horizonBucket)` relatedness cluster + * ordered by `trial_id ASC`, optionally capped at `created_at <= asOf`. + */ +export async function loadClusterTrials( + executor: TrialLedgerExecutor, + query: LoadClusterTrialsQuery +): Promise { + assertExecutor(executor); + if (typeof query !== 'object' || query === null) { + throw new TrialLedgerError('INVALID_ROW', 'loadClusterTrials query must be a non-null object.'); + } + + const universeMarket = validateUniverseMarket(query.universeMarket); + const horizonBucket = validateHorizonBucket(query.horizonBucket); + const normalizedAsOf = normalizeAsOf(query.asOf); + + const sql = + normalizedAsOf === undefined + ? `SELECT${SELECT_TRIAL_COLUMNS} +FROM trial_ledger +WHERE universe_market = $1 + AND horizon_bucket = $2 +ORDER BY trial_id ASC` + : `SELECT${SELECT_TRIAL_COLUMNS} +FROM trial_ledger +WHERE universe_market = $1 + AND horizon_bucket = $2 + AND created_at <= $3::timestamptz +ORDER BY trial_id ASC`; + + const params: readonly unknown[] = + normalizedAsOf === undefined + ? [universeMarket, horizonBucket] + : [universeMarket, horizonBucket, normalizedAsOf]; + + const result = await executor.query>(sql, params); + return result.rows.map(row => parseDbTrialRow(row)); +} + +/** + * Loads the target trial's `(universe_market, horizon_bucket)` relatedness cluster + * and computes its N-hat-deflated Sharpe Ratio via {@link effectiveIndependentTrials} + * and {@link deflatedSharpeRatio}. + */ +export async function clusterDeflatedSharpe( + executor: TrialLedgerExecutor, + query: ClusterDeflatedSharpeQuery +): Promise { + assertExecutor(executor); + if (typeof query !== 'object' || query === null) { + throw new TrialLedgerError( + 'INVALID_ROW', + 'clusterDeflatedSharpe query must be a non-null object.' + ); + } + + const trialId = parseTrialId(query.trialId); + const normalizedAsOf = normalizeAsOf(query.asOf); + const dsrGate = query.dsrGate ?? DSR_VALIDATION_GATE; + if (typeof dsrGate !== 'number' || !Number.isFinite(dsrGate)) { + throw new TrialLedgerError( + 'INVALID_ROW', + `Invalid dsrGate "${String(query.dsrGate)}": expected a finite number.` + ); + } + const sessionDates = + query.sessionDates !== undefined + ? validateSortedDates(query.sessionDates, 'sessionDates') + : undefined; + const observationDatesMap = normalizeObservationDatesMap(query.observationDatesByTrialId); + + const targetResult = await executor.query>( + `SELECT${SELECT_TRIAL_COLUMNS} +FROM trial_ledger +WHERE trial_id = $1::bigint`, + [trialId] + ); + + if (targetResult.rows.length === 0) { + throw new TrialLedgerError('TRIAL_NOT_FOUND', `Trial ${trialId} was not found in trial_ledger.`); + } + + const target = parseDbTrialRow(targetResult.rows[0] as Record); + const cluster = await loadClusterTrials(executor, { + universeMarket: target.universeMarket, + horizonBucket: target.horizonBucket, + asOf: normalizedAsOf, + }); + + const targetInCluster = cluster.find(row => row.trialId === target.trialId); + if (targetInCluster === undefined) { + throw new TrialLedgerError( + 'TRIAL_NOT_FOUND', + `Trial ${trialId} is not visible in cluster (${target.universeMarket}, ${target.horizonBucket}) as of ${normalizedAsOf ?? 'latest'}.` + ); + } + + const eff = computeClusterEffectiveTrials(cluster, sessionDates, observationDatesMap); + const clusterSharpes = cluster.map(row => row.sharpeUnann); + + const dsrResult = deflatedSharpeRatio({ + sharpeUnann: targetInCluster.sharpeUnann, + nObs: targetInCluster.nObs, + skewness: targetInCluster.skewness, + kurtosis: targetInCluster.kurtosis, + nHat: eff.nHat, + clusterSharpes, + }); + + const dsr = dsrResult?.dsr ?? null; + const passesGate = passesDsrGate(dsr, dsrGate); + + return { + trialId: targetInCluster.trialId, + universeMarket: targetInCluster.universeMarket, + horizonBucket: targetInCluster.horizonBucket, + clusterSize: cluster.length, + effectiveTrials: eff.nHat, + meanCorrelation: eff.meanCorrelation, + pairsUsed: eff.pairsUsed, + pairsSkipped: eff.pairsSkipped, + sr0: dsrResult?.sr0 ?? null, + standardError: dsrResult?.standardError ?? null, + dsr, + passesGate, + }; +} diff --git a/libs/research/test/market-data-store.qa.test.ts b/libs/research/test/market-data-store.qa.test.ts new file mode 100644 index 00000000..0aa7d01a --- /dev/null +++ b/libs/research/test/market-data-store.qa.test.ts @@ -0,0 +1,479 @@ +import { describe, expect, it } from 'bun:test'; +import { + applyVaultFence, + computeVaultCutoffTs, + MarketDataStoreValidationError, + resolveDuckDbConnectionBudget, + VaultHoldoutFenceError, + VaultScopeNotAuthorizedError, + type VaultFenceQuery, +} from '@stock-bot/research'; + +const DAY_MS = 86_400_000; + +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 captureError(fn: () => unknown): unknown { + try { + fn(); + } catch (err) { + return err; + } + return undefined; +} + +describe('computeVaultCutoffTs edge cases', () => { + it('clamps 31st to 30-day target months and wraps December/March correctly', () => { + expect(computeVaultCutoffTs('2026-03-31')).toBe(Date.UTC(2025, 8, 30)); + expect(computeVaultCutoffTs('2026-12-31')).toBe(Date.UTC(2026, 5, 30)); + expect(computeVaultCutoffTs('2026-07-31')).toBe(Date.UTC(2026, 0, 31)); + }); + + it('applies Gregorian century leap rules (2000 leap, 2100 not)', () => { + expect(computeVaultCutoffTs('2000-08-30')).toBe(Date.UTC(2000, 1, 29)); + expect(computeVaultCutoffTs('2100-08-31')).toBe(Date.UTC(2100, 1, 28)); + }); + + it('normalizes offset input to UTC before subtracting months', () => { + // 2026-08-31T01:00+02:00 is 2026-08-30T23:00Z -> Feb has no 30th -> 2026-02-28T23:00Z. + expect(computeVaultCutoffTs('2026-08-31T01:00:00+02:00')).toBe( + Date.UTC(2026, 1, 28, 23, 0, 0, 0) + ); + }); + + it('handles pre-1970 instants and the 0..99 two-digit-year range without offsetting to 19xx', () => { + expect(computeVaultCutoffTs('1969-12-31T12:00:00Z')).toBe(Date.UTC(1969, 5, 30, 12)); + const expected = new Date(0); + expected.setUTCFullYear(49, 6, 15); + expected.setUTCHours(0, 0, 0, 0); + expect(computeVaultCutoffTs('0050-01-15')).toBe(expected.getTime()); + }); + + it('throws the typed error when the result would fall outside the ECMAScript range', () => { + expect(() => computeVaultCutoffTs(-8_640_000_000_000_000)).toThrow( + MarketDataStoreValidationError + ); + expect(() => computeVaultCutoffTs(8_640_000_000_000_001)).toThrow( + MarketDataStoreValidationError + ); + }); + + it('rejects non-number/string/Date inputs at runtime', () => { + for (const bad of [null, undefined, {}, [], true] as unknown[]) { + expect(() => computeVaultCutoffTs(bad as number)).toThrow(MarketDataStoreValidationError); + } + }); + + it('carries the offending field name on validation errors', () => { + const err = captureError(() => computeVaultCutoffTs('nope')); + expect(err).toBeInstanceOf(MarketDataStoreValidationError); + expect(err).toBeInstanceOf(Error); + expect((err as MarketDataStoreValidationError).field).toBe('maxIngestedTs'); + expect((err as MarketDataStoreValidationError).name).toBe('MarketDataStoreValidationError'); + }); +}); + +describe('applyVaultFence strict timestamp parsing', () => { + const cutoffMs = Date.UTC(2026, 4, 28); + const ctx = { vaultCutoffTs: cutoffMs }; + + it.each([ + ['lowercase z suffix', '2026-01-01T00:00:00z'], + ['space separator', '2026-01-01 00:00:00Z'], + ['hour 24', '2026-01-01T24:00:00Z'], + ['leap second', '2026-01-01T23:59:60Z'], + ['minute 60', '2026-01-01T00:60:00Z'], + ['offset hour 24', '2026-01-01T00:00:00+24:00'], + ['offset minute 60', '2026-01-01T00:00:00+05:60'], + ['compact offset', '2026-01-01T00:00:00+0500'], + ['missing seconds', '2026-01-01T00:00Z'], + ['empty fraction', '2026-01-01T00:00:00.Z'], + ['month 13', '2026-13-01'], + ['month 00', '2026-00-10'], + ['day 00', '2026-01-00'], + ['1900-02-29 (not leap)', '1900-02-29'], + ['expanded year', '+2026-01-01'], + ['leading whitespace', ' 2026-01-01'], + ['trailing whitespace', '2026-01-01 '], + ['trailing newline', '2026-01-01\n'], + ['epoch digits as string', '1767225600000'], + ])('rejects %s in from', (_label, from) => { + const err = captureError(() => applyVaultFence({ from, to: '2026-02-01' }, ctx)); + expect(err).toBeInstanceOf(MarketDataStoreValidationError); + expect((err as MarketDataStoreValidationError).field).toBe('from'); + }); + + it('accepts 2000-02-29 and treats -00:00 / +00:00 as UTC', () => { + expect( + applyVaultFence({ from: '2000-02-29', to: '2000-02-29T12:00:00+00:00' }, ctx) + ).toMatchObject({ fromMs: Date.UTC(2000, 1, 29), toMs: Date.UTC(2000, 1, 29, 12) }); + expect( + applyVaultFence({ from: '2026-01-01T00:00:00-00:00', to: '2026-01-02' }, ctx).fromMs + ).toBe(Date.UTC(2026, 0, 1)); + }); + + it('rejects non-string timestamps passed through untyped callers', () => { + for (const bad of [123, null, {}] as unknown[]) { + const q = { from: bad, to: '2026-02-01' } as unknown as VaultFenceQuery; + expect(() => applyVaultFence(q, ctx)).toThrow(MarketDataStoreValidationError); + } + }); + + it('allows a zero-width range (from === to as instants)', () => { + const r = applyVaultFence({ from: '2026-01-01T10:00:00Z', to: '2026-01-01T10:00:00Z' }, ctx); + expect(r.fromMs).toBe(r.toMs); + }); +}); + +describe('applyVaultFence boundary semantics', () => { + it('fences on the UTC instant, not the literal string, when offsets are used', () => { + const cutoffMs = Date.UTC(2026, 4, 28); + // 2026-05-27T23:00-01:00 === 2026-05-28T00:00Z === cutoff -> must be fenced. + const err = captureError(() => + applyVaultFence( + { from: '2026-05-27T23:00:00-01:00', to: '2026-06-01' }, + { vaultCutoffTs: cutoffMs } + ) + ); + expect(err).toBeInstanceOf(VaultHoldoutFenceError); + expect((err as VaultHoldoutFenceError).fromMs).toBe(cutoffMs); + // One millisecond earlier is allowed and to is clamped. + const ok = applyVaultFence( + { from: '2026-05-27T22:59:59.999-01:00', to: '2026-06-01' }, + { vaultCutoffTs: cutoffMs } + ); + expect(ok.fromMs).toBe(cutoffMs - 1); + expect(ok.toMs).toBe(cutoffMs - 1); + expect(ok.clampedTo).toBe(true); + }); + + it('does not clamp to/asOf at exactly cutoffMs - 1', () => { + const cutoffMs = Date.UTC(2026, 4, 28); + const r = applyVaultFence( + { from: '2026-05-01', to: '2026-05-27', asOf: '2026-05-27T23:59:59.999Z' }, + { vaultCutoffTs: cutoffMs } + ); + expect(r).toMatchObject({ + toMs: cutoffMs - 1, + asOfMs: cutoffMs - 1, + clampedTo: false, + clampedAsOf: false, + }); + }); + + it('allows a date-only from on the cutoff day when the cutoff has a non-midnight time', () => { + const cutoffMs = Date.UTC(2026, 4, 28, 12, 0, 0, 0); + const r = applyVaultFence( + { from: '2026-05-28', to: '2026-05-28' }, + { vaultCutoffTs: cutoffMs } + ); + expect(r.fromMs).toBe(Date.UTC(2026, 4, 28)); + expect(r.toMs).toBe(cutoffMs - 1); + expect(r.clampedTo).toBe(true); + expect(r.asOfMs).toBe(cutoffMs - 1); + }); + + it('keeps an asOf earlier than from untouched (point-in-time look-back)', () => { + const cutoffMs = Date.UTC(2026, 4, 28); + const r = applyVaultFence( + { from: '2026-03-01', to: '2026-04-01', asOf: '2026-01-15' }, + { vaultCutoffTs: cutoffMs } + ); + expect(r.asOfMs).toBe(Date.UTC(2026, 0, 15, 23, 59, 59, 999)); + expect(r.clampedAsOf).toBe(false); + }); + + it('still fences and clamps vault_fenced queries even when the operator flag is true', () => { + const cutoffMs = Date.UTC(2026, 4, 28); + const authCtx = { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: true }; + expect(() => applyVaultFence({ from: '2026-06-01', to: '2026-07-01' }, authCtx)).toThrow( + VaultHoldoutFenceError + ); + const r = applyVaultFence({ from: '2026-01-01', to: '2026-11-28' }, authCtx); + expect(r.toMs).toBe(cutoffMs - 1); + expect(r.asOfMs).toBe(cutoffMs - 1); + expect(r.scope).toBe('vault_fenced'); + }); + + it('reports from > to as a validation error even when both bounds are inside the Vault', () => { + const err = captureError(() => + applyVaultFence( + { from: '2026-10-02', to: '2026-10-01' }, + { vaultCutoffTs: Date.UTC(2026, 4, 28) } + ) + ); + expect(err).toBeInstanceOf(MarketDataStoreValidationError); + expect(err).not.toBeInstanceOf(VaultHoldoutFenceError); + }); + + it('does not mutate the query or context objects', () => { + const query = Object.freeze({ from: '2026-01-01', to: '2026-11-28', asOf: '2026-11-28' }); + const ctx = Object.freeze({ vaultCutoffTs: Date.UTC(2026, 4, 28) }); + applyVaultFence(query, ctx); + expect(query).toEqual({ from: '2026-01-01', to: '2026-11-28', asOf: '2026-11-28' }); + }); + + it('rejects the minimum representable cutoff since cutoff - 1 would be unrepresentable', () => { + expect(() => + applyVaultFence( + { from: '2026-01-01', to: '2026-02-01' }, + { vaultCutoffTs: -8_640_000_000_000_000 } + ) + ).toThrow(MarketDataStoreValidationError); + }); +}); + +describe('applyVaultFence vault_evaluation_only authorization', () => { + const cutoffMs = Date.UTC(2026, 4, 28); + + it('fails closed for truthy-but-not-true authorization values', () => { + for (const flag of [1, 'true', {}, 'yes'] as unknown[]) { + const ctx = { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: flag as boolean }; + const err = captureError(() => + applyVaultFence( + { from: '2026-06-01', to: '2026-07-01', scope: 'vault_evaluation_only' }, + ctx + ) + ); + expect(err).toBeInstanceOf(VaultScopeNotAuthorizedError); + expect((err as Error).name).toBe('VaultScopeNotAuthorizedError'); + } + }); + + it('fails closed before parsing, so a bad timestamp never leaks past authorization', () => { + const err = captureError(() => + applyVaultFence( + { from: 'garbage', to: 'garbage', scope: 'vault_evaluation_only' }, + { vaultCutoffTs: cutoffMs } + ) + ); + expect(err).toBeInstanceOf(VaultScopeNotAuthorizedError); + }); + + it('still validates timestamps and ordering when authorized', () => { + const ctx = { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: true }; + expect(() => + applyVaultFence({ from: 'bad', to: '2026-07-01', scope: 'vault_evaluation_only' }, ctx) + ).toThrow(MarketDataStoreValidationError); + expect(() => + applyVaultFence({ from: '2026-08-01', to: '2026-07-01', scope: 'vault_evaluation_only' }, ctx) + ).toThrow(MarketDataStoreValidationError); + }); + + it('keeps an explicit asOf past the cutoff unclamped when authorized', () => { + const r = applyVaultFence( + { + from: '2026-01-01', + to: '2026-11-01', + asOf: '2026-11-27T10:00:00Z', + scope: 'vault_evaluation_only', + }, + { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: true } + ); + expect(r).toEqual({ + fromMs: Date.UTC(2026, 0, 1), + toMs: Date.UTC(2026, 10, 1, 23, 59, 59, 999), + asOfMs: Date.UTC(2026, 10, 27, 10), + scope: 'vault_evaluation_only', + clampedTo: false, + clampedAsOf: false, + }); + }); +}); + +describe('applyVaultFence seeded oracle (exact expected outcome per tuple)', () => { + // Independent oracle: each tuple is generated from integer epoch-ms, so the + // expected normalized bounds are computed directly instead of by re-parsing. + it('matches the oracle on 2,000 seeded tuples', () => { + const rng = createSeededRng(0x0a11_7e57); + const baseMs = Date.UTC(2019, 0, 1); + const spanMs = 9 * 365 * DAY_MS; + const counts = { ok: 0, fence: 0, order: 0, clampedTo: 0, clampedAsOf: 0 }; + + type Bound = { str: string; startMs: number; endMs: number }; + const makeBound = (ms: number): Bound => { + if (rng() < 0.4) { + const dayStart = Math.floor(ms / DAY_MS) * DAY_MS; + return { + str: new Date(dayStart).toISOString().slice(0, 10), + startMs: dayStart, + endMs: dayStart + DAY_MS - 1, + }; + } + if (rng() < 0.5) { + // Express the same instant with a non-UTC offset (+/- up to 14h, whole minutes). + const offsetMin = Math.floor((rng() - 0.5) * 2 * 14 * 60); + const local = new Date(ms + offsetMin * 60_000).toISOString().slice(0, 23); + const sign = offsetMin < 0 ? '-' : '+'; + const abs = Math.abs(offsetMin); + const hh = String(Math.floor(abs / 60)).padStart(2, '0'); + const mm = String(abs % 60).padStart(2, '0'); + return { str: `${local}${sign}${hh}:${mm}`, startMs: ms, endMs: ms }; + } + return { str: new Date(ms).toISOString(), startMs: ms, endMs: ms }; + }; + + for (let i = 0; i < 2_000; i += 1) { + // Cutoffs include midnight-aligned values so date-only bounds hit it exactly. + const rawCutoff = baseMs + Math.floor(rng() * spanMs); + const cutoffMs = i % 3 === 0 ? Math.floor(rawCutoff / DAY_MS) * DAY_MS : rawCutoff; + const pick = (): number => { + const mode = Math.floor(rng() * 4); + if (mode === 0) { + return cutoffMs; + } + if (mode === 1) { + return cutoffMs - 1; + } + return cutoffMs + Math.floor((rng() - 0.55) * 300 * DAY_MS); + }; + const from = makeBound(pick()); + const to = makeBound(pick()); + const asOf = i % 3 === 0 ? undefined : makeBound(pick()); + + const fromMs = from.startMs; + const toMs = to.endMs; + const act = () => + applyVaultFence( + { from: from.str, to: to.str, asOf: asOf?.str }, + { vaultCutoffTs: cutoffMs } + ); + + if (fromMs > toMs) { + expect(captureError(act)).toBeInstanceOf(MarketDataStoreValidationError); + counts.order += 1; + continue; + } + if (fromMs >= cutoffMs) { + const err = captureError(act); + expect(err).toBeInstanceOf(VaultHoldoutFenceError); + expect((err as VaultHoldoutFenceError).fromMs).toBe(fromMs); + counts.fence += 1; + continue; + } + const expectedClampedTo = toMs >= cutoffMs; + const expectedClampedAsOf = asOf !== undefined && asOf.endMs >= cutoffMs; + const expectedAsOfMs = asOf === undefined || expectedClampedAsOf ? cutoffMs - 1 : asOf.endMs; + expect(act()).toEqual({ + fromMs, + toMs: expectedClampedTo ? cutoffMs - 1 : toMs, + asOfMs: expectedAsOfMs, + scope: 'vault_fenced', + clampedTo: expectedClampedTo, + clampedAsOf: expectedClampedAsOf, + }); + counts.ok += 1; + counts.clampedTo += expectedClampedTo ? 1 : 0; + counts.clampedAsOf += expectedClampedAsOf ? 1 : 0; + } + + // Coverage guard: every branch must be exercised by the seeded corpus. + expect(counts.ok).toBeGreaterThan(200); + expect(counts.fence).toBeGreaterThan(200); + expect(counts.order).toBeGreaterThan(100); + expect(counts.clampedTo).toBeGreaterThan(50); + expect(counts.clampedAsOf).toBeGreaterThan(50); + }); +}); + +describe('resolveDuckDbConnectionBudget edge cases', () => { + it('treats explicitly undefined env entries as unset and uses defaults', () => { + const budget = resolveDuckDbConnectionBudget({ + STOCKBOT_DUCKDB_MEMORY_LIMIT: undefined, + STOCKBOT_DUCKDB_THREADS: undefined, + STOCKBOT_DUCKDB_TEMP_DIRECTORY: undefined, + }); + expect(budget.statements).toEqual([ + "SET memory_limit = '6GB';", + 'SET threads = 4;', + "SET temp_directory = '/mnt/data/stockbot/tmp/duckdb';", + ]); + }); + + it('reads process.env when env is omitted', () => { + const keys = [ + 'STOCKBOT_DUCKDB_MEMORY_LIMIT', + 'STOCKBOT_DUCKDB_THREADS', + 'STOCKBOT_DUCKDB_TEMP_DIRECTORY', + ] as const; + const saved = keys.map(k => process.env[k]); + try { + process.env.STOCKBOT_DUCKDB_MEMORY_LIMIT = '3GB'; + process.env.STOCKBOT_DUCKDB_THREADS = '3'; + process.env.STOCKBOT_DUCKDB_TEMP_DIRECTORY = '/var/tmp/qa-duckdb'; + expect(resolveDuckDbConnectionBudget().statements).toEqual([ + "SET memory_limit = '3GB';", + 'SET threads = 3;', + "SET temp_directory = '/var/tmp/qa-duckdb';", + ]); + process.env.STOCKBOT_DUCKDB_THREADS = '0'; + expect(() => resolveDuckDbConnectionBudget()).toThrow(MarketDataStoreValidationError); + } finally { + keys.forEach((k, idx) => { + const prev = saved[idx]; + if (prev === undefined) { + delete process.env[k]; + } else { + process.env[k] = prev; + } + }); + } + }); + + it.each(['.5GB', '1.GB', '1.5.5GB', ' 2GB', '2GB ', '2GB\n', '+2GB', '-2GB', '2KB', '2Gb', '2'])( + 'rejects memory limit %p', + value => { + const err = captureError(() => + resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_MEMORY_LIMIT: value }) + ); + expect(err).toBeInstanceOf(MarketDataStoreValidationError); + expect((err as MarketDataStoreValidationError).field).toBe('STOCKBOT_DUCKDB_MEMORY_LIMIT'); + } + ); + + it.each([' 4', '4 ', '4\n', '+4', '1e1', '0x4', '999999999999999999999'])( + 'rejects threads %p', + value => { + const err = captureError(() => + resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_THREADS: value }) + ); + expect(err).toBeInstanceOf(MarketDataStoreValidationError); + expect((err as MarketDataStoreValidationError).field).toBe('STOCKBOT_DUCKDB_THREADS'); + } + ); + + it.each(['/tmp/a\tb', '/tmp/a\x7fb', '/tmp/a\x1bb', "/tmp/x';SET threads = 64;--"])( + 'rejects temp directory %p', + value => { + const err = captureError(() => + resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_TEMP_DIRECTORY: value }) + ); + expect(err).toBeInstanceOf(MarketDataStoreValidationError); + expect((err as MarketDataStoreValidationError).field).toBe('STOCKBOT_DUCKDB_TEMP_DIRECTORY'); + } + ); + + it('fails on any one invalid field instead of returning a partial budget', () => { + expect(() => + resolveDuckDbConnectionBudget({ + STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCKBOT_DUCKDB_THREADS: '2', + STOCKBOT_DUCKDB_TEMP_DIRECTORY: 'tmp', + }) + ).toThrow(MarketDataStoreValidationError); + }); + + it('returns a fresh statements array per call', () => { + const a = resolveDuckDbConnectionBudget({}); + a.statements.push('SET threads = 64;'); + expect(resolveDuckDbConnectionBudget({}).statements).toHaveLength(3); + }); +}); diff --git a/libs/research/test/market-data-store.test.ts b/libs/research/test/market-data-store.test.ts new file mode 100644 index 00000000..36378423 --- /dev/null +++ b/libs/research/test/market-data-store.test.ts @@ -0,0 +1,447 @@ +import { describe, expect, it } from 'bun:test'; +import { + applyVaultFence, + computeVaultCutoffTs, + DEFAULT_DUCKDB_MEMORY_LIMIT, + DEFAULT_DUCKDB_TEMP_DIRECTORY, + DEFAULT_DUCKDB_THREADS, + MarketDataStoreValidationError, + resolveDuckDbConnectionBudget, + VaultHoldoutFenceError, + VaultScopeNotAuthorizedError, +} from '@stock-bot/research'; +import { + applyVaultFence as subpathApplyVaultFence, + computeVaultCutoffTs as subpathComputeVaultCutoffTs, + resolveDuckDbConnectionBudget as subpathResolveDuckDbConnectionBudget, +} from '@stock-bot/research/market-data-store'; + +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 formatUtcDateOnly(epochMs: number): string { + return new Date(epochMs).toISOString().slice(0, 10); +} + +describe('market-data-store exports', () => { + it('exposes identical runtime functions from package root and subpath', () => { + expect(computeVaultCutoffTs).toBe(subpathComputeVaultCutoffTs); + expect(applyVaultFence).toBe(subpathApplyVaultFence); + expect(resolveDuckDbConnectionBudget).toBe(subpathResolveDuckDbConnectionBudget); + }); +}); + +describe('computeVaultCutoffTs', () => { + it('subtracts 6 calendar months in UTC for standard dates', () => { + expect(computeVaultCutoffTs('2026-11-28T00:00:00Z')).toBe(Date.UTC(2026, 4, 28, 0, 0, 0, 0)); + expect(computeVaultCutoffTs('2026-11-28')).toBe(Date.UTC(2026, 4, 28, 0, 0, 0, 0)); + }); + + it('clamps month-end dates to the last day of the target month, including leap years', () => { + expect(computeVaultCutoffTs('2026-08-31')).toBe(Date.UTC(2026, 1, 28, 0, 0, 0, 0)); + expect(computeVaultCutoffTs('2024-08-31')).toBe(Date.UTC(2024, 1, 29, 0, 0, 0, 0)); + expect(computeVaultCutoffTs('2026-10-31')).toBe(Date.UTC(2026, 3, 30, 0, 0, 0, 0)); + }); + + it('crosses year boundaries correctly', () => { + expect(computeVaultCutoffTs('2026-01-15')).toBe(Date.UTC(2025, 6, 15, 0, 0, 0, 0)); + expect(computeVaultCutoffTs('2026-06-30')).toBe(Date.UTC(2025, 11, 30, 0, 0, 0, 0)); + }); + + it('preserves exact UTC time-of-day across month-end clamping', () => { + expect(computeVaultCutoffTs('2026-08-31T14:35:22.789Z')).toBe( + Date.UTC(2026, 1, 28, 14, 35, 22, 789) + ); + }); + + it('accepts integer epoch-ms numbers and valid Date instances', () => { + const inputMs = Date.UTC(2026, 10, 28, 13, 45, 59, 123); + const expectedMs = Date.UTC(2026, 4, 28, 13, 45, 59, 123); + expect(computeVaultCutoffTs(inputMs)).toBe(expectedMs); + expect(computeVaultCutoffTs(new Date(inputMs))).toBe(expectedMs); + }); + + it('rejects invalid, non-finite, non-integer, and naive inputs with MarketDataStoreValidationError', () => { + const invalidInputs: Array = [ + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + Date.UTC(2026, 4, 28) + 0.5, + '', + 'not-a-date', + '2026-02-29', + '2026-05-01T12:00:00', + new Date('invalid'), + ]; + + for (const input of invalidInputs) { + expect(() => computeVaultCutoffTs(input)).toThrow(MarketDataStoreValidationError); + } + }); +}); + +describe('applyVaultFence', () => { + const cutoffMs = Date.UTC(2026, 4, 28, 0, 0, 0, 0); + + it('defaults omitted scope to vault_fenced and passes fully pre-cutoff queries unclamped', () => { + const result = applyVaultFence( + { + from: '2025-01-01T00:00:00Z', + to: '2026-05-27T23:59:59.999Z', + asOf: '2026-05-27T23:59:59.999Z', + }, + { vaultCutoffTs: cutoffMs } + ); + + expect(result).toEqual({ + fromMs: Date.UTC(2025, 0, 1, 0, 0, 0, 0), + toMs: cutoffMs - 1, + asOfMs: cutoffMs - 1, + scope: 'vault_fenced', + clampedTo: false, + clampedAsOf: false, + }); + }); + + it('throws VaultHoldoutFenceError when from >= cutoff (strictly greater or equal)', () => { + for (const from of ['2026-05-28T00:00:00Z', '2026-05-28', '2026-06-01T00:00:00Z']) { + let caught: unknown; + try { + applyVaultFence({ from, to: '2026-07-01T00:00:00Z' }, { vaultCutoffTs: cutoffMs }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(VaultHoldoutFenceError); + const fenceErr = caught as VaultHoldoutFenceError; + expect(fenceErr.from).toBe(from); + expect(fenceErr.vaultCutoffTs).toBe(cutoffMs); + expect(fenceErr.fromMs).toBeGreaterThanOrEqual(cutoffMs); + } + }); + + it('clamps to >= cutoff and asOf >= cutoff to cutoffMs - 1', () => { + const atCutoff = applyVaultFence( + { + from: '2026-01-01T00:00:00Z', + to: '2026-05-28T00:00:00Z', + asOf: '2026-05-28T00:00:00Z', + }, + { vaultCutoffTs: cutoffMs } + ); + expect(atCutoff.toMs).toBe(cutoffMs - 1); + expect(atCutoff.asOfMs).toBe(cutoffMs - 1); + expect(atCutoff.clampedTo).toBe(true); + expect(atCutoff.clampedAsOf).toBe(true); + + const pastCutoff = applyVaultFence( + { + from: '2026-01-01', + to: '2026-11-28', + asOf: '2026-11-28', + }, + { vaultCutoffTs: cutoffMs } + ); + expect(pastCutoff.toMs).toBe(cutoffMs - 1); + expect(pastCutoff.asOfMs).toBe(cutoffMs - 1); + expect(pastCutoff.clampedTo).toBe(true); + expect(pastCutoff.clampedAsOf).toBe(true); + }); + + it('defaults omitted asOf in vault_fenced scope to cutoffMs - 1 with clampedAsOf=false', () => { + const result = applyVaultFence( + { + from: '2026-01-01', + to: '2026-03-01', + }, + { vaultCutoffTs: cutoffMs } + ); + expect(result.asOfMs).toBe(cutoffMs - 1); + expect(result.clampedTo).toBe(false); + expect(result.clampedAsOf).toBe(false); + }); + + it('fails closed on vault_evaluation_only unless vaultOperatorAuthorized is true', () => { + expect(() => + applyVaultFence( + { + from: '2026-05-28', + to: '2026-11-28', + scope: 'vault_evaluation_only', + }, + { vaultCutoffTs: cutoffMs } + ) + ).toThrow(VaultScopeNotAuthorizedError); + + expect(() => + applyVaultFence( + { + from: '2026-05-28', + to: '2026-11-28', + scope: 'vault_evaluation_only', + }, + { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: false } + ) + ).toThrow(VaultScopeNotAuthorizedError); + + const authorized = applyVaultFence( + { + from: '2026-05-28', + to: '2026-11-28', + scope: 'vault_evaluation_only', + }, + { vaultCutoffTs: cutoffMs, vaultOperatorAuthorized: true } + ); + expect(authorized).toEqual({ + fromMs: Date.UTC(2026, 4, 28, 0, 0, 0, 0), + toMs: Date.UTC(2026, 10, 28, 23, 59, 59, 999), + asOfMs: Date.UTC(2026, 10, 28, 23, 59, 59, 999), + scope: 'vault_evaluation_only', + clampedTo: false, + clampedAsOf: false, + }); + }); + + it('expands date-only from to 00:00:00.000Z and date-only to/asOf to 23:59:59.999Z', () => { + const result = applyVaultFence( + { + from: '2026-03-10', + to: '2026-03-10', + asOf: '2026-03-10', + }, + { vaultCutoffTs: cutoffMs } + ); + expect(result.fromMs).toBe(Date.UTC(2026, 2, 10, 0, 0, 0, 0)); + expect(result.toMs).toBe(Date.UTC(2026, 2, 10, 23, 59, 59, 999)); + expect(result.asOfMs).toBe(Date.UTC(2026, 2, 10, 23, 59, 59, 999)); + }); + + it('normalizes explicit UTC offsets and truncates sub-millisecond fractions to integer ms', () => { + const result = applyVaultFence( + { + from: '2026-03-10T08:00:00.987654-04:00', + to: '2026-03-10T18:30:00.1+05:30', + }, + { vaultCutoffTs: cutoffMs } + ); + expect(result.fromMs).toBe(Date.UTC(2026, 2, 10, 12, 0, 0, 987)); + expect(result.toMs).toBe(Date.UTC(2026, 2, 10, 13, 0, 0, 100)); + }); + + it('rejects unknown scope, malformed timestamps, from > to, and non-finite cutoffs', () => { + expect(() => + applyVaultFence( + { + from: '2026-01-01', + to: '2026-02-01', + scope: 'unrestricted' as never, + }, + { vaultCutoffTs: cutoffMs } + ) + ).toThrow(MarketDataStoreValidationError); + + const invalidQueries = [ + { from: 'bad-date', to: '2026-02-01' }, + { from: '2026-01-01', to: 'bad-date' }, + { from: '2026-01-01', to: '2026-02-01', asOf: 'bad-date' }, + { from: '2026-01-01', to: '2026-02-01', asOf: '' }, + { from: '2026-01-01T00:00:00', to: '2026-02-01' }, + { from: '2026-02-30', to: '2026-03-01' }, + { from: '2026-04-01', to: '2026-03-01' }, + { from: '2026-09-01', to: '2026-08-01' }, + ]; + for (const q of invalidQueries) { + expect(() => applyVaultFence(q, { vaultCutoffTs: cutoffMs })).toThrow( + MarketDataStoreValidationError + ); + } + + for (const badCutoff of [ + Number.NaN, + Number.POSITIVE_INFINITY, + Number.NEGATIVE_INFINITY, + cutoffMs + 0.25, + ]) { + expect(() => + applyVaultFence({ from: '2026-01-01', to: '2026-02-01' }, { vaultCutoffTs: badCutoff }) + ).toThrow(MarketDataStoreValidationError); + } + }); + + it('produces identical epoch-ms results under TZ=America/Toronto and TZ=UTC', () => { + const previousTz = process.env.TZ; + try { + process.env.TZ = 'UTC'; + const utcCutoff = computeVaultCutoffTs('2026-08-31T23:30:00.500Z'); + const utcFenced = applyVaultFence( + { from: '2026-01-01', to: '2026-03-15', asOf: '2026-02-28' }, + { vaultCutoffTs: utcCutoff } + ); + + process.env.TZ = 'America/Toronto'; + const torontoCutoff = computeVaultCutoffTs('2026-08-31T23:30:00.500Z'); + const torontoFenced = applyVaultFence( + { from: '2026-01-01', to: '2026-03-15', asOf: '2026-02-28' }, + { vaultCutoffTs: torontoCutoff } + ); + + expect(torontoCutoff).toBe(utcCutoff); + expect(torontoFenced).toEqual(utcFenced); + } finally { + if (previousTz === undefined) { + delete process.env.TZ; + } else { + process.env.TZ = previousTz; + } + } + }); + + it('enforces fromMs <= toMs < cutoffMs and asOfMs < cutoffMs across 1,500 seeded random cases', () => { + const rng = createSeededRng(0x5eed1234); + const baseMs = Date.UTC(2020, 0, 1, 0, 0, 0, 0); + const spanMs = 8 * 365 * 86_400_000; + let passedCount = 0; + let fenceErrorCount = 0; + let validationErrorCount = 0; + + for (let i = 0; i < 1_500; i += 1) { + const randCutoff = baseMs + Math.floor(rng() * spanMs); + const bucket = i % 5; + const offsetFrom = + bucket === 0 + ? -Math.floor(rng() * 180 * 86_400_000) - 1 + : bucket === 1 + ? 0 + : Math.floor((rng() - 0.5) * 360 * 86_400_000); + const offsetTo = Math.floor((rng() - 0.3) * 360 * 86_400_000); + const rawFromMs = randCutoff + offsetFrom; + const rawToMs = randCutoff + offsetTo; + + const useDateOnlyFrom = rng() < 0.35; + const useDateOnlyTo = rng() < 0.35; + const fromStr = useDateOnlyFrom + ? formatUtcDateOnly(rawFromMs) + : new Date(rawFromMs).toISOString(); + const toStr = useDateOnlyTo ? formatUtcDateOnly(rawToMs) : new Date(rawToMs).toISOString(); + + const asOfMode = i % 4; + let asOfStr: string | undefined; + if (asOfMode === 1) { + const rawAsOfMs = randCutoff + Math.floor((rng() - 0.5) * 360 * 86_400_000); + asOfStr = new Date(rawAsOfMs).toISOString(); + } else if (asOfMode === 2) { + const rawAsOfMs = randCutoff + Math.floor((rng() - 0.5) * 360 * 86_400_000); + asOfStr = formatUtcDateOnly(rawAsOfMs); + } else if (asOfMode === 3) { + asOfStr = new Date(randCutoff).toISOString(); + } + + try { + const fenced = applyVaultFence( + { from: fromStr, to: toStr, asOf: asOfStr }, + { vaultCutoffTs: randCutoff } + ); + expect(fenced.scope).toBe('vault_fenced'); + expect(fenced.fromMs).toBeLessThanOrEqual(fenced.toMs); + expect(fenced.toMs).toBeLessThan(randCutoff); + expect(fenced.asOfMs).toBeLessThan(randCutoff); + passedCount += 1; + } catch (err) { + if (err instanceof VaultHoldoutFenceError) { + expect(err.fromMs).toBeGreaterThanOrEqual(randCutoff); + fenceErrorCount += 1; + } else if (err instanceof MarketDataStoreValidationError) { + validationErrorCount += 1; + } else { + throw err; + } + } + } + + expect(passedCount).toBeGreaterThan(200); + expect(fenceErrorCount).toBeGreaterThan(200); + expect(validationErrorCount).toBeGreaterThan(100); + }); +}); + +describe('resolveDuckDbConnectionBudget', () => { + it('returns the exact default budget and SET statements when env is empty', () => { + const budget = resolveDuckDbConnectionBudget({}); + expect(budget).toEqual({ + memoryLimit: DEFAULT_DUCKDB_MEMORY_LIMIT, + threads: DEFAULT_DUCKDB_THREADS, + tempDirectory: DEFAULT_DUCKDB_TEMP_DIRECTORY, + statements: [ + "SET memory_limit = '6GB';", + 'SET threads = 4;', + "SET temp_directory = '/mnt/data/stockbot/tmp/duckdb';", + ], + }); + }); + + it('applies valid environment overrides including decimal sizes and boundary thread counts', () => { + const localDev = resolveDuckDbConnectionBudget({ + STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB', + STOCKBOT_DUCKDB_THREADS: '2', + STOCKBOT_DUCKDB_TEMP_DIRECTORY: '/tmp/duckdb', + }); + expect(localDev.statements).toEqual([ + "SET memory_limit = '2GB';", + 'SET threads = 2;', + "SET temp_directory = '/tmp/duckdb';", + ]); + + const decimalMin = resolveDuckDbConnectionBudget({ + STOCKBOT_DUCKDB_MEMORY_LIMIT: '1.5GiB', + STOCKBOT_DUCKDB_THREADS: '1', + STOCKBOT_DUCKDB_TEMP_DIRECTORY: '/var/tmp/stockbot-duckdb', + }); + expect(decimalMin.memoryLimit).toBe('1.5GiB'); + expect(decimalMin.threads).toBe(1); + + const maxThreads = resolveDuckDbConnectionBudget({ + STOCKBOT_DUCKDB_MEMORY_LIMIT: '512MiB', + STOCKBOT_DUCKDB_THREADS: '64', + }); + expect(maxThreads.memoryLimit).toBe('512MiB'); + expect(maxThreads.threads).toBe(64); + }); + + it('rejects malformed memory limits, out-of-range threads, and unsafe temp paths', () => { + const badMemoryLimits = ['0GB', '0.0GiB', '2gb', '2TB', '2 GB', '', "2GB'; DROP TABLE t;--"]; + for (const value of badMemoryLimits) { + expect(() => resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_MEMORY_LIMIT: value })).toThrow( + MarketDataStoreValidationError + ); + } + + const badThreads = ['0', '65', '-1', '2.5', '04', 'abc', '']; + for (const value of badThreads) { + expect(() => resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_THREADS: value })).toThrow( + MarketDataStoreValidationError + ); + } + + const badTempDirs = [ + 'relative/path', + './tmp', + '', + "/tmp/a'b", + '/tmp/a;b', + '/tmp/a\nb', + '/tmp/a\rb', + '/tmp/a\0b', + ]; + for (const value of badTempDirs) { + expect(() => + resolveDuckDbConnectionBudget({ STOCKBOT_DUCKDB_TEMP_DIRECTORY: value }) + ).toThrow(MarketDataStoreValidationError); + } + }); +}); diff --git a/libs/research/test/signal-study-qa.test.ts b/libs/research/test/signal-study-qa.test.ts new file mode 100644 index 00000000..990a694e --- /dev/null +++ b/libs/research/test/signal-study-qa.test.ts @@ -0,0 +1,519 @@ +import { describe, expect, it } from 'bun:test'; +import { + analyzeSignalPanel, + eventStudy, + type EventStudyInput, + type SignalCrossSection, +} from '@stock-bot/calculations'; +import { + analyzeSignal, + canonicalExpressionHash, + runEventStudy, + SignalStudyError, + type AnalyzeSignalRequest, + type RunEventStudyRequest, + type SignalStudyErrorCode, + type TrialLedgerExecutor, +} from '@stock-bot/research'; + +// QA edge cases for T-85 study runners: window-boundary fencing, parity with the pure math, +// logged-row contents, error-code mapping and append-only accounting. + +const VAULT_CUTOFF = '2025-05-01'; +const CAMPAIGN_ID = '11111111-2222-4333-8444-555555555555'; + +interface Call { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +interface Stored { + 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 createExecutor(opts: { readonly dsrThrows?: unknown } = {}) { + const calls: Call[] = []; + const rows: Stored[] = []; + let nextId = 500; + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + calls.push({ text, params }); + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + const p = params ?? []; + const id = ++nextId; + const row: Stored = { + trial_id: String(id), + created_at: new Date(Date.UTC(2025, 3, 2, 0, 0, id % 60)), + 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 (opts.dsrThrows !== undefined) { + throw opts.dsrThrows; + } + 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, calls, rows }; +} + +function rng(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 businessDates(start: string, count: number): string[] { + const out: string[] = []; + const d = new Date(`${start}T00:00:00.000Z`); + 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 signalPanel(dates: readonly string[], seed = 7, n = 15): SignalCrossSection[] { + const r = rng(seed); + const ids = Array.from({ length: n }, (_, i) => i + 1); + return dates.map((date, t) => { + const signal = new Float64Array(n); + const forwardReturn = new Float64Array(n); + const slope = 0.002 + ((t % 5) - 2) * 0.0005; + for (let i = 0; i < n; i += 1) { + const s = r() * 2 - 1; + signal[i] = s; + forwardReturn[i] = 0.0005 + slope * s + 0.015 * (r() * 2 - 1); + } + return { date, ids, signal, forwardReturn }; + }); +} + +function signalRequest(overrides: Partial = {}): AnalyzeSignalRequest { + return { + principalId: 'operator', + campaignId: CAMPAIGN_ID, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'rank(ret_20d)', + params: { lookback: 20 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + panel: signalPanel(businessDates('2025-03-03', 20)), + vaultCutoffDate: VAULT_CUTOFF, + ...overrides, + }; +} + +function eventInput( + dates: readonly string[], + dayIndices: readonly number[], + seed = 13 +): EventStudyInput { + const r = rng(seed); + const entityReturns = new Map(); + for (let id = 1; id <= 4; id += 1) { + const s = new Float64Array(dates.length); + for (let t = 0; t < dates.length; t += 1) { + s[t] = (r() - 0.5) * 0.02; + } + entityReturns.set(id, s); + } + const benchmarkReturns = new Float64Array(dates.length); + for (let t = 0; t < dates.length; t += 1) { + benchmarkReturns[t] = (r() - 0.5) * 0.01; + } + return { + sessionDates: dates, + entityReturns, + benchmarkReturns, + events: dayIndices.map((dayIndex, i) => ({ entityId: (i % 4) + 1, dayIndex })), + }; +} + +function eventRequest(overrides: Partial = {}): RunEventStudyRequest { + return { + principalId: 'operator', + campaignId: CAMPAIGN_ID, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'earnings_car', + params: { minSurprisePct: 5 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + input: eventInput(businessDates('2025-01-02', 60), [12, 16, 20, 24, 28, 32]), + vaultCutoffDate: VAULT_CUTOFF, + options: { preDays: 3, postDays: 5, minEvents: 5 }, + ...overrides, + }; +} + +async function expectCode(fn: () => Promise, code: SignalStudyErrorCode) { + let caught: unknown; + try { + await fn(); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(SignalStudyError); + expect((caught as SignalStudyError).code).toBe(code); + return caught as SignalStudyError; +} + +describe('runEventStudy vault window boundary', () => { + const dates = businessDates('2025-03-03', 55); + const cutoffIdx = dates.findIndex(d => d >= VAULT_CUTOFF); + + it('keeps an event whose window ends on the last pre-cutoff session and drops one ending on the cutoff', async () => { + const postDays = 5; + const lastSafe = cutoffIdx - 1 - postDays; + const firstUnsafe = cutoffIdx - postDays; + const { executor } = createExecutor(); + + const res = await runEventStudy( + executor, + eventRequest({ + input: eventInput(dates, [6, 10, 14, 18, lastSafe, firstUnsafe]), + options: { preDays: 3, postDays, minEvents: 5 }, + }) + ); + + expect(res.status).toBe('ok'); + if (res.status !== 'ok') { + return; + } + expect(res.vaultExcludedEvents).toBe(1); + expect(res.study.diagnostics.eventsUsed).toBe(5); + expect(res.study.diagnostics.droppedWindowOutOfRange).toBe(0); + expect(res.trial.sampleEnd < VAULT_CUTOFF).toBe(true); + }); + + it('with postDays = 0 fences on the event date alone', async () => { + const { executor } = createExecutor(); + const res = await runEventStudy( + executor, + eventRequest({ + input: eventInput(dates, [6, 10, 14, 18, cutoffIdx - 1, cutoffIdx]), + options: { preDays: 3, postDays: 0, minEvents: 5 }, + }) + ); + expect(res.status).toBe('ok'); + if (res.status !== 'ok') { + return; + } + expect(res.vaultExcludedEvents).toBe(1); + expect(res.study.diagnostics.eventsUsed).toBe(5); + }); + + it('returns insufficient_data with zero queries when the cutoff precedes every session', async () => { + const { executor, calls } = createExecutor(); + const res = await runEventStudy( + executor, + eventRequest({ + input: eventInput(dates, [6, 10, 14, 18, 22]), + vaultCutoffDate: '2025-01-01', + }) + ); + expect(res.status).toBe('insufficient_data'); + expect(res.vaultExcludedEvents).toBe(5); + expect(calls).toHaveLength(0); + }); + + it('matches eventStudy run directly on the manually truncated pre-cutoff input', async () => { + const options = { preDays: 3, postDays: 5, minEvents: 5 }; + const input = eventInput(dates, [6, 10, 14, 18, 22, cutoffIdx - 2, cutoffIdx + 3]); + const { executor, rows } = createExecutor(); + + const res = await runEventStudy(executor, eventRequest({ input, options })); + + const manualReturns = new Map(); + for (const [id, s] of input.entityReturns) { + manualReturns.set(id as number, Float64Array.from(s).subarray(0, cutoffIdx)); + } + const expected = eventStudy( + { + sessionDates: dates.slice(0, cutoffIdx), + entityReturns: manualReturns, + benchmarkReturns: Float64Array.from(input.benchmarkReturns ?? []).subarray(0, cutoffIdx), + events: input.events.slice(0, 5), + }, + options + ); + expect(res.status).toBe('ok'); + expect(expected.status).toBe('ok'); + if (res.status !== 'ok' || expected.status !== 'ok') { + return; + } + expect(res.vaultExcludedEvents).toBe(2); + expect(res.study).toEqual(expected); + expect(rows[0]?.daily_series).toEqual( + Array.from(expected.clustered.meanCars, v => Math.fround(v)) + ); + }); + + it('leaves caller Map, arrays and events untouched when the calendar is trimmed', async () => { + const input = eventInput(dates, [6, 10, 14, 18, 22, cutoffIdx + 1]); + const snapshot = { + sessionDates: [...input.sessionDates], + events: input.events.map(e => ({ ...e })), + benchmark: Array.from(input.benchmarkReturns ?? []), + entities: Array.from(input.entityReturns, ([k, v]) => [k, Array.from(v)] as const), + }; + const { executor } = createExecutor(); + + const res = await runEventStudy(executor, eventRequest({ input })); + + expect(res.status).toBe('ok'); + expect([...input.sessionDates]).toEqual(snapshot.sessionDates); + expect(input.events.map(e => ({ ...e }))).toEqual(snapshot.events); + expect(Array.from(input.benchmarkReturns ?? [])).toEqual(snapshot.benchmark); + expect(Array.from(input.entityReturns, ([k, v]) => [k, Array.from(v)] as const)).toEqual( + snapshot.entities + ); + }); +}); + +describe('runEventStudy error mapping (zero queries)', () => { + it('maps eventStudy option and return errors to typed codes', async () => { + const { executor, calls } = createExecutor(); + await expectCode( + () => runEventStudy(executor, eventRequest({ options: { preDays: -1, postDays: 5 } })), + 'invalid_option' + ); + await expectCode( + () => runEventStudy(executor, eventRequest({ options: { postDays: 2.5 } })), + 'invalid_option' + ); + + const base = eventRequest(); + const badReturns = new Map(base.input.entityReturns); + const poisoned = Float64Array.from(badReturns.get(1) ?? []); + poisoned[3] = Number.POSITIVE_INFINITY; // pre-cutoff value: must be rejected + badReturns.set(1, poisoned); + await expectCode( + () => + runEventStudy(executor, { ...base, input: { ...base.input, entityReturns: badReturns } }), + 'invalid_panel' + ); + await expectCode( + () => + runEventStudy(executor, { + ...base, + input: { ...base.input, sessionDates: ['2025-01-02', '2025-13-01'] }, + }), + 'invalid_date' + ); + await expectCode( + () => + runEventStudy(executor, { + ...base, + input: { ...base.input, events: [{ entityId: Number.NaN, dayIndex: 3 }] }, + }), + 'invalid_panel' + ); + await expectCode( + () => runEventStudy(executor, { ...base, input: null as unknown as EventStudyInput }), + 'invalid_request' + ); + expect(calls).toHaveLength(0); + }); +}); + +describe('analyzeSignal contract details', () => { + it('returns the same analysis as analyzeSignalPanel with the cutoff applied', async () => { + const dates = [...businessDates('2025-04-01', 12), '2025-05-01', '2025-05-02']; + const panel = signalPanel(dates, 21); + const options = { minCrossSection: 5, quantiles: 5 }; + const { executor } = createExecutor(); + + const res = await analyzeSignal(executor, signalRequest({ panel, options })); + + expect(res.status).toBe('ok'); + expect(res.analysis).toEqual( + analyzeSignalPanel(panel, { ...options, vaultCutoffDate: VAULT_CUTOFF }) + ); + expect(res.analysis.diagnostics.vaultExcludedDates).toBe(2); + }); + + it('writes the INSERT with request metadata, logged rank-IC series and a hash bound to the sample window', async () => { + const { executor, rows } = createExecutor(); + const req = signalRequest({ campaignId: undefined, hypothesisId: undefined }); + + const res = await analyzeSignal(executor, req); + + expect(res.status).toBe('ok'); + if (res.status !== 'ok') { + return; + } + const row = rows[0]; + expect(row).toBeDefined(); + if (row === undefined) { + return; + } + expect(row.principal_id).toBe('operator'); + expect(row.campaign_id).toBeNull(); + expect(row.hypothesis_id).toBeNull(); + expect(row.stage).toBe('signal_ic'); + expect(row.universe_market).toBe('US_EQ'); + expect(row.horizon_bucket).toBe('swing_1_10d'); + expect(row.sample_start).toBe(res.trial.sampleStart); + expect(row.sample_end).toBe(res.trial.sampleEnd); + expect(row.n_obs).toBe(res.analysis.rankIcSeries.length); + expect(row.daily_series).toEqual(Array.from(res.analysis.rankIcSeries, v => Math.fround(v))); + expect(res.trial.expressionHash).toBe( + canonicalExpressionHash({ + ...req.expression, + sampleStart: res.trial.sampleStart, + sampleEnd: res.trial.sampleEnd, + }) + ); + expect(res.trial.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/); + }); + + it('changes expressionHash when the sample window changes but the expression does not', async () => { + const a = await analyzeSignal(createExecutor().executor, signalRequest()); + const b = await analyzeSignal( + createExecutor().executor, + signalRequest({ panel: signalPanel(businessDates('2025-02-03', 20)) }) + ); + expect(a.status).toBe('ok'); + expect(b.status).toBe('ok'); + if (a.status !== 'ok' || b.status !== 'ok') { + return; + } + expect(a.trial.sampleStart).not.toBe(b.trial.sampleStart); + expect(a.trial.expressionHash).not.toBe(b.trial.expressionHash); + }); + + it('appends one row per call even for identical repeated requests (no dedupe)', async () => { + const { executor, rows } = createExecutor(); + const req = signalRequest(); + const first = await analyzeSignal(executor, req); + const second = await analyzeSignal(executor, req); + expect(rows).toHaveLength(2); + expect(first.status === 'ok' && second.status === 'ok').toBe(true); + if (first.status !== 'ok' || second.status !== 'ok') { + return; + } + expect(second.trial.trialId).not.toBe(first.trial.trialId); + expect(second.deflatedSharpe.clusterSize).toBe(2); + }); + + it('forwards dsrGate so passesGate follows the requested threshold', async () => { + const low = await analyzeSignal(createExecutor().executor, signalRequest({ dsrGate: -1 })); + const high = await analyzeSignal(createExecutor().executor, signalRequest({ dsrGate: 2 })); + expect(low.status).toBe('ok'); + expect(high.status).toBe('ok'); + if (low.status !== 'ok' || high.status !== 'ok') { + return; + } + expect(low.deflatedSharpe.dsr).toBe(high.deflatedSharpe.dsr); + expect(low.deflatedSharpe.passesGate).toBe(true); + expect(high.deflatedSharpe.passesGate).toBe(false); + }); + + it('wraps a non-Error DSR read rejection as dsr_read_failed carrying trialId and raw cause', async () => { + const { executor, calls } = createExecutor({ dsrThrows: 'connection reset' }); + const err = await expectCode(() => analyzeSignal(executor, signalRequest()), 'dsr_read_failed'); + expect(err.trialId).toBe(501); + expect(err.cause).toBe('connection reset'); + expect(calls.filter(c => c.text.trimStart().startsWith('INSERT'))).toHaveLength(1); + }); + + it('returns insufficient_data with zero queries when the cutoff precedes the whole panel', async () => { + const { executor, calls } = createExecutor(); + const res = await analyzeSignal(executor, signalRequest({ vaultCutoffDate: '2025-01-01' })); + expect(res.status).toBe('insufficient_data'); + expect(res.analysis.diagnostics.vaultExcludedDates).toBe(20); + expect(calls).toHaveLength(0); + }); + + it('rejects malformed ledger metadata before any query', async () => { + const { executor, calls } = createExecutor(); + await expectCode( + () => analyzeSignal(executor, signalRequest({ campaignId: 'not-a-uuid' })), + 'invalid_request' + ); + await expectCode( + () => analyzeSignal(executor, signalRequest({ universeMarket: 'XX' as unknown as 'US_EQ' })), + 'invalid_request' + ); + await expectCode( + () => + analyzeSignal( + executor, + signalRequest({ horizonBucket: 'forever' as unknown as 'swing_1_10d' }) + ), + 'invalid_request' + ); + await expectCode( + () => analyzeSignal(executor, signalRequest({ vaultCutoffDate: '2025-5-1' })), + 'invalid_date' + ); + await expectCode( + () => analyzeSignal(executor, signalRequest({ options: { quantiles: 0 } })), + 'invalid_option' + ); + await expectCode( + () => analyzeSignal(executor, null as unknown as AnalyzeSignalRequest), + 'invalid_request' + ); + expect(calls).toHaveLength(0); + }); +}); diff --git a/libs/research/test/signal-study.test.ts b/libs/research/test/signal-study.test.ts new file mode 100644 index 00000000..9f8747ea --- /dev/null +++ b/libs/research/test/signal-study.test.ts @@ -0,0 +1,1042 @@ +import { describe, expect, it } from 'bun:test'; +import vm from 'node:vm'; +import type { EventStudyInput, SignalCrossSection } from '@stock-bot/calculations'; +import { + SignalStudyError, + analyzeSignal, + runEventStudy, + type AnalyzeSignalRequest, + type RunEventStudyRequest, + type SignalStudyErrorCode, + type TrialLedgerExecutor, +} from '@stock-bot/research'; +import { + SignalStudyError as SubpathSignalStudyError, + analyzeSignal as subpathAnalyzeSignal, + runEventStudy as subpathRunEventStudy, +} from '@stock-bot/research/signal-study'; + +const VAULT_CUTOFF = '2025-05-01'; +const VALID_CAMPAIGN_ID = '11111111-2222-4333-8444-555555555555'; +const VALID_HYPOTHESIS_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; + +interface RecordedSqlCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +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[]; +} + +interface InMemoryExecutorOptions { + readonly failOnInsert?: Error; + readonly failOnDsrRead?: Error; +} + +function createInMemoryTrialExecutor(options: InMemoryExecutorOptions = {}): { + executor: TrialLedgerExecutor; + calls: RecordedSqlCall[]; + rows: StoredTrialRow[]; +} { + const calls: RecordedSqlCall[] = []; + const rows: StoredTrialRow[] = []; + let nextTrialId = 100; + + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + calls.push({ text, params }); + const trimmed = text.trimStart(); + + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + if (options.failOnInsert !== undefined) { + throw options.failOnInsert; + } + const p = params ?? []; + const trialId = ++nextTrialId; + const createdAt = new Date(Date.UTC(2025, 3, 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')) { + if (options.failOnDsrRead !== undefined) { + throw options.failOnDsrRead; + } + 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, calls, rows }; +} + +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 makeSignalPanel(dates: readonly string[], nNames = 15, seed = 42): SignalCrossSection[] { + const rand = createSeededRng(seed); + const ids = Array.from({ length: nNames }, (_, i) => i + 1); + return dates.map((date, t) => { + const signal = new Float64Array(nNames); + const forwardReturn = new Float64Array(nNames); + const slope = 0.002 + ((t % 5) - 2) * 0.0005; + for (let i = 0; i < nNames; i += 1) { + const s = rand() * 2 - 1; + signal[i] = s; + forwardReturn[i] = 0.0005 + slope * s + 0.015 * (rand() * 2 - 1); + } + return { date, ids, signal, forwardReturn }; + }); +} + +function makeSignalRequest(overrides: Partial = {}): AnalyzeSignalRequest { + const dates = makeBusinessDates('2025-03-03', 20); + return { + principalId: 'operator', + campaignId: VALID_CAMPAIGN_ID, + hypothesisId: VALID_HYPOTHESIS_ID, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'rank(ret_20d) - zscore(vol_20d)', + params: { lookback: 20 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + panel: makeSignalPanel(dates), + vaultCutoffDate: VAULT_CUTOFF, + ...overrides, + }; +} + +function makeEventStudyInput( + dates: readonly string[], + eventDayIndices: readonly number[], + seed = 99 +): EventStudyInput { + const rand = createSeededRng(seed); + const entityReturns = new Map(); + for (let entityId = 1; entityId <= 4; entityId += 1) { + const series = new Float64Array(dates.length); + for (let t = 0; t < dates.length; t += 1) { + series[t] = (rand() - 0.5) * 0.02; + } + entityReturns.set(entityId, series); + } + const benchmarkReturns = new Float64Array(dates.length); + for (let t = 0; t < dates.length; t += 1) { + benchmarkReturns[t] = (rand() - 0.5) * 0.01; + } + const events = eventDayIndices.map((dayIndex, idx) => ({ + entityId: (idx % 4) + 1, + dayIndex, + })); + return { + sessionDates: dates, + entityReturns, + benchmarkReturns, + events, + }; +} + +function makeEventStudyRequest( + overrides: Partial = {} +): RunEventStudyRequest { + const dates = makeBusinessDates('2025-01-02', 60); + return { + principalId: 'operator', + campaignId: VALID_CAMPAIGN_ID, + hypothesisId: VALID_HYPOTHESIS_ID, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'earnings_surprise_car', + params: { minSurprisePct: 5 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + input: makeEventStudyInput(dates, [12, 16, 20, 24, 28, 32]), + vaultCutoffDate: VAULT_CUTOFF, + options: { preDays: 5, postDays: 5, minEvents: 5 }, + ...overrides, + }; +} + +async function expectStudyError( + fn: () => Promise, + expectedCode: SignalStudyErrorCode +): Promise { + try { + await fn(); + } catch (error) { + expect(error).toBeInstanceOf(SignalStudyError); + const typed = error as SignalStudyError; + expect(typed.code).toBe(expectedCode); + return typed; + } + throw new Error(`Expected SignalStudyError(${expectedCode}), but call succeeded`); +} + +describe('signal-study exports', () => { + it('exposes identical runtime exports from package root and subpath', () => { + expect(analyzeSignal).toBe(subpathAnalyzeSignal); + expect(runEventStudy).toBe(subpathRunEventStudy); + expect(SignalStudyError).toBe(SubpathSignalStudyError); + }); +}); + +describe('analyzeSignal', () => { + it('runs happy path with default rank_ic series, issuing 1 INSERT then 2 SELECTs', async () => { + const { executor, calls, rows } = createInMemoryTrialExecutor(); + const request = makeSignalRequest(); + + const result = await analyzeSignal(executor, request); + + expect(result.status).toBe('ok'); + if (result.status !== 'ok') { + return; + } + + expect(calls).toHaveLength(3); + expect(calls[0]?.text.trimStart().startsWith('INSERT INTO trial_ledger')).toBe(true); + expect(calls[0]?.params?.[2]).toBe('signal_ic'); + expect(calls[1]?.text).toContain('WHERE trial_id = $1::bigint'); + expect(calls[2]?.text).toContain('WHERE universe_market = $1'); + + expect(rows).toHaveLength(1); + expect(result.trial.trialId).toBe(101); + expect(result.trial.nObs).toBe(result.analysis.rankIcSeries.length); + expect(result.trial.sampleStart).toBe(result.analysis.dates[0]!); + expect(result.trial.sampleEnd).toBe(result.analysis.dates[result.analysis.dates.length - 1]!); + expect(result.trial.sampleEnd < VAULT_CUTOFF).toBe(true); + expect(result.trial.expressionHash).toMatch(/^[0-9a-f]{64}$/); + expect(result.deflatedSharpe.trialId).toBe(101); + expect(result.deflatedSharpe.clusterSize).toBe(1); + expect(Number.isFinite(result.deflatedSharpe.effectiveTrials)).toBe(true); + }); + + it('logs quantile spread series when ledgerSeries is quantile_spread', async () => { + const { executor, calls, rows } = createInMemoryTrialExecutor(); + const request = makeSignalRequest({ ledgerSeries: 'quantile_spread' }); + + const result = await analyzeSignal(executor, request); + + expect(result.status).toBe('ok'); + if (result.status !== 'ok') { + return; + } + expect(calls).toHaveLength(3); + expect(rows).toHaveLength(1); + expect(result.trial.nObs).toBe(result.analysis.quantiles.spreadSeries.length); + expect(result.trial.sampleStart).toBe(result.analysis.quantiles.dates[0]!); + expect(result.trial.sampleEnd).toBe( + result.analysis.quantiles.dates[result.analysis.quantiles.dates.length - 1]! + ); + const logged = rows[0]!.daily_series; + expect(logged).toHaveLength(result.analysis.quantiles.spreadSeries.length); + for (let i = 0; i < logged.length; i += 1) { + expect(logged[i]).toBe(Math.fround(result.analysis.quantiles.spreadSeries[i]!)); + } + }); + + it('returns insufficient_data with zero queries when fewer than 2 valid dates remain', async () => { + const { executor, calls } = createInMemoryTrialExecutor(); + const dates = ['2025-04-30', '2025-05-01', '2025-05-02']; + const request = makeSignalRequest({ + panel: makeSignalPanel(dates), + vaultCutoffDate: VAULT_CUTOFF, + }); + + const result = await analyzeSignal(executor, request); + + expect(result.status).toBe('insufficient_data'); + if (result.status === 'insufficient_data') { + expect(result.reason).toBe('too_few_observations'); + } + expect(calls).toHaveLength(0); + }); + + it('returns insufficient_data with zero queries when rankIcSeries has zero variance', async () => { + const { executor, calls } = createInMemoryTrialExecutor(); + const dates = makeBusinessDates('2025-03-03', 6); + const ids = [1, 2, 3, 4, 5, 6]; + const panel: SignalCrossSection[] = dates.map(date => ({ + date, + ids, + signal: [1, 2, 3, 4, 5, 6], + forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05, 0.06], + })); + + const result = await analyzeSignal(executor, makeSignalRequest({ panel })); + + expect(result.status).toBe('insufficient_data'); + if (result.status === 'insufficient_data') { + expect(result.reason).toBe('zero_variance_series'); + } + expect(calls).toHaveLength(0); + }); + + it('excludes dates >= vaultCutoffDate and is bit-invariant to post-cutoff mutations', async () => { + const preDates = makeBusinessDates('2025-04-01', 12); + const postDates = ['2025-05-01', '2025-05-02', '2025-05-05']; + const allDates = [...preDates, ...postDates]; + const basePanel = makeSignalPanel(allDates, 15, 77); + + const mutatedPanel: SignalCrossSection[] = basePanel.map(slice => { + if (slice.date >= VAULT_CUTOFF) { + return { + ...slice, + signal: Array.from({ length: slice.ids.length }, (_, i) => (i + 1) * 999), + forwardReturn: Array.from({ length: slice.ids.length }, () => -0.75), + }; + } + return slice; + }); + + const run1Store = createInMemoryTrialExecutor(); + const run2Store = createInMemoryTrialExecutor(); + const res1 = await analyzeSignal(run1Store.executor, makeSignalRequest({ panel: basePanel })); + const res2 = await analyzeSignal( + run2Store.executor, + makeSignalRequest({ panel: mutatedPanel }) + ); + + expect(res1.status).toBe('ok'); + expect(res2.status).toBe('ok'); + if (res1.status !== 'ok' || res2.status !== 'ok') { + return; + } + + expect(res1.analysis.diagnostics.vaultExcludedDates).toBe(3); + expect(res1.trial.sampleEnd < VAULT_CUTOFF).toBe(true); + expect(res1.trial.expressionHash).toBe(res2.trial.expressionHash); + expect(res1.trial.sampleStart).toBe(res2.trial.sampleStart); + expect(res1.trial.sampleEnd).toBe(res2.trial.sampleEnd); + expect(Array.from(res1.analysis.rankIcSeries)).toEqual(Array.from(res2.analysis.rankIcSeries)); + expect(run1Store.rows[0]?.daily_series).toEqual(run2Store.rows[0]?.daily_series); + }); + + it('produces identical expressionHash for identical requests and different hashes on param change', async () => { + const store1 = createInMemoryTrialExecutor(); + const store2 = createInMemoryTrialExecutor(); + const store3 = createInMemoryTrialExecutor(); + + const baseReq = makeSignalRequest(); + const res1 = await analyzeSignal(store1.executor, baseReq); + const res2 = await analyzeSignal(store2.executor, baseReq); + const res3 = await analyzeSignal( + store3.executor, + makeSignalRequest({ + panel: baseReq.panel, + expression: { + ...baseReq.expression, + params: { lookback: 40 }, + }, + }) + ); + + expect(res1.status).toBe('ok'); + expect(res2.status).toBe('ok'); + expect(res3.status).toBe('ok'); + if (res1.status === 'ok' && res2.status === 'ok' && res3.status === 'ok') { + expect(res1.trial.expressionHash).toBe(res2.trial.expressionHash); + expect(res1.trial.expressionHash).not.toBe(res3.trial.expressionHash); + } + }); + + it('propagates INSERT failure with no result and 1 total query', async () => { + const insertError = new Error('simulated pg insert failure'); + const { executor, calls } = createInMemoryTrialExecutor({ failOnInsert: insertError }); + + await expect(analyzeSignal(executor, makeSignalRequest())).rejects.toBe(insertError); + expect(calls).toHaveLength(1); + expect(calls[0]?.text.trimStart().startsWith('INSERT INTO trial_ledger')).toBe(true); + }); + + it('throws SignalStudyError(dsr_read_failed) carrying trialId and cause without retrying INSERT', async () => { + const readError = new Error('simulated pg select failure'); + const { executor, calls, rows } = createInMemoryTrialExecutor({ failOnDsrRead: readError }); + + const err = await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest()), + 'dsr_read_failed' + ); + expect(err.trialId).toBe(101); + expect(err.cause).toBe(readError); + expect(rows).toHaveLength(1); + const insertCount = calls.filter(c => c.text.trimStart().startsWith('INSERT')).length; + expect(insertCount).toBe(1); + }); + + it('rejects invalid inputs with typed SignalStudyError codes and zero SQL queries', async () => { + const { executor, calls } = createInMemoryTrialExecutor(); + + await expectStudyError( + () => analyzeSignal(null as unknown as TrialLedgerExecutor, makeSignalRequest()), + 'invalid_request' + ); + await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest({ panel: [] })), + 'empty_panel' + ); + await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest({ vaultCutoffDate: '2025-02-30' })), + 'invalid_date' + ); + await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest({ principalId: 'bad-principal' })), + 'invalid_request' + ); + await expectStudyError( + () => + analyzeSignal( + executor, + makeSignalRequest({ + ledgerSeries: 'bad_series' as unknown as 'rank_ic', + }) + ), + 'invalid_option' + ); + await expectStudyError( + () => + analyzeSignal( + executor, + makeSignalRequest({ + ledgerSeries: null as unknown as 'rank_ic', + }) + ), + 'invalid_option' + ); + await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest({ dsrGate: Number.NaN })), + 'invalid_option' + ); + + const unsortedPanel = makeSignalPanel(['2025-03-05', '2025-03-04']); + await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest({ panel: unsortedPanel })), + 'unsorted_dates' + ); + + const duplicatePanel = makeSignalPanel(['2025-03-05', '2025-03-05']); + await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest({ panel: duplicatePanel })), + 'duplicate_date' + ); + + const mismatchedPanel: SignalCrossSection[] = [ + { date: '2025-03-05', ids: [1, 2, 3], signal: [1, 2], forwardReturn: [0.1, 0.2, 0.3] }, + ]; + await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest({ panel: mismatchedPanel })), + 'invalid_panel' + ); + + // Missing or malformed cross-section vectors must throw SignalStudyError('invalid_panel'), + // never a raw TypeError, and issue zero SQL queries. + const missingForwardReturnPanel = [ + { date: '2025-03-05', ids: [1, 2, 3], signal: [1, 2, 3] }, + ] as unknown as SignalCrossSection[]; + await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest({ panel: missingForwardReturnPanel })), + 'invalid_panel' + ); + const nullSlicePanel = [null] as unknown as SignalCrossSection[]; + await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest({ panel: nullSlicePanel })), + 'invalid_panel' + ); + + expect(calls).toHaveLength(0); + }); + + it('supports typed-array panel vectors and falls back conservatively to count-based DSR across cluster trials', async () => { + const { executor, rows } = createInMemoryTrialExecutor(); + const dates = makeBusinessDates('2025-03-03', 12); + const typedPanel: SignalCrossSection[] = makeSignalPanel(dates, 12, 111).map(slice => ({ + date: slice.date, + ids: Int32Array.from(slice.ids as number[]), + signal: slice.signal, + forwardReturn: slice.forwardReturn, + })); + + const first = await analyzeSignal(executor, makeSignalRequest({ panel: typedPanel })); + const second = await analyzeSignal( + executor, + makeSignalRequest({ + panel: typedPanel, + expression: { + expression: 'rank(ret_10d)', + params: { lookback: 10 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + }) + ); + + expect(first.status).toBe('ok'); + expect(second.status).toBe('ok'); + if (first.status !== 'ok' || second.status !== 'ok') { + return; + } + expect(rows).toHaveLength(2); + expect(second.deflatedSharpe.clusterSize).toBe(2); + expect(second.deflatedSharpe.pairsUsed).toBe(0); + expect(second.deflatedSharpe.pairsSkipped).toBe(1); + expect(second.deflatedSharpe.effectiveTrials).toBe(2); + }); + + it('does not mutate frozen caller inputs', async () => { + const { executor } = createInMemoryTrialExecutor(); + const dates = makeBusinessDates('2025-03-03', 10); + const panel = Object.freeze( + makeSignalPanel(dates).map(slice => + Object.freeze({ + date: slice.date, + ids: Object.freeze([...slice.ids]), + signal: Object.freeze([...slice.signal]), + forwardReturn: Object.freeze([...slice.forwardReturn]), + }) + ) + ); + const expression = Object.freeze({ + expression: 'rank(ret_5d)', + params: Object.freeze({ lookback: 5 }), + universe: 'US_EQ', + horizon: '5d', + }); + const options = Object.freeze({ minCrossSection: 5, quantiles: 5 }); + const request = Object.freeze(makeSignalRequest({ panel, expression, options })); + + const result = await analyzeSignal(executor, request); + expect(result.status).toBe('ok'); + }); +}); + +describe('runEventStudy', () => { + it('runs happy path issuing 1 INSERT (stage=event_study) then 2 SELECTs', async () => { + const { executor, calls, rows } = createInMemoryTrialExecutor(); + const request = makeEventStudyRequest(); + + const result = await runEventStudy(executor, request); + + expect(result.status).toBe('ok'); + if (result.status !== 'ok') { + return; + } + + expect(calls).toHaveLength(3); + expect(calls[0]?.text.trimStart().startsWith('INSERT INTO trial_ledger')).toBe(true); + expect(calls[0]?.params?.[2]).toBe('event_study'); + expect(calls[1]?.text).toContain('WHERE trial_id = $1::bigint'); + expect(calls[2]?.text).toContain('WHERE universe_market = $1'); + + expect(rows).toHaveLength(1); + expect(result.vaultExcludedEvents).toBe(0); + expect(result.trial.trialId).toBe(101); + expect(result.trial.nObs).toBe(result.study.clustered.meanCars.length); + expect(result.trial.sampleStart).toBe(result.study.clustered.dates[0]!); + expect(result.trial.sampleEnd).toBe( + result.study.clustered.dates[result.study.clustered.dates.length - 1]! + ); + expect(result.trial.sampleEnd < VAULT_CUTOFF).toBe(true); + expect(result.deflatedSharpe.clusterSize).toBe(1); + }); + + it('fences events whose event date OR post-event window end >= vaultCutoffDate and is bit-invariant to post-cutoff return mutations', async () => { + const dates = makeBusinessDates('2025-03-03', 55); + const cutoffIdx = dates.findIndex(d => d >= VAULT_CUTOFF); + expect(cutoffIdx).toBeGreaterThan(25); + + const postDays = 5; + // 5 safe events strictly ending before cutoff; + // 1 event before cutoff whose dayIndex + postDays lands ON cutoff; + // 1 event ON cutoff; + // 1 event AFTER cutoff. + const eventDayIndices = [ + 6, + 10, + 14, + 18, + 22, + cutoffIdx - postDays, + cutoffIdx, + cutoffIdx + 2, + ]; + const baseInput = makeEventStudyInput(dates, eventDayIndices, 303); + + const mutatedReturns = new Map(); + for (const [id, series] of baseInput.entityReturns.entries()) { + const copy = new Float64Array(series); + for (let t = cutoffIdx; t < copy.length; t += 1) { + copy[t] = 0.95; + } + mutatedReturns.set(id, copy); + } + const mutatedBenchmark = new Float64Array(baseInput.benchmarkReturns!); + for (let t = cutoffIdx; t < mutatedBenchmark.length; t += 1) { + mutatedBenchmark[t] = -0.5; + } + const mutatedInput: EventStudyInput = { + ...baseInput, + entityReturns: mutatedReturns, + benchmarkReturns: mutatedBenchmark, + }; + + const store1 = createInMemoryTrialExecutor(); + const store2 = createInMemoryTrialExecutor(); + const res1 = await runEventStudy( + store1.executor, + makeEventStudyRequest({ input: baseInput, options: { preDays: 3, postDays, minEvents: 5 } }) + ); + const res2 = await runEventStudy( + store2.executor, + makeEventStudyRequest({ + input: mutatedInput, + options: { preDays: 3, postDays, minEvents: 5 }, + }) + ); + + expect(res1.status).toBe('ok'); + expect(res2.status).toBe('ok'); + if (res1.status !== 'ok' || res2.status !== 'ok') { + return; + } + + expect(res1.vaultExcludedEvents).toBe(3); + expect(res2.vaultExcludedEvents).toBe(3); + expect(res1.study.diagnostics.eventsUsed).toBe(5); + expect(res1.trial.sampleEnd < VAULT_CUTOFF).toBe(true); + expect(res1.trial.expressionHash).toBe(res2.trial.expressionHash); + expect(Array.from(res1.study.clustered.meanCars)).toEqual( + Array.from(res2.study.clustered.meanCars) + ); + expect(store1.rows[0]?.daily_series).toEqual(store2.rows[0]?.daily_series); + + // Non-finite returns (e.g. Infinity from zero prior price) in the excluded Vault tail + // must not fail the pre-Vault study or alter its outputs or ledger values. + const infiniteTailReturns = new Map(); + for (const [id, series] of baseInput.entityReturns.entries()) { + const copy = new Float64Array(series); + copy[cutoffIdx] = Number.POSITIVE_INFINITY; + copy[copy.length - 1] = Number.NEGATIVE_INFINITY; + infiniteTailReturns.set(id, copy); + } + const infiniteTailBenchmark = new Float64Array(baseInput.benchmarkReturns!); + infiniteTailBenchmark[cutoffIdx] = Number.POSITIVE_INFINITY; + const store3 = createInMemoryTrialExecutor(); + const res3 = await runEventStudy( + store3.executor, + makeEventStudyRequest({ + input: { + ...baseInput, + entityReturns: infiniteTailReturns, + benchmarkReturns: infiniteTailBenchmark, + }, + options: { preDays: 3, postDays, minEvents: 5 }, + }) + ); + expect(res3.status).toBe('ok'); + if (res3.status !== 'ok') { + return; + } + expect(res3.vaultExcludedEvents).toBe(3); + expect(res3.trial.expressionHash).toBe(res1.trial.expressionHash); + expect(Array.from(res3.study.clustered.meanCars)).toEqual( + Array.from(res1.study.clustered.meanCars) + ); + expect(store3.rows[0]?.daily_series).toEqual(store1.rows[0]?.daily_series); + }); + + it('returns insufficient_data with zero queries for below_min_events, too_few_event_dates, and zero-variance clustered CARs', async () => { + const { executor, calls } = createInMemoryTrialExecutor(); + const dates = makeBusinessDates('2025-01-02', 40); + + // below_min_events + const resBelowMin = await runEventStudy( + executor, + makeEventStudyRequest({ + input: makeEventStudyInput(dates, [10, 15]), + options: { preDays: 3, postDays: 3, minEvents: 5 }, + }) + ); + expect(resBelowMin.status).toBe('insufficient_data'); + if (resBelowMin.status === 'insufficient_data') { + expect(resBelowMin.reason).toBe('below_min_events'); + } + + // too_few_event_dates (all 5 events on the exact same dayIndex) + const sameDayInput = makeEventStudyInput(dates, [15, 15, 15, 15]); + const sameDayWithFive = { + ...sameDayInput, + entityReturns: new Map([ + ...sameDayInput.entityReturns.entries(), + [5, new Float64Array(dates.length).fill(0.005)], + ]), + events: [1, 2, 3, 4, 5].map(entityId => ({ entityId, dayIndex: 15 })), + }; + const resTooFewDates = await runEventStudy( + executor, + makeEventStudyRequest({ + input: sameDayWithFive, + options: { preDays: 3, postDays: 3, minEvents: 5 }, + }) + ); + expect(resTooFewDates.status).toBe('insufficient_data'); + if (resTooFewDates.status === 'insufficient_data') { + expect(resTooFewDates.reason).toBe('too_few_event_dates'); + } + + // zero_variance_series (identical constant returns on every date -> identical clustered meanCars) + const constantReturns = new Map([ + [1, new Float64Array(dates.length).fill(0.01)], + [2, new Float64Array(dates.length).fill(0.01)], + ]); + const constantInput: EventStudyInput = { + sessionDates: dates, + entityReturns: constantReturns, + events: [ + { entityId: 1, dayIndex: 6 }, + { entityId: 2, dayIndex: 10 }, + { entityId: 1, dayIndex: 14 }, + { entityId: 2, dayIndex: 18 }, + { entityId: 1, dayIndex: 22 }, + ], + }; + const resZeroVar = await runEventStudy( + executor, + makeEventStudyRequest({ + input: constantInput, + options: { preDays: 2, postDays: 2, minEvents: 5 }, + }) + ); + expect(resZeroVar.status).toBe('insufficient_data'); + if (resZeroVar.status === 'insufficient_data') { + expect(resZeroVar.reason).toBe('zero_variance_series'); + } + + expect(calls).toHaveLength(0); + }); + + it('propagates INSERT failure and wraps DSR-read failure with trialId and cause without retry', async () => { + const insertError = new Error('event insert failed'); + const failInsertStore = createInMemoryTrialExecutor({ failOnInsert: insertError }); + await expect(runEventStudy(failInsertStore.executor, makeEventStudyRequest())).rejects.toBe( + insertError + ); + expect(failInsertStore.calls).toHaveLength(1); + + const readError = new Error('event dsr read failed'); + const failReadStore = createInMemoryTrialExecutor({ failOnDsrRead: readError }); + const err = await expectStudyError( + () => runEventStudy(failReadStore.executor, makeEventStudyRequest()), + 'dsr_read_failed' + ); + expect(err.trialId).toBe(101); + expect(err.cause).toBe(readError); + expect(failReadStore.calls.filter(c => c.text.trimStart().startsWith('INSERT'))).toHaveLength( + 1 + ); + }); + + it('validates inputs with zero queries and does not mutate frozen caller inputs', async () => { + const { executor, calls } = createInMemoryTrialExecutor(); + + await expectStudyError( + () => + runEventStudy( + executor, + makeEventStudyRequest({ + input: { sessionDates: [], entityReturns: new Map(), events: [] }, + }) + ), + 'empty_panel' + ); + await expectStudyError( + () => + runEventStudy( + executor, + makeEventStudyRequest({ + input: { + sessionDates: ['2025-01-05', '2025-01-04'], + entityReturns: new Map(), + events: [], + }, + }) + ), + 'unsorted_dates' + ); + await expectStudyError( + () => + runEventStudy( + executor, + makeEventStudyRequest({ + input: { + sessionDates: ['2025-01-05', '2025-01-05'], + entityReturns: new Map(), + events: [], + }, + }) + ), + 'duplicate_date' + ); + await expectStudyError( + () => + runEventStudy( + executor, + makeEventStudyRequest({ + options: { postDays: -1 }, + }) + ), + 'invalid_option' + ); + await expectStudyError( + () => + runEventStudy( + executor, + makeEventStudyRequest({ + options: { postDays: null as unknown as number }, + }) + ), + 'invalid_option' + ); + await expectStudyError( + () => + runEventStudy( + executor, + makeEventStudyRequest({ + input: { + sessionDates: ['2025-01-05', '2025-01-06'], + entityReturns: new Map(), + events: [{ entityId: 1, dayIndex: -2 }], + }, + }) + ), + 'invalid_panel' + ); + // Shape validation against the full calendar is preserved even when Vault dates exist. + await expectStudyError( + () => + runEventStudy( + executor, + makeEventStudyRequest({ + input: { + sessionDates: ['2025-04-29', '2025-04-30', '2025-05-01'], + entityReturns: new Map([[1, new Float64Array([0.01, 0.02])]]), + events: [], + }, + }) + ), + 'invalid_panel' + ); + expect(calls).toHaveLength(0); + + // Frozen immutability test + const baseReq = makeEventStudyRequest(); + const frozenInput: EventStudyInput = Object.freeze({ + sessionDates: Object.freeze([...baseReq.input.sessionDates]), + entityReturns: baseReq.input.entityReturns, + benchmarkReturns: Object.freeze([...(baseReq.input.benchmarkReturns ?? [])]), + events: Object.freeze(baseReq.input.events.map(e => Object.freeze({ ...e }))), + }); + const frozenReq = Object.freeze({ + ...baseReq, + input: frozenInput, + options: Object.freeze({ ...baseReq.options }), + expression: Object.freeze({ + ...baseReq.expression, + params: Object.freeze({ minSurprisePct: 5 }), + }), + }); + + const okStore = createInMemoryTrialExecutor(); + const result = await runEventStudy(okStore.executor, frozenReq); + expect(result.status).toBe('ok'); + }); + + it('rejects serialized entityReturns pair arrays (including duplicate keys) with invalid_panel and zero queries when calendar spans vaultCutoffDate', async () => { + const baseReq = makeEventStudyRequest(); + const cutoffDate = baseReq.input.sessionDates[baseReq.input.sessionDates.length - 5]; + expect(cutoffDate).toBeDefined(); + if (cutoffDate === undefined) { + throw new Error('Expected sessionDates to have at least 5 dates'); + } + const vaultSpanningReq = { ...baseReq, vaultCutoffDate: cutoffDate }; + + // Confirm the uncorrupted Map request succeeds under this Vault-spanning cutoff. + const validStore = createInMemoryTrialExecutor(); + const validRes = await runEventStudy(validStore.executor, vaultSpanningReq); + expect(validRes.status).toBe('ok'); + + const existingEntries = Array.from(baseReq.input.entityReturns.entries()); + const firstEntry = existingEntries[0]; + expect(firstEntry).toBeDefined(); + if (!firstEntry) { + throw new Error('Expected at least one entityReturns entry'); + } + const [dupEntityId, firstSeries] = firstEntry; + const duplicateSeries = Array.from(firstSeries, value => value + 0.05); + // Serialized JSON [entityId, series][] pair array with duplicate entityId key. + const serializedPairsWithDuplicate = [...existingEntries, [dupEntityId, duplicateSeries]]; + + const { executor, calls } = createInMemoryTrialExecutor(); + await expectStudyError( + () => + runEventStudy(executor, { + ...vaultSpanningReq, + input: { + ...baseReq.input, + entityReturns: serializedPairsWithDuplicate as unknown as EventStudyInput['entityReturns'], + }, + }), + 'invalid_panel' + ); + expect(calls).toHaveLength(0); + }); + + it('accepts cross-realm typed arrays in both analyzeSignal and runEventStudy (including Vault-trimmed prefixes)', async () => { + const toCrossRealmFloat64 = (values: readonly number[]): Float64Array => + vm.runInNewContext('new Float64Array(values)', { values }) as Float64Array; + const toCrossRealmInt32 = (values: readonly number[]): Int32Array => + vm.runInNewContext('new Int32Array(values)', { values }) as Int32Array; + + // Confirm the VM-created typed array fails same-realm instanceof. + const probeF64 = toCrossRealmFloat64([1, 2]); + expect(probeF64 instanceof Float64Array).toBe(false); + + // 1. analyzeSignal with cross-realm Int32Array ids and Float64Array signal/forwardReturn + const baseSignalReq = makeSignalRequest(); + const crossRealmPanel: SignalCrossSection[] = baseSignalReq.panel.map(slice => ({ + date: slice.date, + ids: toCrossRealmInt32(Array.from(slice.ids, id => Number(id))), + signal: toCrossRealmFloat64(Array.from(slice.signal)), + forwardReturn: toCrossRealmFloat64(Array.from(slice.forwardReturn)), + })); + + const baseSignalStore = createInMemoryTrialExecutor(); + const baseSignalRes = await analyzeSignal(baseSignalStore.executor, baseSignalReq); + const crossSignalStore = createInMemoryTrialExecutor(); + const crossSignalRes = await analyzeSignal(crossSignalStore.executor, { + ...baseSignalReq, + panel: crossRealmPanel, + }); + expect(baseSignalRes.status).toBe('ok'); + expect(crossSignalRes.status).toBe('ok'); + if (baseSignalRes.status === 'ok' && crossSignalRes.status === 'ok') { + expect(crossSignalRes.trial.expressionHash).toBe(baseSignalRes.trial.expressionHash); + expect(crossSignalRes.analysis.rankIcSeries).toEqual(baseSignalRes.analysis.rankIcSeries); + } + + // 2. runEventStudy with cross-realm Float64Array returns and a calendar spanning vaultCutoffDate + const rawEventReq = makeEventStudyRequest(); + const cutoffDate = rawEventReq.input.sessionDates[rawEventReq.input.sessionDates.length - 5]; + expect(cutoffDate).toBeDefined(); + if (cutoffDate === undefined) { + throw new Error('Expected sessionDates to have at least 5 dates'); + } + const baseEventReq: RunEventStudyRequest = { ...rawEventReq, vaultCutoffDate: cutoffDate }; + const crossRealmEntityReturns = new Map(); + for (const [entityId, series] of baseEventReq.input.entityReturns) { + crossRealmEntityReturns.set(entityId, toCrossRealmFloat64(Array.from(series))); + } + const crossRealmBenchmark = + baseEventReq.input.benchmarkReturns !== undefined + ? toCrossRealmFloat64(Array.from(baseEventReq.input.benchmarkReturns)) + : undefined; + + const baseEventStore = createInMemoryTrialExecutor(); + const baseEventRes = await runEventStudy(baseEventStore.executor, baseEventReq); + const crossEventStore = createInMemoryTrialExecutor(); + const crossEventRes = await runEventStudy(crossEventStore.executor, { + ...baseEventReq, + input: { + ...baseEventReq.input, + entityReturns: crossRealmEntityReturns, + ...(crossRealmBenchmark !== undefined ? { benchmarkReturns: crossRealmBenchmark } : {}), + }, + }); + expect(baseEventRes.status).toBe('ok'); + expect(crossEventRes.status).toBe('ok'); + if (baseEventRes.status === 'ok' && crossEventRes.status === 'ok') { + expect(crossEventRes.trial.expressionHash).toBe(baseEventRes.trial.expressionHash); + expect(crossEventRes.study.clustered.meanCars).toEqual( + baseEventRes.study.clustered.meanCars + ); + expect(crossEventRes.vaultExcludedEvents).toBe(baseEventRes.vaultExcludedEvents); + } + }); +}); diff --git a/libs/research/test/trial-ledger-qa.test.ts b/libs/research/test/trial-ledger-qa.test.ts new file mode 100644 index 00000000..8d593332 --- /dev/null +++ b/libs/research/test/trial-ledger-qa.test.ts @@ -0,0 +1,470 @@ +/** + * QA edge-case coverage for `@stock-bot/research` trial-ledger (T-84). + * + * Focus: the hand-written cross-window / date-merged correlation paths in + * `clusterDeflatedSharpe` must agree with the canonical `effectiveIndependentTrials` + * helper applied to an explicitly date-aligned, NaN-padded oracle; pair accounting must + * be complete; pre-built rows must be re-fenced; SQL must never interpolate values. + */ +import { describe, expect, it } from 'bun:test'; +import { + deflatedSharpeRatio, + effectiveIndependentTrials, + passesDsrGate, +} from '@stock-bot/calculations'; +import { + TrialLedgerError, + buildTrialRow, + clusterDeflatedSharpe, + loadClusterTrials, + recordTrials, + type BuiltTrialRow, + type TrialLedgerErrorCode, + type TrialLedgerExecutor, + type TrialRowInput, +} from '@stock-bot/research'; + +const VAULT_CUTOFF = '2025-05-01'; +const HASH_A = 'a'.repeat(64); + +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 gaussianSeries(seed: number, length: number, mean = 0.0003, std = 0.01): number[] { + const next = createSeededRng(seed); + const out = new Array(length); + for (let i = 0; i < length; i += 1) { + const u = Math.max(next(), 1e-12); + const v = next(); + out[i] = mean + std * Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); + } + return out; +} + +function businessDates(start: string, count: number): string[] { + const out: string[] = []; + const current = new Date(`${start}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 input(overrides: Partial): TrialRowInput { + return { + principalId: 'operator', + stage: 'signal_ic', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expressionHash: HASH_A, + sampleStart: '2020-01-02', + sampleEnd: '2020-01-10', + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: [0.01, -0.02, 0.015, 0.003], + ...overrides, + }; +} + +function toDbRow(row: BuiltTrialRow, trialId: number): Record { + return { + trial_id: String(trialId), + created_at: '2025-04-01T12:00:00.000000Z', + principal_id: row.principalId, + campaign_id: row.campaignId, + stage: row.stage, + universe_market: row.universeMarket, + horizon_bucket: row.horizonBucket, + hypothesis_id: row.hypothesisId, + expression_hash: row.expressionHash, + sample_start: row.sampleStart, + sample_end: row.sampleEnd, + n_obs: row.nObs, + sharpe_unann: row.sharpeUnann, + skewness: row.skewness, + kurtosis: row.kurtosis, + daily_series: row.dailySeries.map(v => Math.fround(v)), + }; +} + +function clusterExecutor(dbRows: readonly Record[]): { + executor: TrialLedgerExecutor; + calls: { text: string; params: readonly unknown[] | undefined }[]; +} { + const calls: { text: string; params: readonly unknown[] | undefined }[] = []; + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + calls.push({ text, params }); + if (text.includes('WHERE trial_id = $1')) { + const id = String(params?.[0]); + return { rows: dbRows.filter(r => r.trial_id === id) as unknown as readonly Row[] }; + } + return { rows: dbRows as unknown as readonly Row[] }; + }, + }; + return { executor, calls }; +} + +async function expectCode(fn: () => Promise | unknown, code: TrialLedgerErrorCode) { + let caught: unknown; + try { + await fn(); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(TrialLedgerError); + expect((caught as TrialLedgerError).code).toBe(code); +} + +/** Oracle: place each stored (float32) series on the global session grid, NaN elsewhere. */ +function alignOnGrid( + grid: readonly string[], + series: readonly number[], + dates: readonly string[] +): number[] { + const out = new Array(grid.length).fill(Number.NaN); + const index = new Map(grid.map((d, i) => [d, i] as const)); + for (let i = 0; i < dates.length; i += 1) { + out[index.get(dates[i] as string) as number] = Math.fround(series[i] as number); + } + return out; +} + +describe('trial-ledger QA: cross-window correlation agrees with effectiveIndependentTrials oracle', () => { + it('mixed dense windows (shared, prefix, suffix, staggered, disjoint) match the NaN-padded oracle', async () => { + // Arrange: 120-session grid; 7 trials on 5 distinct windows with a common factor. + const grid = businessDates('2020-01-02', 120); + const factor = gaussianSeries(11, 120, 0, 0.01); + const windows: [number, number][] = [ + [0, 119], + [0, 119], + [0, 79], + [40, 119], + [20, 99], + [100, 119], + [0, 9], + ]; + const rows: BuiltTrialRow[] = []; + const oracle: number[][] = []; + windows.forEach(([s, e], i) => { + const noise = gaussianSeries(100 + i, 120, 0, 0.01); + const full = factor.map((f, t) => 0.0002 + 0.7 * f + 0.5 * (noise[t] as number)); + const series = full.slice(s, e + 1); + const row = buildTrialRow( + input({ sampleStart: grid[s]!, sampleEnd: grid[e]!, dailySeries: series }) + ); + rows.push(row); + oracle.push(alignOnGrid(grid, row.dailySeries, grid.slice(s, e + 1))); + }); + const db = rows.map((r, i) => toDbRow(r, i + 1)); + const { executor } = clusterExecutor(db); + + // Act + const result = await clusterDeflatedSharpe(executor, { trialId: 1, sessionDates: grid }); + const expected = effectiveIndependentTrials(oracle); + + // Assert + expect(result.clusterSize).toBe(7); + expect(result.pairsUsed).toBe(expected.pairsUsed); + expect(result.pairsSkipped).toBe(expected.pairsSkipped); + expect(result.pairsUsed + result.pairsSkipped).toBe((7 * 6) / 2); + expect(result.meanCorrelation).not.toBeNull(); + expect(Math.abs(result.meanCorrelation! - expected.meanCorrelation!)).toBeLessThan(1e-9); + expect(Math.abs(result.effectiveTrials - expected.nHat)).toBeLessThan(1e-9); + // [100,119] vs [0,9] are disjoint and must be skipped, never fabricated. + expect(result.pairsSkipped).toBeGreaterThan(0); + + const directDsr = deflatedSharpeRatio({ + sharpeUnann: rows[0]!.sharpeUnann, + nObs: rows[0]!.nObs, + skewness: rows[0]!.skewness, + kurtosis: rows[0]!.kurtosis, + nHat: result.effectiveTrials, + clusterSharpes: rows.map(r => r.sharpeUnann), + }); + expect(result.dsr).not.toBeNull(); + expect(Math.abs(result.dsr! - directDsr!.dsr)).toBeLessThan(1e-9); + expect(result.passesGate).toBe(passesDsrGate(directDsr!.dsr)); + }); + + it('sparse explicit-date trials mixed with dense-grid trials match the date-aligned oracle', async () => { + // Arrange: two sparse signal trials omitting different dates, plus two dense trials. + const grid = businessDates('2021-03-01', 60); + const factor = gaussianSeries(21, 60, 0, 0.01); + const make = (seed: number) => { + const noise = gaussianSeries(seed, 60, 0, 0.01); + return factor.map((f, t) => 0.8 * f + 0.4 * (noise[t] as number)); + }; + const fullA = make(31); + const fullB = make(32); + const fullC = make(33); + const fullD = make(34); + const keepA = grid.map((_, i) => i).filter(i => i % 7 !== 3); + const keepB = grid.map((_, i) => i).filter(i => i >= 5 && i % 5 !== 1); + const datesA = keepA.map(i => grid[i]!); + const datesB = keepB.map(i => grid[i]!); + + const rowA = buildTrialRow( + input({ sampleStart: grid[0]!, sampleEnd: grid[59]!, dailySeries: keepA.map(i => fullA[i]!) }) + ); + const rowB = buildTrialRow( + input({ sampleStart: grid[5]!, sampleEnd: grid[59]!, dailySeries: keepB.map(i => fullB[i]!) }) + ); + const rowC = buildTrialRow( + input({ sampleStart: grid[0]!, sampleEnd: grid[59]!, dailySeries: fullC }) + ); + const rowD = buildTrialRow( + input({ sampleStart: grid[10]!, sampleEnd: grid[49]!, dailySeries: fullD.slice(10, 50) }) + ); + const db = [toDbRow(rowA, 1), toDbRow(rowB, 2), toDbRow(rowC, 3), toDbRow(rowD, 4)]; + const { executor } = clusterExecutor(db); + + // Act + const result = await clusterDeflatedSharpe(executor, { + trialId: 3, + sessionDates: grid, + observationDatesByTrialId: new Map([ + [1, datesA], + [2, datesB], + ]), + }); + const expected = effectiveIndependentTrials([ + alignOnGrid(grid, rowA.dailySeries, datesA), + alignOnGrid(grid, rowB.dailySeries, datesB), + alignOnGrid(grid, rowC.dailySeries, grid), + alignOnGrid(grid, rowD.dailySeries, grid.slice(10, 50)), + ]); + + // Assert + expect(result.pairsUsed).toBe(6); + expect(expected.pairsUsed).toBe(6); + expect(Math.abs(result.meanCorrelation! - expected.meanCorrelation!)).toBeLessThan(1e-9); + expect(Math.abs(result.effectiveTrials - expected.nHat)).toBeLessThan(1e-9); + }); + + it('accounts for every pair exactly once when unaligned trials are mixed in', async () => { + // Arrange: 3 dense trials on the grid + 2 trials whose length does not match the grid. + const grid = businessDates('2022-01-03', 40); + const dense = [0, 1, 2].map(i => + buildTrialRow( + input({ sampleStart: grid[0]!, sampleEnd: grid[39]!, dailySeries: gaussianSeries(50 + i, 40) }) + ) + ); + const unaligned = [0, 1].map(i => + buildTrialRow( + input({ sampleStart: grid[0]!, sampleEnd: grid[39]!, dailySeries: gaussianSeries(60 + i, 37) }) + ) + ); + const db = [...dense, ...unaligned].map((r, i) => toDbRow(r, i + 1)); + const { executor } = clusterExecutor(db); + + // Act + const result = await clusterDeflatedSharpe(executor, { trialId: 4, sessionDates: grid }); + + // Assert: 3 dense pairs used; 3*2 + 1 = 7 pairs skipped; total C(5,2) = 10. + expect(result.clusterSize).toBe(5); + expect(result.pairsUsed).toBe(3); + expect(result.pairsSkipped).toBe(7); + const denseOnly = effectiveIndependentTrials(dense.map(r => r.dailySeries.map(Math.fround))); + expect(Math.abs(result.meanCorrelation! - denseOnly.meanCorrelation!)).toBeLessThan(1e-9); + const expectedNHat = Math.max(1, 1 + 4 * (1 - Math.max(0, denseOnly.meanCorrelation!))); + expect(Math.abs(result.effectiveTrials - expectedNHat)).toBeLessThan(1e-9); + }); + + it('is deterministic: repeated calls on the same retained inputs return identical results', async () => { + const grid = businessDates('2020-06-01', 50); + const rows = [0, 1, 2, 3].map(i => + buildTrialRow( + input({ + sampleStart: grid[i * 5]!, + sampleEnd: grid[49]!, + dailySeries: gaussianSeries(900 + i, 50 - i * 5), + }) + ) + ); + const { executor } = clusterExecutor(rows.map((r, i) => toDbRow(r, i + 1))); + const first = await clusterDeflatedSharpe(executor, { trialId: 2, sessionDates: grid }); + const second = await clusterDeflatedSharpe(executor, { trialId: 2, sessionDates: grid }); + expect(second).toEqual(first); + }); + + it('rejects observation dates that disagree with the stored series or window before any math', async () => { + const grid = businessDates('2020-01-02', 10); + const row = buildTrialRow( + input({ sampleStart: grid[0]!, sampleEnd: grid[9]!, dailySeries: gaussianSeries(5, 10) }) + ); + const { executor } = clusterExecutor([toDbRow(row, 1), toDbRow(row, 2)]); + + await expectCode( + () => + clusterDeflatedSharpe(executor, { + trialId: 1, + observationDatesByTrialId: { '1': grid.slice(0, 9) }, + }), + 'INVALID_ROW' + ); + await expectCode( + () => + clusterDeflatedSharpe(executor, { + trialId: 1, + observationDatesByTrialId: { '1': businessDates('2019-12-30', 10) }, + }), + 'INVALID_SAMPLE_WINDOW' + ); + await expectCode( + () => + clusterDeflatedSharpe(executor, { + trialId: 1, + observationDatesByTrialId: new Map([ + [1, grid], + ['1', grid], + ]), + }), + 'INVALID_ROW' + ); + await expectCode( + () => clusterDeflatedSharpe(executor, { trialId: 1, sessionDates: [grid[1]!, grid[0]!] }), + 'INVALID_DATE' + ); + }); +}); + +describe('trial-ledger QA: writer re-fences pre-built rows and never interpolates values', () => { + it('re-applies the vault fence to a pre-built row whose window was edited after building', async () => { + const built = buildTrialRow(input({})); + const calls: unknown[] = []; + const executor: TrialLedgerExecutor = { + async query() { + calls.push(1); + return { rows: [] }; + }, + }; + + await expectCode( + () => recordTrials(executor, [built, { ...built, sampleEnd: VAULT_CUTOFF }]), + 'VAULT_FENCE_VIOLATION' + ); + await expectCode( + () => recordTrials(executor, [{ ...built, vaultCutoffDate: '2020-01-10' }]), + 'VAULT_FENCE_VIOLATION' + ); + await expectCode( + () => recordTrials(executor, [{ ...built, nObs: built.nObs + 1 }]), + 'INVALID_ROW' + ); + await expectCode( + () => recordTrials(executor, [{ ...built, sharpeUnann: built.sharpeUnann * 1.01 }]), + 'INVALID_ROW' + ); + expect(calls).toHaveLength(0); + }); + + it('keeps row order for mixed raw/pre-built batches and passes every value as a bind parameter', async () => { + // Arrange: hostile-looking but valid strings must never reach the SQL text. + const hashes = ['1', '2', '3'].map(c => c.repeat(64)); + const prebuilt = buildTrialRow(input({ expressionHash: hashes[1]! })); + const rows = [ + input({ expressionHash: hashes[0]!, sampleStart: '2020-01-03' }), + prebuilt, + input({ expressionHash: hashes[2]!, horizonBucket: 'position_10d_plus' }), + ]; + let seenText = ''; + let seenParams: readonly unknown[] = []; + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + seenText = text; + seenParams = params ?? []; + return { + rows: [ + { trial_id: '7', created_at: '2025-04-01T10:00:00.000001Z' }, + { trial_id: '8', created_at: '2025-04-01T10:00:00.000001Z' }, + { trial_id: '9', created_at: '2025-04-01T10:00:00.000001Z' }, + ] as unknown as readonly Row[], + }; + }, + }; + + // Act + const receipts = await recordTrials(executor, rows); + + // Assert + expect(receipts.map(r => r.trialId)).toEqual([7, 8, 9]); + expect(receipts[0]!.createdAt).toBe('2025-04-01T10:00:00.000001Z'); + expect(seenParams).toHaveLength(42); + expect(seenParams[6]).toBe(hashes[0]); + expect(seenParams[14 + 6]).toBe(hashes[1]); + expect(seenParams[28 + 6]).toBe(hashes[2]); + expect(seenParams[7]).toBe('2020-01-03'); + expect(seenParams[28 + 4]).toBe('position_10d_plus'); + expect(seenParams[14 + 10]).toBe(prebuilt.sharpeUnann); + for (const h of hashes) { + expect(seenText.includes(h)).toBe(false); + } + expect(seenText.includes('operator')).toBe(false); + expect(seenText.includes('2020-01-')).toBe(false); + expect(seenText).toContain('$42::real[]'); + expect(seenText.match(/INSERT INTO/g)).toHaveLength(1); + }); + + it('fails loudly when the database returns fewer receipts than rows inserted', async () => { + const executor: TrialLedgerExecutor = { + async query>() { + return { + rows: [{ trial_id: '1', created_at: '2025-04-01T10:00:00.000000Z' }] as unknown as readonly Row[], + }; + }, + }; + await expectCode( + () => + recordTrials(executor, [ + input({}), + input({ horizonBucket: 'position_10d_plus' }), + ]), + 'INVALID_ROW' + ); + }); +}); + +describe('trial-ledger QA: reader parses PostgreSQL wire shapes', () => { + it('parses text-form REAL[] arrays and rejects corrupted moments from the database', async () => { + const built = buildTrialRow(input({})); + const textRow = { + ...toDbRow(built, 3), + daily_series: `{${built.dailySeries.map(v => Math.fround(v)).join(',')}}`, + }; + const ok = await loadClusterTrials(clusterExecutor([textRow]).executor, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + expect(ok).toHaveLength(1); + expect(ok[0]!.dailySeries).toEqual(built.dailySeries.map(v => Math.fround(v))); + expect(ok[0]!.trialId).toBe(3); + + await expectCode( + () => + loadClusterTrials(clusterExecutor([{ ...textRow, sharpe_unann: 'NaN' }]).executor, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }), + 'INVALID_ROW' + ); + await expectCode( + () => + loadClusterTrials(clusterExecutor([{ ...textRow, daily_series: '{}' }]).executor, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }), + 'SERIES_TOO_SHORT' + ); + }); +}); diff --git a/libs/research/test/trial-ledger.test.ts b/libs/research/test/trial-ledger.test.ts new file mode 100644 index 00000000..7c44b86d --- /dev/null +++ b/libs/research/test/trial-ledger.test.ts @@ -0,0 +1,1078 @@ +import { createHash } from 'node:crypto'; +import { describe, expect, it } from 'bun:test'; +import { + deflatedSharpeRatio, + effectiveIndependentTrials, + trialMoments, +} from '@stock-bot/calculations'; +import { + HORIZON_BUCKETS, + MAX_TRIAL_BATCH_SIZE, + TRIAL_STAGES, + TrialLedgerError, + UNIVERSE_MARKETS, + buildTrialRow, + canonicalExpressionHash, + clusterDeflatedSharpe, + loadClusterTrials, + recordTrials, + type BuiltTrialRow, + type CanonicalExpressionInput, + type TrialLedgerErrorCode, + type TrialLedgerExecutor, + type TrialRowInput, +} from '@stock-bot/research'; +import { + HORIZON_BUCKETS as subpathHorizonBuckets, + MAX_TRIAL_BATCH_SIZE as subpathMaxBatchSize, + TRIAL_STAGES as subpathTrialStages, + TrialLedgerError as SubpathTrialLedgerError, + UNIVERSE_MARKETS as subpathUniverseMarkets, + buildTrialRow as subpathBuildTrialRow, + canonicalExpressionHash as subpathCanonicalExpressionHash, + clusterDeflatedSharpe as subpathClusterDeflatedSharpe, + loadClusterTrials as subpathLoadClusterTrials, + recordTrials as subpathRecordTrials, +} from '@stock-bot/research/trial-ledger'; + +const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const VALID_UUID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; +const VALID_HASH = 'a'.repeat(64); +const VAULT_CUTOFF = '2025-05-01'; + +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 createGaussianSampler(seed: number): () => number { + const next = createSeededRng(seed); + let spare: number | null = null; + return () => { + if (spare !== null) { + const value = spare; + spare = null; + return value; + } + let u = 0; + let v = 0; + while (u <= 1e-12) { + u = next(); + } + v = next(); + const mag = Math.sqrt(-2 * Math.log(u)); + const theta = 2 * Math.PI * v; + spare = mag * Math.sin(theta); + return mag * Math.cos(theta); + }; +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out = 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 makeSampleSeries(seed: number, length: number, mean = 0.0004, std = 0.01): number[] { + const gauss = createGaussianSampler(seed); + const out = new Array(length); + for (let i = 0; i < length; i += 1) { + out[i] = mean + std * gauss(); + } + return out; +} + +function makeValidInput(overrides: Partial = {}): TrialRowInput { + return { + principalId: 'operator', + campaignId: null, + hypothesisId: null, + stage: 'signal_ic', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expressionHash: VALID_HASH, + sampleStart: '2020-01-02', + sampleEnd: '2024-12-31', + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: [0.002, -0.001, 0.004, 0.0015, -0.0005, 0.003], + ...overrides, + }; +} + +function expectLedgerErrorCode(fn: () => unknown, expectedCode: TrialLedgerErrorCode): void { + try { + fn(); + } catch (error) { + expect(error).toBeInstanceOf(TrialLedgerError); + expect((error as TrialLedgerError).code).toBe(expectedCode); + return; + } + throw new Error(`Expected TrialLedgerError(${expectedCode}), but call succeeded`); +} + +async function expectAsyncLedgerErrorCode( + fn: () => Promise, + expectedCode: TrialLedgerErrorCode +): Promise { + try { + await fn(); + } catch (error) { + expect(error).toBeInstanceOf(TrialLedgerError); + expect((error as TrialLedgerError).code).toBe(expectedCode); + return; + } + throw new Error(`Expected async TrialLedgerError(${expectedCode}), but call succeeded`); +} + +interface FakeCall { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +function createFakeExecutor( + handler?: (text: string, params?: readonly unknown[]) => { rows: readonly Record[] } +): { executor: TrialLedgerExecutor; calls: FakeCall[] } { + const calls: FakeCall[] = []; + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + calls.push({ text, params }); + if (handler !== undefined) { + return handler(text, params) as { rows: readonly Row[] }; + } + return { rows: [] }; + }, + }; + return { executor, calls }; +} + +function builtRowToDbRow( + row: BuiltTrialRow, + trialId: number, + createdAt = '2025-04-01T12:00:00.000Z' +): Record { + return { + trial_id: String(trialId), + created_at: new Date(createdAt), + principal_id: row.principalId, + campaign_id: row.campaignId, + stage: row.stage, + universe_market: row.universeMarket, + horizon_bucket: row.horizonBucket, + hypothesis_id: row.hypothesisId, + expression_hash: row.expressionHash, + sample_start: row.sampleStart, + sample_end: row.sampleEnd, + n_obs: row.nObs, + sharpe_unann: row.sharpeUnann, + skewness: row.skewness, + kurtosis: row.kurtosis, + daily_series: row.dailySeries.map(v => Math.fround(v)), + }; +} + +describe('trial-ledger exports', () => { + it('exposes identical runtime exports from package root and subpath', () => { + expect(canonicalExpressionHash).toBe(subpathCanonicalExpressionHash); + expect(buildTrialRow).toBe(subpathBuildTrialRow); + expect(recordTrials).toBe(subpathRecordTrials); + expect(loadClusterTrials).toBe(subpathLoadClusterTrials); + expect(clusterDeflatedSharpe).toBe(subpathClusterDeflatedSharpe); + expect(TrialLedgerError).toBe(SubpathTrialLedgerError); + expect(TRIAL_STAGES).toBe(subpathTrialStages); + expect(UNIVERSE_MARKETS).toBe(subpathUniverseMarkets); + expect(HORIZON_BUCKETS).toBe(subpathHorizonBuckets); + expect(MAX_TRIAL_BATCH_SIZE).toBe(subpathMaxBatchSize); + }); +}); + +describe('canonicalExpressionHash', () => { + const baseInput: CanonicalExpressionInput = { + expression: 'rank(ret_20d) - zscore(vol_20d)', + params: { lookback: 20, winsor: 0.01, nested: { b: 2, a: 1 } }, + universe: { market: 'US_EQ', minAdvUsd: 5_000_000 }, + sampleStart: '2018-01-02', + sampleEnd: '2024-12-31', + horizon: '5d', + }; + + it('is invariant to top-level/nested key ordering, undefined keys, -0, and expression whitespace', () => { + const h1 = canonicalExpressionHash(baseInput); + expect(h1).toMatch(/^[0-9a-f]{64}$/); + + const reordered: CanonicalExpressionInput = { + horizon: '5d', + sampleEnd: '2024-12-31', + sampleStart: '2018-01-02', + universe: { minAdvUsd: 5_000_000, market: 'US_EQ', ignored: undefined }, + params: { nested: { a: 1, b: 2, omitMe: undefined }, winsor: 0.01, lookback: 20 }, + expression: ' rank(ret_20d)\n\t - zscore(vol_20d) ', + }; + expect(canonicalExpressionHash(reordered)).toBe(h1); + + const negZero = canonicalExpressionHash({ + ...baseInput, + params: { zero: -0 }, + }); + const posZero = canonicalExpressionHash({ + ...baseInput, + params: { zero: 0 }, + }); + expect(negZero).toBe(posZero); + }); + + it('changes when any field or nested value changes', () => { + const base = canonicalExpressionHash(baseInput); + expect(canonicalExpressionHash({ ...baseInput, expression: 'rank(ret_10d) - zscore(vol_20d)' })).not.toBe(base); + expect( + canonicalExpressionHash({ + ...baseInput, + params: { lookback: 21, winsor: 0.01, nested: { b: 2, a: 1 } }, + }) + ).not.toBe(base); + expect( + canonicalExpressionHash({ + ...baseInput, + universe: { market: 'CA_EQ', minAdvUsd: 5_000_000 }, + }) + ).not.toBe(base); + expect(canonicalExpressionHash({ ...baseInput, sampleStart: '2018-01-03' })).not.toBe(base); + expect(canonicalExpressionHash({ ...baseInput, sampleEnd: '2024-12-30' })).not.toBe(base); + expect(canonicalExpressionHash({ ...baseInput, horizon: '20d' })).not.toBe(base); + }); + + it('matches node:crypto SHA-256 bit-for-bit across ASCII, UTF-8, and block-boundary lengths', () => { + const cases: CanonicalExpressionInput[] = [ + baseInput, + { + expression: 'α_momentum + 収益率 🚀', + params: { label: 'café', tags: ['日本語', 'Ελληνικά'] }, + universe: 'US_EQ', + sampleStart: '2020-01-02', + sampleEnd: '2020-12-31', + horizon: '1d', + }, + // Exercise SHA-256 padding boundaries (55, 56, 63, 64, 65 bytes of payload variation) + ...[1, 8, 15, 16, 17, 63, 64, 65, 128].map(padLen => ({ + expression: 'x'.repeat(padLen), + params: null, + universe: 'FX', + sampleStart: '2021-01-04', + sampleEnd: '2021-06-30', + horizon: 5, + })), + ]; + + for (const input of cases) { + const canonicalJson = JSON.stringify({ + expression: input.expression.trim().replace(/\s+/g, ' '), + horizon: input.horizon, + params: + input.params !== null && typeof input.params === 'object' && !Array.isArray(input.params) + ? Object.fromEntries( + Object.entries(input.params as Record) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([k, v]) => [ + k, + v !== null && typeof v === 'object' && !Array.isArray(v) + ? Object.fromEntries( + Object.entries(v as Record).sort(([a], [b]) => + a < b ? -1 : a > b ? 1 : 0 + ) + ) + : v, + ]) + ) + : input.params, + sampleEnd: input.sampleEnd, + sampleStart: input.sampleStart, + universe: + input.universe !== null && + typeof input.universe === 'object' && + !Array.isArray(input.universe) + ? Object.fromEntries( + Object.entries(input.universe as Record).sort(([a], [b]) => + a < b ? -1 : a > b ? 1 : 0 + ) + ) + : input.universe, + }); + + const expected = createHash('sha256').update(canonicalJson, 'utf8').digest('hex'); + expect(canonicalExpressionHash(input)).toBe(expected); + } + }); + + it('rejects non-JSON values, cycles, malformed dates, and inverted sample windows', () => { + expectLedgerErrorCode( + () => canonicalExpressionHash({ ...baseInput, expression: ' ' }), + 'INVALID_EXPRESSION_INPUT' + ); + expectLedgerErrorCode( + () => canonicalExpressionHash({ ...baseInput, params: { bad: Number.NaN } }), + 'INVALID_EXPRESSION_INPUT' + ); + expectLedgerErrorCode( + () => canonicalExpressionHash({ ...baseInput, params: { bad: Number.POSITIVE_INFINITY } }), + 'INVALID_EXPRESSION_INPUT' + ); + expectLedgerErrorCode( + () => canonicalExpressionHash({ ...baseInput, params: { bad: 1n } }), + 'INVALID_EXPRESSION_INPUT' + ); + expectLedgerErrorCode( + () => canonicalExpressionHash({ ...baseInput, params: { bad: () => 1 } }), + 'INVALID_EXPRESSION_INPUT' + ); + expectLedgerErrorCode( + () => canonicalExpressionHash({ ...baseInput, params: { bad: Symbol('x') } }), + 'INVALID_EXPRESSION_INPUT' + ); + expectLedgerErrorCode( + () => canonicalExpressionHash({ ...baseInput, params: new Map([['a', 1]]) }), + 'INVALID_EXPRESSION_INPUT' + ); + expectLedgerErrorCode( + () => canonicalExpressionHash({ ...baseInput, params: [undefined] }), + 'INVALID_EXPRESSION_INPUT' + ); + + const cyclic: Record = {}; + cyclic.self = cyclic; + expectLedgerErrorCode( + () => canonicalExpressionHash({ ...baseInput, params: cyclic }), + 'INVALID_EXPRESSION_INPUT' + ); + + expectLedgerErrorCode( + () => canonicalExpressionHash({ ...baseInput, sampleStart: '2026-02-29' }), + 'INVALID_DATE' + ); + expectLedgerErrorCode( + () => + canonicalExpressionHash({ + ...baseInput, + sampleStart: '2024-06-02', + sampleEnd: '2024-06-01', + }), + 'INVALID_SAMPLE_WINDOW' + ); + }); +}); + +describe('buildTrialRow', () => { + it('computes moments identical to trialMoments and accepts operator and agent principals', () => { + const series = [0.012, -0.004, 0.007, 0.003, -0.009, 0.015, 0.002, -0.001]; + const expected = trialMoments(series); + expect(expected).not.toBeNull(); + + const row = buildTrialRow( + makeValidInput({ + principalId: VALID_AGENT_PRINCIPAL, + campaignId: VALID_UUID.toUpperCase(), + hypothesisId: VALID_UUID, + dailySeries: series, + }) + ); + + expect(row.principalId).toBe(VALID_AGENT_PRINCIPAL); + expect(row.campaignId).toBe(VALID_UUID); + expect(row.hypothesisId).toBe(VALID_UUID); + expect(row.nObs).toBe(expected!.nObs); + expect(row.sharpeUnann).toBe(expected!.sharpeUnann); + expect(row.skewness).toBe(expected!.skewness); + expect(row.kurtosis).toBe(expected!.kurtosis); + expect(Object.isFrozen(row)).toBe(true); + expect(Object.isFrozen(row.dailySeries)).toBe(true); + }); + + it('rejects every invalid field and vault fence violation with the expected typed error code', () => { + const invalidCases: readonly [Partial, TrialLedgerErrorCode][] = [ + [{ dailySeries: [] }, 'SERIES_TOO_SHORT'], + [{ dailySeries: [0.01] }, 'SERIES_TOO_SHORT'], + [{ dailySeries: [0.01, Number.NaN] }, 'INVALID_SERIES_VALUE'], + [{ dailySeries: [0.01, Number.POSITIVE_INFINITY] }, 'INVALID_SERIES_VALUE'], + [{ dailySeries: [0.01, Number.NEGATIVE_INFINITY] }, 'INVALID_SERIES_VALUE'], + [{ dailySeries: [0.01, 1e40] }, 'INVALID_SERIES_VALUE'], + [{ dailySeries: [0.01, 1e-50] }, 'INVALID_SERIES_VALUE'], + [{ dailySeries: [0.01, 0.01, 0.01] }, 'ZERO_VARIANCE_SERIES'], + [{ dailySeries: [1.0, 1.0 + 1e-12, 1.0 + 2e-12] }, 'ZERO_VARIANCE_SERIES'], + [{ sampleStart: '2024-05-02', sampleEnd: '2024-05-01' }, 'INVALID_SAMPLE_WINDOW'], + [{ sampleStart: '2026-02-29' }, 'INVALID_DATE'], + [{ sampleEnd: '2024-12-31T00:00:00Z' }, 'INVALID_DATE'], + [{ vaultCutoffDate: '2025-02-29' }, 'INVALID_DATE'], + [{ principalId: 'service' }, 'INVALID_PRINCIPAL'], + [{ principalId: '' }, 'INVALID_PRINCIPAL'], + [{ principalId: 'agent:not-a-uuid' }, 'INVALID_PRINCIPAL'], + [{ principalId: 'agent:00000000-0000-0000-0000-000000000000' }, 'INVALID_PRINCIPAL'], + [{ principalId: 'agent:11111111-2222-4333-8444-55555555555A' }, 'INVALID_PRINCIPAL'], + [{ campaignId: 'not-a-uuid' }, 'INVALID_UUID'], + [{ hypothesisId: '1234' }, 'INVALID_UUID'], + [{ stage: 'live_trade' as TrialRowInput['stage'] }, 'INVALID_STAGE'], + [{ universeMarket: 'US' as TrialRowInput['universeMarket'] }, 'INVALID_UNIVERSE_MARKET'], + [{ horizonBucket: 'weekly' as TrialRowInput['horizonBucket'] }, 'INVALID_HORIZON_BUCKET'], + [{ expressionHash: 'A'.repeat(64) }, 'INVALID_EXPRESSION_HASH'], + [{ expressionHash: 'a'.repeat(63) }, 'INVALID_EXPRESSION_HASH'], + [{ expressionHash: 'g'.repeat(64) }, 'INVALID_EXPRESSION_HASH'], + [{ sampleEnd: VAULT_CUTOFF }, 'VAULT_FENCE_VIOLATION'], + [{ sampleEnd: '2025-05-02' }, 'VAULT_FENCE_VIOLATION'], + [{ sampleStart: VAULT_CUTOFF, sampleEnd: '2025-06-01' }, 'VAULT_FENCE_VIOLATION'], + ]; + + for (const [overrides, expectedCode] of invalidCases) { + expectLedgerErrorCode(() => buildTrialRow(makeValidInput(overrides)), expectedCode); + } + }); +}); + +describe('recordTrials', () => { + it('returns [] and issues zero SQL for an empty batch', async () => { + const { executor, calls } = createFakeExecutor(); + const receipts = await recordTrials(executor, []); + expect(receipts).toEqual([]); + expect(calls).toHaveLength(0); + }); + + it('validates all rows upfront and sends zero SQL when any row is invalid or batch exceeds cap', async () => { + const { executor, calls } = createFakeExecutor(); + + const invalidOverrides: readonly [Partial, TrialLedgerErrorCode][] = [ + [{ dailySeries: [0.01] }, 'SERIES_TOO_SHORT'], + [{ dailySeries: [0.01, Number.NaN] }, 'INVALID_SERIES_VALUE'], + [{ dailySeries: [0.01, 1e40] }, 'INVALID_SERIES_VALUE'], + [{ dailySeries: [0.01, 1e-50] }, 'INVALID_SERIES_VALUE'], + [{ dailySeries: [0.01, 0.01] }, 'ZERO_VARIANCE_SERIES'], + [{ sampleStart: '2024-06-02', sampleEnd: '2024-06-01' }, 'INVALID_SAMPLE_WINDOW'], + [{ principalId: 'bad' }, 'INVALID_PRINCIPAL'], + [{ expressionHash: 'bad' }, 'INVALID_EXPRESSION_HASH'], + [{ sampleEnd: VAULT_CUTOFF }, 'VAULT_FENCE_VIOLATION'], + ]; + + for (const [overrides, expectedCode] of invalidOverrides) { + await expectAsyncLedgerErrorCode( + () => recordTrials(executor, [makeValidInput(), makeValidInput(overrides)]), + expectedCode + ); + } + + // Forged pre-built row violating vault fence must also be rejected with zero SQL. + const validBuilt = buildTrialRow(makeValidInput()); + const forgedBuilt: BuiltTrialRow = { ...validBuilt, sampleEnd: VAULT_CUTOFF }; + await expectAsyncLedgerErrorCode( + () => recordTrials(executor, [validBuilt, forgedBuilt]), + 'VAULT_FENCE_VIOLATION' + ); + + // Pre-built row whose dailySeries was replaced with a different same-length vector while + // retaining stale moments must be rejected with zero SQL. + const replacementSeries = makeSampleSeries(404, validBuilt.dailySeries.length, -0.002, 0.02); + const staleMomentsBuilt: BuiltTrialRow = { + ...validBuilt, + expressionHash: 'f'.repeat(64), + dailySeries: replacementSeries, + }; + await expectAsyncLedgerErrorCode( + () => recordTrials(executor, [validBuilt, staleMomentsBuilt]), + 'INVALID_ROW' + ); + + // Pre-built row whose dailySeries collapses to constant at float32 REAL precision must be + // rejected with ZERO_VARIANCE_SERIES and zero SQL. + const float32CollapsedSeries = [1.0, 1.0 + 1e-12, 1.0 + 2e-12]; + const float32CollapsedMoments = trialMoments(float32CollapsedSeries)!; + const float32CollapsedBuilt: BuiltTrialRow = { + ...validBuilt, + nObs: float32CollapsedMoments.nObs, + sharpeUnann: float32CollapsedMoments.sharpeUnann, + skewness: float32CollapsedMoments.skewness, + kurtosis: float32CollapsedMoments.kurtosis, + dailySeries: float32CollapsedSeries, + }; + await expectAsyncLedgerErrorCode( + () => recordTrials(executor, [validBuilt, float32CollapsedBuilt]), + 'ZERO_VARIANCE_SERIES' + ); + + // Oversized batch rejected before any SQL. + const oversized = new Array(MAX_TRIAL_BATCH_SIZE + 1).fill(validBuilt); + await expectAsyncLedgerErrorCode(() => recordTrials(executor, oversized), 'BATCH_TOO_LARGE'); + + expect(calls).toHaveLength(0); + }); + + it('executes one parameterised multi-row INSERT for a 3-horizon batch', async () => { + const { executor, calls } = createFakeExecutor(() => ({ + rows: [ + { trial_id: '101', created_at: new Date('2025-04-01T10:00:00.000Z') }, + { trial_id: '102', created_at: new Date('2025-04-01T10:00:00.001Z') }, + { trial_id: '103', created_at: new Date('2025-04-01T10:00:00.002Z') }, + ], + })); + + const horizons = ['1d', '5d', '20d'] as const; + const batch = horizons.map((horizon, idx) => + buildTrialRow( + makeValidInput({ + horizonBucket: horizon === '20d' ? 'position_10d_plus' : 'swing_1_10d', + expressionHash: canonicalExpressionHash({ + expression: 'rank(ret_20d)', + params: { lookback: 20 }, + universe: 'US_EQ', + sampleStart: '2020-01-02', + sampleEnd: '2024-12-31', + horizon, + }), + dailySeries: makeSampleSeries(100 + idx, 10), + }) + ) + ); + + const receipts = await recordTrials(executor, batch); + expect(calls).toHaveLength(1); + expect(calls[0]!.text).toContain('INSERT INTO trial_ledger'); + expect(calls[0]!.text).toContain('RETURNING trial_id,'); + expect(calls[0]!.text).toContain('AS created_at'); + expect(calls[0]!.params).toHaveLength(3 * 14); + expect(receipts).toEqual([ + { trialId: 101, createdAt: '2025-04-01T10:00:00.000Z' }, + { trialId: 102, createdAt: '2025-04-01T10:00:00.001Z' }, + { trialId: 103, createdAt: '2025-04-01T10:00:00.002Z' }, + ]); + }); + + it('preserves PostgreSQL microsecond UTC timestamps across Z and explicit offsets in receipts and asOf queries', async () => { + const microTs = '2025-04-01T10:00:00.123456Z'; + const rowAtBoundary = builtRowToDbRow(buildTrialRow(makeValidInput()), 7, microTs); + rowAtBoundary.created_at = microTs; + const { executor, calls } = createFakeExecutor((text, params) => { + if (text.startsWith('INSERT INTO trial_ledger')) { + return { rows: [{ trial_id: '7', created_at: microTs }] }; + } + const asOfParam = params?.[2] as string | undefined; + if (asOfParam !== undefined && microTs <= asOfParam) { + return { rows: [rowAtBoundary] }; + } + return { rows: [] }; + }); + + const receipts = await recordTrials(executor, [makeValidInput()]); + expect(receipts).toEqual([{ trialId: 7, createdAt: microTs }]); + + const zRows = await loadClusterTrials(executor, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + asOf: receipts[0]!.createdAt, + }); + const plusZeroRows = await loadClusterTrials(executor, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + asOf: '2025-04-01T10:00:00.123456+00:00', + }); + const plusTwoRows = await loadClusterTrials(executor, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + asOf: '2025-04-01T12:00:00.123456+02:00', + }); + + expect(calls).toHaveLength(4); + expect(calls[1]!.params).toEqual(['US_EQ', 'swing_1_10d', microTs]); + expect(calls[2]!.params).toEqual(['US_EQ', 'swing_1_10d', microTs]); + expect(calls[3]!.params).toEqual(['US_EQ', 'swing_1_10d', microTs]); + expect(zRows).toHaveLength(1); + expect(plusZeroRows).toHaveLength(1); + expect(plusTwoRows).toHaveLength(1); + expect(plusZeroRows[0]!.trialId).toBe(zRows[0]!.trialId); + expect(plusTwoRows[0]!.trialId).toBe(zRows[0]!.trialId); + }); +}); + +describe('loadClusterTrials and clusterDeflatedSharpe', () => { + it('validates cluster query inputs before issuing SQL and supports asOf normalization', async () => { + const { executor, calls } = createFakeExecutor(() => ({ rows: [] })); + + await expectAsyncLedgerErrorCode( + () => + loadClusterTrials(executor, { + universeMarket: 'EU_EQ' as 'US_EQ', + horizonBucket: 'swing_1_10d', + }), + 'INVALID_UNIVERSE_MARKET' + ); + await expectAsyncLedgerErrorCode( + () => + loadClusterTrials(executor, { + universeMarket: 'US_EQ', + horizonBucket: 'daily' as 'swing_1_10d', + }), + 'INVALID_HORIZON_BUCKET' + ); + await expectAsyncLedgerErrorCode( + () => + loadClusterTrials(executor, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + asOf: '2025-04-01T12:00:00', // naive datetime rejected + }), + 'INVALID_DATE' + ); + expect(calls).toHaveLength(0); + + await loadClusterTrials(executor, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + asOf: '2025-04-01', + }); + expect(calls).toHaveLength(1); + expect(calls[0]!.text).toContain('AND created_at <= $3::timestamptz'); + expect(calls[0]!.params).toEqual(['US_EQ', 'swing_1_10d', '2025-04-01T23:59:59.999Z']); + }); + + it('computes exact N-hat and DSR for proven shared-grid prefix/suffix/disjoint windows and sparse observation-date alignment', async () => { + const baseSeries = makeSampleSeries(701, 100, 0.001, 0.01); + const twinSeries = baseSeries.map((v, i) => v * 0.98 + (i % 2 === 0 ? 0.0005 : -0.0005)); + const calendar100 = makeBusinessDates('2020-01-02', 100); + + // 1. Same-start, different-end (prefix overlap) with proven sessionDates grid + const rowPrefixA = buildTrialRow( + makeValidInput({ + sampleStart: calendar100[0]!, + sampleEnd: calendar100[99]!, + dailySeries: baseSeries, + }) + ); + const rowPrefixB = buildTrialRow( + makeValidInput({ + sampleStart: calendar100[0]!, + sampleEnd: calendar100[69]!, + dailySeries: twinSeries.slice(0, 70), + }) + ); + + const dbPrefix = [builtRowToDbRow(rowPrefixA, 1), builtRowToDbRow(rowPrefixB, 2)]; + const prefixExec = createFakeExecutor(text => + text.includes('WHERE trial_id = $1') ? { rows: [dbPrefix[0]!] } : { rows: dbPrefix } + ); + const prefixRes = await clusterDeflatedSharpe(prefixExec.executor, { + trialId: 1, + sessionDates: calendar100, + }); + expect(prefixRes.pairsUsed).toBe(1); + expect(prefixRes.pairsSkipped).toBe(0); + expect(prefixRes.meanCorrelation).not.toBeNull(); + expect(prefixRes.meanCorrelation!).toBeGreaterThan(0.95); + expect(prefixRes.effectiveTrials).toBeLessThan(1.1); + + // Without proven sessionDates or observationDatesByTrialId, pairs are skipped conservatively. + const unalignedRes = await clusterDeflatedSharpe(prefixExec.executor, { trialId: 1 }); + expect(unalignedRes.pairsUsed).toBe(0); + expect(unalignedRes.pairsSkipped).toBe(1); + expect(unalignedRes.meanCorrelation).toBeNull(); + expect(unalignedRes.effectiveTrials).toBe(2); + + // 2. Same-end, different-start (suffix overlap) with proven sessionDates grid + const rowSuffixA = buildTrialRow( + makeValidInput({ + sampleStart: calendar100[0]!, + sampleEnd: calendar100[99]!, + dailySeries: baseSeries, + }) + ); + const rowSuffixB = buildTrialRow( + makeValidInput({ + sampleStart: calendar100[30]!, + sampleEnd: calendar100[99]!, + dailySeries: twinSeries.slice(30), + }) + ); + const dbSuffix = [builtRowToDbRow(rowSuffixA, 10), builtRowToDbRow(rowSuffixB, 11)]; + const suffixExec = createFakeExecutor(text => + text.includes('WHERE trial_id = $1') ? { rows: [dbSuffix[0]!] } : { rows: dbSuffix } + ); + const suffixRes = await clusterDeflatedSharpe(suffixExec.executor, { + trialId: 10, + sessionDates: calendar100, + }); + expect(suffixRes.pairsUsed).toBe(1); + expect(suffixRes.pairsSkipped).toBe(0); + expect(suffixRes.meanCorrelation!).toBeGreaterThan(0.95); + + // 3. Disjoint windows on a shared calendar -> pairsSkipped > 0, meanCorrelation === null, effectiveTrials === clusterSize + const calendar220 = makeBusinessDates('2019-01-02', 220); + const rowDisjointA = buildTrialRow( + makeValidInput({ + sampleStart: calendar220[0]!, + sampleEnd: calendar220[99]!, + dailySeries: baseSeries, + }) + ); + const rowDisjointB = buildTrialRow( + makeValidInput({ + sampleStart: calendar220[120]!, + sampleEnd: calendar220[219]!, + dailySeries: twinSeries, + }) + ); + const dbDisjoint = [builtRowToDbRow(rowDisjointA, 20), builtRowToDbRow(rowDisjointB, 21)]; + const disjointExec = createFakeExecutor(text => + text.includes('WHERE trial_id = $1') ? { rows: [dbDisjoint[0]!] } : { rows: dbDisjoint } + ); + const disjointRes = await clusterDeflatedSharpe(disjointExec.executor, { + trialId: 20, + sessionDates: calendar220, + }); + expect(disjointRes.pairsUsed).toBe(0); + expect(disjointRes.pairsSkipped).toBe(1); + expect(disjointRes.meanCorrelation).toBeNull(); + expect(disjointRes.effectiveTrials).toBe(2); + + const directDsr = deflatedSharpeRatio({ + sharpeUnann: rowDisjointA.sharpeUnann, + nObs: rowDisjointA.nObs, + skewness: rowDisjointA.skewness, + kurtosis: rowDisjointA.kurtosis, + nHat: 2, + clusterSharpes: [rowDisjointA.sharpeUnann, rowDisjointB.sharpeUnann], + }); + expect(disjointRes.dsr).toBeCloseTo(directDsr!.dsr, 12); + + // 4. Regression: equal-length sparse signal_ic vectors with the same [sampleStart, sampleEnd] + // where trial 30 omits Tuesday and trial 31 omits Thursday. + // Values are constructed so naive index pairing yields +1.0, while true date pairing on + // [Mon, Wed, Fri] yields -1.0. + const weekDates = ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04', '2024-01-05']; + const datesSkipTue = ['2024-01-01', '2024-01-03', '2024-01-04', '2024-01-05']; + const datesSkipThu = ['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-05']; + // Index values: A=[+0.02, -0.02, +0.01, -0.01] on [Mon, Wed, Thu, Fri] + // B=[+0.02, -0.02, +0.01, -0.01] on [Mon, Tue, Wed, Fri] + // Naive index pairing: identical vectors -> rho = +1.0! + // True date pairing on [Mon, Wed, Fri]: A=[+0.02, -0.02, -0.01], B=[+0.02, +0.01, -0.01] -> rho != +1.0. + // Let's make true date pairing strongly negative on [Mon, Wed, Fri]: + // Mon: A=-0.02, B=+0.02; Wed: A=+0.02, B=-0.02; Fri: A=0.00, B=0.00 -> exact rho = -1.0! + // And put Tue (B only) = +0.02, Thu (A only) = -0.02 so index-aligned A=[-0.02, +0.02, -0.02, 0.00] + // vs B=[+0.02, +0.02, -0.02, 0.00] has positive index correlation (+0.333) while true date correlation is -1.0! + const sparseA = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: weekDates[0]!, + sampleEnd: weekDates[4]!, + dailySeries: [-0.02, 0.02, -0.02, 0.0], + }) + ); + const sparseB = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: weekDates[0]!, + sampleEnd: weekDates[4]!, + dailySeries: [0.02, 0.02, -0.02, 0.0], + }) + ); + const dbSparse = [builtRowToDbRow(sparseA, 30), builtRowToDbRow(sparseB, 31)]; + const sparseExec = createFakeExecutor(text => + text.includes('WHERE trial_id = $1') ? { rows: [dbSparse[0]!] } : { rows: dbSparse } + ); + + // Without observation dates (even when the 5-day session calendar is given), 4 !== 5 proves + // the vectors are sparse -> skip pair rather than inventing an index-aligned correlation. + const sparseNoDatesRes = await clusterDeflatedSharpe(sparseExec.executor, { + trialId: 30, + sessionDates: weekDates, + }); + expect(sparseNoDatesRes.pairsUsed).toBe(0); + expect(sparseNoDatesRes.pairsSkipped).toBe(1); + expect(sparseNoDatesRes.meanCorrelation).toBeNull(); + expect(sparseNoDatesRes.effectiveTrials).toBe(2); + + // With explicit observation dates, Mon/Wed/Fri align accurately (rho = -1.0, never mis-pairing Wed with Tue). + const sparseAlignedRes = await clusterDeflatedSharpe(sparseExec.executor, { + trialId: 30, + observationDatesByTrialId: { + 30: datesSkipTue, + 31: datesSkipThu, + }, + }); + expect(sparseAlignedRes.pairsUsed).toBe(1); + expect(sparseAlignedRes.pairsSkipped).toBe(0); + expect(sparseAlignedRes.meanCorrelation).not.toBeNull(); + expect(sparseAlignedRes.meanCorrelation!).toBeCloseTo(-1.0, 6); + expect(sparseAlignedRes.effectiveTrials).toBe(2); + + // 5. Regression: clipped sessionDates calendar whose count matches a sparse older trial. + // Calendar covers only Wed–Fri; older trial spans Tue–Fri and skipped Wed (3 entries). + const wedToFri = ['2024-01-03', '2024-01-04', '2024-01-05']; + const targetWedFri = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: '2024-01-03', + sampleEnd: '2024-01-05', + dailySeries: [0.01, -0.02, 0.03], + }) + ); + const olderSparseTueFri = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: '2024-01-02', + sampleEnd: '2024-01-05', + dailySeries: [0.01, -0.02, 0.03], + }) + ); + const dbClippedStart = [ + builtRowToDbRow(targetWedFri, 40), + builtRowToDbRow(olderSparseTueFri, 41), + ]; + const clippedStartExec = createFakeExecutor(text => + text.includes('WHERE trial_id = $1') + ? { rows: [dbClippedStart[0]!] } + : { rows: dbClippedStart } + ); + const clippedStartRes = await clusterDeflatedSharpe(clippedStartExec.executor, { + trialId: 40, + sessionDates: wedToFri, + }); + expect(clippedStartRes.pairsUsed).toBe(0); + expect(clippedStartRes.pairsSkipped).toBe(1); + expect(clippedStartRes.meanCorrelation).toBeNull(); + expect(clippedStartRes.effectiveTrials).toBe(2); + + // Symmetric regression: calendar clipped at the end (Tue–Thu) vs a Tue–Fri sparse trial. + const tueToThu = ['2024-01-02', '2024-01-03', '2024-01-04']; + const targetTueThu = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: '2024-01-02', + sampleEnd: '2024-01-04', + dailySeries: [0.01, -0.02, 0.03], + }) + ); + const dbClippedEnd = [ + builtRowToDbRow(targetTueThu, 42), + builtRowToDbRow(olderSparseTueFri, 43), + ]; + const clippedEndExec = createFakeExecutor(text => + text.includes('WHERE trial_id = $1') ? { rows: [dbClippedEnd[0]!] } : { rows: dbClippedEnd } + ); + const clippedEndRes = await clusterDeflatedSharpe(clippedEndExec.executor, { + trialId: 42, + sessionDates: tueToThu, + }); + expect(clippedEndRes.pairsUsed).toBe(0); + expect(clippedEndRes.pairsSkipped).toBe(1); + expect(clippedEndRes.meanCorrelation).toBeNull(); + expect(clippedEndRes.effectiveTrials).toBe(2); + + // 6. Regression: cross-window Pearson skips pairs whose overlap slice is constant even when + // floating-point rounding in the prefix-sum mean leaves identical nonzero residuals. + const constOverlapA = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: weekDates[0]!, + sampleEnd: weekDates[3]!, + dailySeries: [0, 0.1, 0.1, 0.1], + }) + ); + const constOverlapB = buildTrialRow( + makeValidInput({ + stage: 'signal_ic', + sampleStart: weekDates[1]!, + sampleEnd: weekDates[4]!, + dailySeries: [0.1, 0.1, 0.1, -0.1], + }) + ); + const dbConstOverlap = [ + builtRowToDbRow(constOverlapA, 50), + builtRowToDbRow(constOverlapB, 51), + ]; + const constOverlapExec = createFakeExecutor(text => + text.includes('WHERE trial_id = $1') + ? { rows: [dbConstOverlap[0]!] } + : { rows: dbConstOverlap } + ); + const constOverlapRes = await clusterDeflatedSharpe(constOverlapExec.executor, { + trialId: 50, + sessionDates: weekDates, + }); + expect(constOverlapRes.pairsUsed).toBe(0); + expect(constOverlapRes.pairsSkipped).toBe(1); + expect(constOverlapRes.meanCorrelation).toBeNull(); + expect(constOverlapRes.effectiveTrials).toBe(2); + }); + + it('rejects invalid trialId with zero SQL and throws TRIAL_NOT_FOUND when absent or excluded by asOf', async () => { + const { executor, calls } = createFakeExecutor(() => ({ rows: [] })); + await expectAsyncLedgerErrorCode( + () => clusterDeflatedSharpe(executor, { trialId: 0 }), + 'INVALID_TRIAL_ID' + ); + await expectAsyncLedgerErrorCode( + () => clusterDeflatedSharpe(executor, { trialId: -5 }), + 'INVALID_TRIAL_ID' + ); + await expectAsyncLedgerErrorCode( + () => clusterDeflatedSharpe(executor, { trialId: 'abc' }), + 'INVALID_TRIAL_ID' + ); + expect(calls).toHaveLength(0); + + await expectAsyncLedgerErrorCode( + () => clusterDeflatedSharpe(executor, { trialId: 999 }), + 'TRIAL_NOT_FOUND' + ); + + const row = buildTrialRow(makeValidInput()); + const dbRow = builtRowToDbRow(row, 42, '2025-04-10T00:00:00.000Z'); + const asOfExec = createFakeExecutor(text => + text.includes('WHERE trial_id = $1') ? { rows: [dbRow] } : { rows: [] } + ); + await expectAsyncLedgerErrorCode( + () => + clusterDeflatedSharpe(asOfExec.executor, { + trialId: 42, + asOf: '2025-04-01T00:00:00Z', + }), + 'TRIAL_NOT_FOUND' + ); + }); +}); + +describe('trial-ledger in-memory benchmark', () => { + it('benchmarks 200 trials x 5,000 daily observations for shared-window and staggered-window clusters', async () => { + const trialCount = 200; + const obsPerTrial = 5_000; + const gauss = createGaussianSampler(20260403); + const sharedSessionDates = makeBusinessDates('2005-01-03', obsPerTrial); + const sharedStart = sharedSessionDates[0]!; + const sharedEnd = sharedSessionDates[obsPerTrial - 1]!; + + // Pre-generate common factor + idiosyncratic series outside the timed region. + const common = new Array(obsPerTrial); + for (let t = 0; t < obsPerTrial; t += 1) { + common[t] = 0.0003 + 0.008 * gauss(); + } + const rawInputs: TrialRowInput[] = new Array(trialCount); + for (let k = 0; k < trialCount; k += 1) { + const series = new Array(obsPerTrial); + const loading = 0.35 + (k % 5) * 0.05; + const noiseScale = Math.sqrt(1 - loading * loading) * 0.01; + for (let t = 0; t < obsPerTrial; t += 1) { + series[t] = loading * (common[t] as number) + noiseScale * gauss(); + } + rawInputs[k] = { + principalId: 'operator', + stage: 'signal_ic', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expressionHash: k.toString(16).padStart(64, '0'), + sampleStart: sharedStart, + sampleEnd: sharedEnd, + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: series, + }; + } + + const startNs = Bun.nanoseconds(); + + const builtRows: BuiltTrialRow[] = new Array(trialCount); + const dbRows: Record[] = new Array(trialCount); + for (let k = 0; k < trialCount; k += 1) { + const built = buildTrialRow(rawInputs[k] as TrialRowInput); + builtRows[k] = built; + dbRows[k] = { + trial_id: String(k + 1), + created_at: '2025-04-01T12:00:00.000Z', + principal_id: built.principalId, + campaign_id: built.campaignId, + stage: built.stage, + universe_market: built.universeMarket, + horizon_bucket: built.horizonBucket, + hypothesis_id: built.hypothesisId, + expression_hash: built.expressionHash, + sample_start: built.sampleStart, + sample_end: built.sampleEnd, + n_obs: built.nObs, + sharpe_unann: built.sharpeUnann, + skewness: built.skewness, + kurtosis: built.kurtosis, + daily_series: built.dailySeries, + }; + } + + const memExecutor: TrialLedgerExecutor = { + async query>(text: string) { + if (text.includes('WHERE trial_id = $1')) { + return { rows: [dbRows[0] as unknown as Row] }; + } + return { rows: dbRows as unknown as Row[] }; + }, + }; + + const result = await clusterDeflatedSharpe(memExecutor, { + trialId: 1, + sessionDates: sharedSessionDates, + }); + const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6; + const trialsPerSec = trialCount / (elapsedMs / 1000); + + // Staggered rolling-window benchmark: 200 distinct shifted windows (each shifted by 1 session + // across a 5,199-session calendar) verifying zero dense NaN padding overhead. + const staggeredCalendar = makeBusinessDates('2004-01-02', obsPerTrial + trialCount - 1); + const staggeredDbRows: Record[] = new Array(trialCount); + for (let k = 0; k < trialCount; k += 1) { + const built = builtRows[k] as BuiltTrialRow; + staggeredDbRows[k] = { + ...dbRows[k], + sample_start: staggeredCalendar[k]!, + sample_end: staggeredCalendar[k + obsPerTrial - 1]!, + n_obs: built.nObs, + }; + } + const staggeredExec: TrialLedgerExecutor = { + async query>(text: string) { + if (text.includes('WHERE trial_id = $1')) { + return { rows: [staggeredDbRows[0] as unknown as Row] }; + } + return { rows: staggeredDbRows as unknown as Row[] }; + }, + }; + + const staggeredStartNs = Bun.nanoseconds(); + const staggeredResult = await clusterDeflatedSharpe(staggeredExec, { + trialId: 1, + sessionDates: staggeredCalendar, + }); + const staggeredElapsedMs = (Bun.nanoseconds() - staggeredStartNs) / 1e6; + const staggeredTrialsPerSec = trialCount / (staggeredElapsedMs / 1000); + + process.stdout.write( + `[trial-ledger benchmark] trials=${trialCount} obsPerTrial=${obsPerTrial} elapsedMs=${elapsedMs.toFixed(2)} trialsPerSec=${trialsPerSec.toFixed(1)} effectiveTrials=${result.effectiveTrials.toFixed(2)} dsr=${(result.dsr ?? Number.NaN).toFixed(6)} staggeredElapsedMs=${staggeredElapsedMs.toFixed(2)} staggeredTrialsPerSec=${staggeredTrialsPerSec.toFixed(1)} staggeredPairsUsed=${staggeredResult.pairsUsed}\n` + ); + + expect(result.clusterSize).toBe(trialCount); + expect(Number.isFinite(elapsedMs)).toBe(true); + expect(Number.isFinite(trialsPerSec)).toBe(true); + expect(result.effectiveTrials).toBeGreaterThan(1); + expect(result.effectiveTrials).toBeLessThan(trialCount); + expect(result.dsr).not.toBeNull(); + + expect(staggeredResult.clusterSize).toBe(trialCount); + expect(staggeredResult.pairsUsed).toBe((trialCount * (trialCount - 1)) / 2); + expect(staggeredResult.pairsSkipped).toBe(0); + expect(Number.isFinite(staggeredElapsedMs)).toBe(true); + expect(staggeredResult.dsr).not.toBeNull(); + + // Cross-check against direct calculations on the same cluster. + const directEff = effectiveIndependentTrials(builtRows.map(r => r.dailySeries)); + expect(result.effectiveTrials).toBeCloseTo(directEff.nHat, 12); + }); +}); diff --git a/scripts/test/benchmark-sma.test.ts b/scripts/test/benchmark-sma.test.ts index eafeecc7..dd453c5f 100644 --- a/scripts/test/benchmark-sma.test.ts +++ b/scripts/test/benchmark-sma.test.ts @@ -16,6 +16,7 @@ test('sma_benchmark_modes rejects incompatible modes, periods and topology', () } }); +// Launches 24 fresh Bun processes; deadline is not a throughput target. test('sma_recorded_decision_parity verifies six shapes and actual financial/diagnostic identities', async () => { const process = Bun.spawn([Bun.which('bun')!, 'scripts/benchmark-research.ts', '--sma', '--self-test'], { stdout: 'pipe', stderr: 'pipe' }); const [stdout, stderr, exit] = await Promise.all([new Response(process.stdout).text(), new Response(process.stderr).text(), process.exited]); @@ -42,4 +43,4 @@ test('sma_recorded_decision_parity verifies six shapes and actual financial/diag } } } -}, 60000); +}, 180000); diff --git a/studio.config.json b/studio.config.json index b425c1fc..ccc87b53 100644 --- a/studio.config.json +++ b/studio.config.json @@ -3,11 +3,19 @@ "agentExecution": { "programmer": { "shell": true, - "networkDomains": [] + "networkDomains": [ + "crates.io", + "index.crates.io", + "static.crates.io" + ] }, "qa": { "shell": true, - "networkDomains": [] + "networkDomains": [ + "crates.io", + "index.crates.io", + "static.crates.io" + ] } }, "test": { diff --git a/test/contracts/market-data-store.type-test.ts b/test/contracts/market-data-store.type-test.ts new file mode 100644 index 00000000..c3ecb138 --- /dev/null +++ b/test/contracts/market-data-store.type-test.ts @@ -0,0 +1,324 @@ +import type { + BarBatch, + DataScope, + DuckDbConnectionBudget, + EventKind, + FencedTimeRange, + MarketDataStore, + Table, + UniverseRef, + VaultFenceContext, + VaultFenceQuery, +} from '@stock-bot/research'; +import type { + DataScope as SubpathDataScope, + MarketDataStore as SubpathMarketDataStore, +} from '@stock-bot/research/market-data-store'; + +type AssertEqual = + (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 ? true : false; + +const _sameStore: AssertEqual = true; +const _sameScope: AssertEqual = true; +void _sameStore; +void _sameScope; + +const emptyTable: Table = { columns: [], rows: [] }; +const emptyBatch: BarBatch = { rows: [] }; + +const stubStore: MarketDataStore = { + bars(_q: { + listingIds: number[]; + timeframe: '1m' | '5m' | '1h' | '1d'; + from: string; + to: string; + adjustment: 'raw' | 'split' | 'total'; + asOf?: string; + scope?: DataScope; + }): AsyncIterable { + return { + async *[Symbol.asyncIterator]() { + yield emptyBatch; + }, + }; + }, + + async crossSection(_q: { + features: string[]; + date: string; + universe: UniverseRef; + asOf?: string; + }): Promise
{ + return emptyTable; + }, + + async fundamentalsAsOf(_q: { + listingIds: number[]; + fields: string[]; + asOf: string; + allowEstimatedLag?: boolean; + }): Promise
{ + return emptyTable; + }, + + async events(_q: { + kinds: EventKind[]; + listingIds?: number[]; + from: string; + to: string; + asOf?: string; + }): Promise
{ + return emptyTable; + }, + + async shortsAsOf(_q: { + listingIds: number[]; + from: string; + to: string; + asOf?: string; + }): Promise
{ + return emptyTable; + }, + + async macroAsOf(_q: { + countries: string[]; + indicators: string[]; + from: string; + to: string; + asOf?: string; + }): Promise
{ + return emptyTable; + }, + + async fx(_q: { + pair: 'USD.CAD'; + timeframe: '1m' | '1d'; + from: string; + to: string; + }): Promise
{ + return emptyTable; + }, + + async universe(_q: { ref: UniverseRef; date: string }): Promise { + return [101, 202]; + }, +}; + +function verifyAllMethods(store: MarketDataStore): void { + const _bars: AsyncIterable = store.bars({ + listingIds: [1, 2], + timeframe: '1d', + from: '2024-01-01', + to: '2025-12-31', + adjustment: 'raw', + }); + const _barsWithOpts: AsyncIterable = store.bars({ + listingIds: [1], + timeframe: '1m', + from: '2025-01-01T00:00:00Z', + to: '2025-06-01T00:00:00Z', + adjustment: 'total', + asOf: '2025-06-01T00:00:00Z', + scope: 'vault_fenced', + }); + const _cross: Promise
= store.crossSection({ + features: ['rsi_14@v1'], + date: '2025-05-01', + universe: 'us_liquid_top3000', + asOf: '2025-05-01', + }); + const _fundamentals: Promise
= store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue_ttm'], + asOf: '2025-05-01', + allowEstimatedLag: false, + }); + const _events: Promise
= store.events({ + kinds: ['filing', 'earnings', 'ceo_post', 'corporate_action'], + from: '2025-01-01', + to: '2025-05-01', + }); + const _shorts: Promise
= store.shortsAsOf({ + listingIds: [1], + from: '2025-01-01', + to: '2025-05-01', + }); + const _macro: Promise
= store.macroAsOf({ + countries: ['US', 'CA'], + indicators: ['CPI'], + from: '2025-01-01', + to: '2025-05-01', + }); + const _fx: Promise
= store.fx({ + pair: 'USD.CAD', + timeframe: '1d', + from: '2025-01-01', + to: '2025-05-01', + }); + const _universe: Promise = store.universe({ + ref: 'us_liquid_top3000', + date: '2025-05-01', + }); + + void _bars; + void _barsWithOpts; + void _cross; + void _fundamentals; + void _events; + void _shorts; + void _macro; + void _fx; + void _universe; + + // Negative checks: unknown DataScope, non-numeric listingIds, missing required fields. + // @ts-expect-error Only 'vault_fenced' and 'vault_evaluation_only' are valid DataScope values. + const _badScope: DataScope = 'unrestricted'; + void _badScope; + + store.bars({ + // @ts-expect-error listingIds must be INT32 number[], not string[]. + listingIds: ['AAPL'], + timeframe: '1d', + from: '2025-01-01', + to: '2025-05-01', + adjustment: 'raw', + }); + + // @ts-expect-error adjustment is required on bars(). + store.bars({ + listingIds: [1], + timeframe: '1d', + from: '2025-01-01', + to: '2025-05-01', + }); + + // @ts-expect-error asOf is required on fundamentalsAsOf(). + store.fundamentalsAsOf({ + listingIds: [1], + fields: ['revenue_ttm'], + }); + + store.fx({ + // @ts-expect-error pair is locked to 'USD.CAD' in §4. + pair: 'EUR.USD', + timeframe: '1d', + from: '2025-01-01', + to: '2025-05-01', + }); +} + +verifyAllMethods(stubStore); + +// Ensure auxiliary exported contract types remain structurally usable. +const _query: VaultFenceQuery = { from: '2025-01-01', to: '2025-05-01' }; +const _ctx: VaultFenceContext = { vaultCutoffTs: Date.UTC(2026, 4, 28) }; +const _range: FencedTimeRange = { + fromMs: 0, + toMs: 1, + asOfMs: 1, + scope: 'vault_fenced', + clampedTo: false, + clampedAsOf: false, +}; +const _budget: DuckDbConnectionBudget = { + memoryLimit: '6GB', + threads: 4, + tempDirectory: '/mnt/data/stockbot/tmp/duckdb', + statements: [], +}; +void _query; +void _ctx; +void _range; +void _budget; + +// QA: exact parameter/return signatures for every §4 method. Assignability of +// the stub above cannot catch optionality drift (e.g. `crossSection.asOf` +// becoming required), so assert type identity against the documented shapes. +type ParamOf = Parameters[0]; +type ReturnOf = ReturnType; + +const _exactMethodKeys: AssertEqual< + keyof MarketDataStore, + | 'bars' + | 'crossSection' + | 'fundamentalsAsOf' + | 'events' + | 'shortsAsOf' + | 'macroAsOf' + | 'fx' + | 'universe' +> = true; +const _exactScope: AssertEqual = true; +const _exactBarsParam: AssertEqual< + ParamOf<'bars'>, + { + listingIds: number[]; + timeframe: '1m' | '5m' | '1h' | '1d'; + from: string; + to: string; + adjustment: 'raw' | 'split' | 'total'; + asOf?: string; + scope?: DataScope; + } +> = true; +const _exactBarsReturn: AssertEqual, AsyncIterable> = true; +const _exactCrossParam: AssertEqual< + ParamOf<'crossSection'>, + { features: string[]; date: string; universe: UniverseRef; asOf?: string } +> = true; +const _exactCrossReturn: AssertEqual, Promise
> = true; +const _exactFundParam: AssertEqual< + ParamOf<'fundamentalsAsOf'>, + { listingIds: number[]; fields: string[]; asOf: string; allowEstimatedLag?: boolean } +> = true; +const _exactFundReturn: AssertEqual, Promise
> = true; +const _exactEventsParam: AssertEqual< + ParamOf<'events'>, + { kinds: EventKind[]; listingIds?: number[]; from: string; to: string; asOf?: string } +> = true; +const _exactEventsReturn: AssertEqual, Promise
> = true; +const _exactShortsParam: AssertEqual< + ParamOf<'shortsAsOf'>, + { listingIds: number[]; from: string; to: string; asOf?: string } +> = true; +const _exactShortsReturn: AssertEqual, Promise
> = true; +const _exactMacroParam: AssertEqual< + ParamOf<'macroAsOf'>, + { countries: string[]; indicators: string[]; from: string; to: string; asOf?: string } +> = true; +const _exactMacroReturn: AssertEqual, Promise
> = true; +const _exactFxParam: AssertEqual< + ParamOf<'fx'>, + { pair: 'USD.CAD'; timeframe: '1m' | '1d'; from: string; to: string } +> = true; +const _exactFxReturn: AssertEqual, Promise
> = true; +const _exactUniverseParam: AssertEqual< + ParamOf<'universe'>, + { ref: UniverseRef; date: string } +> = true; +const _exactUniverseReturn: AssertEqual, Promise> = true; + +// Sanity: the helper must actually detect optionality drift. +const _detectsOptionalityDrift: AssertEqual<{ asOf?: string }, { asOf: string }> = false; + +void [ + _exactMethodKeys, + _exactScope, + _exactBarsParam, + _exactBarsReturn, + _exactCrossParam, + _exactCrossReturn, + _exactFundParam, + _exactFundReturn, + _exactEventsParam, + _exactEventsReturn, + _exactShortsParam, + _exactShortsReturn, + _exactMacroParam, + _exactMacroReturn, + _exactFxParam, + _exactFxReturn, + _exactUniverseParam, + _exactUniverseReturn, + _detectsOptionalityDrift, +]; diff --git a/test/postgres/security-master-override-seed.test.ts b/test/postgres/security-master-override-seed.test.ts new file mode 100644 index 00000000..ca9fe665 --- /dev/null +++ b/test/postgres/security-master-override-seed.test.ts @@ -0,0 +1,486 @@ +import { randomUUID } from 'node:crypto'; +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'; +import { + buildMatchReport, + generateOverrideSeedSql, + generateOverrideTemplateSql, + type OverrideSeedRow, +} from '../../apps/stock/data-pipeline/src/security-master'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('security-master-override-seed-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; + +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 pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + 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: 'master' }); + + return { pool, schema, postgres }; +} + +async function seedSingleListing(pool: Pool): Promise { + const instrumentResult = await pool.query<{ instrument_id: number }>( + `INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country) + VALUES ('US0378331005', '037833100', 'Apple Inc.', 'common', 'US') + RETURNING instrument_id` + ); + const instrumentId = instrumentResult.rows[0]?.instrument_id; + if (instrumentId === undefined) { + throw new Error('Failed to insert fixture instrument'); + } + + const listingResult = await pool.query<{ listing_id: number }>( + `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency) + VALUES ($1, 'XNAS', 'AAPL', '', 'USD') + RETURNING listing_id`, + [instrumentId] + ); + const listingId = listingResult.rows[0]?.listing_id; + if (listingId === undefined) { + throw new Error('Failed to insert fixture listing'); + } + return listingId; +} + +describe.skipIf(!url)('security master override seed SQL', () => { + test('inserts matching override row with resolved listing_id and is idempotent on re-run', async () => { + const f = await createIsolatedFixture(); + const expectedListingId = await seedSingleListing(f.pool); + + const row: OverrideSeedRow = { + source: 'eod', + sourceId: 'AAPL.US', + validFrom: '2020-01-15', + validTo: '2025-12-31', + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + reason: "O'Brien fix", + createdBy: 'director', + }; + + const sql = generateOverrideSeedSql([row]); + + // First run inserts exactly one row with the resolved listing_id + await f.pool.query(sql); + + const rowsAfterFirst = ( + await f.pool.query<{ + source: string; + source_id: string; + valid_from: string; + valid_to: string | null; + listing_id: number; + reason: string; + created_by: string; + }>( + `SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to, listing_id, reason, created_by + FROM override` + ) + ).rows; + + expect(rowsAfterFirst).toEqual([ + { + source: 'eod', + source_id: 'AAPL.US', + valid_from: '2020-01-15', + valid_to: '2025-12-31', + listing_id: expectedListingId, + reason: "O'Brien fix", + created_by: 'director', + }, + ]); + + // Second run is a no-op via ON CONFLICT (source, source_id, valid_from) DO NOTHING + await f.pool.query(sql); + + const countAfterSecond = ( + await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') + ).rows[0]?.count; + expect(countAfterSecond).toBe(1); + }); + + test('natural key matching no listing inserts nothing and raises no error', async () => { + const f = await createIsolatedFixture(); + await seedSingleListing(f.pool); + + const sql = generateOverrideSeedSql([ + { + source: 'qm', + sourceId: 'MISSING:US', + validFrom: '1900-01-01', + validTo: null, + primaryIsin: 'US9999999999', + mic: 'XNAS', + tickerRoot: 'MISSING', + classSuffix: '', + currency: 'USD', + reason: 'Non-existent listing test', + createdBy: 'director', + }, + ]); + + await f.pool.query(sql); + + const count = ( + await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') + ).rows[0]?.count; + expect(count).toBe(0); + }); + + test('duplicate natural key raises cardinality_violation and inserts no override row', async () => { + const f = await createIsolatedFixture(); + await seedSingleListing(f.pool); + + // Insert a second listing row with the same natural key (e.g., different listing dates) + const instrumentResult = await f.pool.query<{ instrument_id: number }>( + `SELECT instrument_id FROM instrument WHERE primary_isin = 'US0378331005'` + ); + const instrumentId = instrumentResult.rows[0]?.instrument_id; + if (instrumentId === undefined) { + throw new Error('Expected fixture instrument'); + } + await f.pool.query( + `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency, listed_from) + VALUES ($1, 'XNAS', 'AAPL', '', 'USD', DATE '2022-01-03')`, + [instrumentId] + ); + + const sql = generateOverrideSeedSql([ + { + source: 'eod', + sourceId: 'AAPL.US', + validFrom: '2020-01-15', + validTo: null, + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + reason: 'Ambiguous natural key test', + createdBy: 'director', + }, + ]); + + let caughtError: unknown; + try { + await f.pool.query(sql); + } catch (err) { + caughtError = err; + } + + expect(caughtError).toBeDefined(); + expect((caughtError as { code?: string }).code).toBe('21000'); + + const count = ( + await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') + ).rows[0]?.count; + expect(count).toBe(0); + }); + + test('empty seed SQL and template SQL execute cleanly without inserting rows', async () => { + const f = await createIsolatedFixture(); + await seedSingleListing(f.pool); + + const emptySql = generateOverrideSeedSql([]); + await f.pool.query(emptySql); + + const report = buildMatchReport({ + stageA: { + instruments: [], + unresolved: [], + conflicts: [ + { + source: 'eod', + sourceId: 'AAPL.US', + conflictKind: 'isin_cusip_mismatch', + detail: { isin: 'US0378331005', cusip: '037833100', country: 'US', derivedIsin: null }, + }, + ], + stats: { + totalInputRecords: 1, + totalInstruments: 0, + bySource: { + ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + eod: { total: 1, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 1 }, + }, + }, + }, + stageB: { + listings: [], + providerMappings: [], + unresolved: [], + conflicts: [], + stats: { + totalListings: 0, + totalProviderMappings: 0, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }, + }, + }); + + const templateSql = generateOverrideTemplateSql(report); + await f.pool.query(templateSql); + + const count = ( + await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') + ).rows[0]?.count; + expect(count).toBe(0); + }); + + test('uncommented template candidate with CR/LF source_id preserves the exact ID in PostgreSQL', async () => { + const f = await createIsolatedFixture(); + const expectedListingId = await seedSingleListing(f.pool); + const rawSourceId = "AAPL\r\nLINE2'\\END"; + + const report = buildMatchReport({ + stageA: { + instruments: [], + unresolved: [], + conflicts: [ + { + source: 'eod', + sourceId: rawSourceId, + conflictKind: 'isin_cusip_mismatch', + detail: { isin: 'US0378331005', cusip: '037833100', country: 'US', derivedIsin: null }, + }, + ], + stats: { + totalInputRecords: 1, + totalInstruments: 0, + bySource: { + ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + eod: { total: 1, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 1 }, + }, + }, + }, + stageB: { + listings: [], + providerMappings: [], + unresolved: [], + conflicts: [], + stats: { + totalListings: 0, + totalProviderMappings: 0, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }, + }, + }); + + const templateSql = generateOverrideTemplateSql(report); + const candidateLines = templateSql + .split('\n') + .slice(templateSql.split('\n').findIndex(line => line === '-- INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)')) + .filter(line => line.startsWith('-- ')) + .map(line => line.slice(3)) + .join('\n') + .replace("'TODO_ISIN_12'", "'US0378331005'") + .replace("'TODO_MIC'", "'XNAS'") + .replace("'TODO_TICKER'", "'AAPL'"); + + await f.pool.query(candidateLines); + + const inserted = ( + await f.pool.query<{ source_id: string; listing_id: number }>( + 'SELECT source_id, listing_id FROM override' + ) + ).rows; + expect(inserted).toEqual([{ source_id: rawSourceId, listing_id: expectedListingId }]); + }); + + test('uncommented template candidate with unstorable source_id fails not_null_violation and inserts no row when marker is left in place', async () => { + const f = await createIsolatedFixture(); + await seedSingleListing(f.pool); + const overlongSourceId = 'X'.repeat(65); + + const report = buildMatchReport({ + stageA: { + instruments: [], + unresolved: [], + conflicts: [ + { + source: 'eod', + sourceId: overlongSourceId, + conflictKind: 'isin_cusip_mismatch', + detail: { isin: 'US0378331005', cusip: '037833100', country: 'US', derivedIsin: null }, + }, + ], + stats: { + totalInputRecords: 1, + totalInstruments: 0, + bySource: { + ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + eod: { total: 1, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 1 }, + }, + }, + }, + stageB: { + listings: [], + providerMappings: [], + unresolved: [], + conflicts: [], + stats: { + totalListings: 0, + totalProviderMappings: 0, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }, + }, + }); + + const templateSql = generateOverrideTemplateSql(report); + const templateLines = templateSql.split('\n'); + const insertStartIndex = templateLines.findIndex( + line => + line === + '-- INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)' + ); + expect(insertStartIndex).toBeGreaterThan(-1); + + const candidateSql = templateLines + .slice(insertStartIndex) + .filter(line => line.startsWith('-- ')) + .map(line => line.slice(3)) + .join('\n') + .replace("'TODO_ISIN_12'", "'US0378331005'") + .replace("'TODO_MIC'", "'XNAS'") + .replace("'TODO_TICKER'", "'AAPL'"); + + let caughtError: unknown; + try { + await f.pool.query(candidateSql); + } catch (err) { + caughtError = err; + } + + expect(caughtError).toBeDefined(); + expect((caughtError as { code?: string }).code).toBe('23502'); + + const count = ( + await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') + ).rows[0]?.count; + expect(count).toBe(0); + }); + + test('multi-statement seed file round-trips special characters, class suffix keys, and distinct valid_from rows', async () => { + const f = await createIsolatedFixture(); + const aaplListingId = await seedSingleListing(f.pool); + const brk = await f.pool.query<{ instrument_id: number }>( + `INSERT INTO instrument (primary_isin, canonical_name, security_type, issuer_country) + VALUES ('US0846707026', 'Berkshire Hathaway', 'common', 'US') RETURNING instrument_id` + ); + const brkA = await f.pool.query<{ listing_id: number }>( + `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency) + VALUES ($1, 'XNYS', 'BRK', 'A', 'USD') RETURNING listing_id`, + [brk.rows[0]?.instrument_id] + ); + const brkB = await f.pool.query<{ listing_id: number }>( + `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency) + VALUES ($1, 'XNYS', 'BRK', 'B', 'USD') RETURNING listing_id`, + [brk.rows[0]?.instrument_id] + ); + const trickyReason = "line1\nO'Brien \\ back\r\nslash -- not a comment; DROP TABLE override;"; + + const sql = generateOverrideSeedSql([ + { source: 'eod', sourceId: 'BRK-B.US', validFrom: '2021-01-01', validTo: null, primaryIsin: 'US0846707026', mic: 'XNYS', tickerRoot: 'BRK', classSuffix: 'B', currency: 'USD', reason: trickyReason, createdBy: 'director' }, + { source: 'eod', sourceId: 'BRK-B.US', validFrom: '2020-01-01', validTo: '2020-12-31', primaryIsin: 'US0846707026', mic: 'XNYS', tickerRoot: 'BRK', classSuffix: 'A', currency: 'USD', reason: 'pre-split mapping', createdBy: 'director' }, + { source: 'qm', sourceId: "AAPL'Q", primaryIsin: 'US0378331005', mic: 'XNAS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', reason: 'default dates', createdBy: 'qa' }, + ]); + await f.pool.query(sql); + + const rows = ( + await f.pool.query<{ source: string; source_id: string; valid_from: string; valid_to: string | null; listing_id: number; reason: string }>( + `SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to, listing_id, reason + FROM override ORDER BY source, source_id, valid_from` + ) + ).rows; + expect(rows).toEqual([ + { source: 'eod', source_id: 'BRK-B.US', valid_from: '2020-01-01', valid_to: '2020-12-31', listing_id: brkA.rows[0]?.listing_id ?? -1, reason: 'pre-split mapping' }, + { source: 'eod', source_id: 'BRK-B.US', valid_from: '2021-01-01', valid_to: null, listing_id: brkB.rows[0]?.listing_id ?? -1, reason: trickyReason }, + { source: 'qm', source_id: "AAPL'Q", valid_from: '1900-01-01', valid_to: null, listing_id: aaplListingId, reason: 'default dates' }, + ]); + }); + + test('re-seeding an existing override key keeps the originally stored listing_id (DO NOTHING, no overwrite)', async () => { + const f = await createIsolatedFixture(); + const aaplListingId = await seedSingleListing(f.pool); + await f.pool.query( + `INSERT INTO override (source, source_id, valid_from, listing_id, reason, created_by) + VALUES ('eod', 'AAPL.US', DATE '1900-01-01', $1, 'original', 'director')`, + [aaplListingId] + ); + const instrumentId = (await f.pool.query<{ instrument_id: number }>(`SELECT instrument_id FROM instrument`)).rows[0]?.instrument_id; + await f.pool.query( + `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency) VALUES ($1, 'XNYS', 'AAPL', '', 'USD')`, + [instrumentId] + ); + + await f.pool.query( + generateOverrideSeedSql([ + { source: 'eod', sourceId: 'AAPL.US', primaryIsin: 'US0378331005', mic: 'XNYS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', reason: 'replacement', createdBy: 'qa' }, + ]) + ); + + const rows = (await f.pool.query<{ listing_id: number; reason: string }>('SELECT listing_id, reason FROM override')).rows; + expect(rows).toEqual([{ listing_id: aaplListingId, reason: 'original' }]); + }); +}); diff --git a/test/postgres/security-master-persist-qa.test.ts b/test/postgres/security-master-persist-qa.test.ts new file mode 100644 index 00000000..61a0c26f --- /dev/null +++ b/test/postgres/security-master-persist-qa.test.ts @@ -0,0 +1,384 @@ +import { randomUUID } from 'node:crypto'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool, type PoolClient } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + DEFAULT_OTC_MICS, + formatListingNaturalKey, + linkDelistingChains, + matchInstrumentsStageA, + matchListingsStageB, + persistSecurityMaster, + type SecurityType, +} from '../../apps/stock/data-pipeline/src/security-master'; + +// QA edge cases for persistSecurityMaster that complement security-master-persist.test.ts: +// mutable-field updates on existing rows, re-runs without Pass 6, price_corr retention, +// and instruments that become un-persistable after a successful load. + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('security-master-persist-qa-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; + +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 pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=15000 -c lock_timeout=15000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + 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: 'master' }); + return { pool }; +} + +async function withClient(pool: Pool, fn: (client: PoolClient) => Promise): Promise { + const client = await pool.connect(); + try { + return await fn(client); + } finally { + client.release(); + } +} + +const AAPL_KEY = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', +}; +const SIVB_KEY = { + primaryIsin: 'US78486Q1013', + mic: 'XNAS', + tickerRoot: 'SIVB', + classSuffix: '', + currency: 'USD', +}; +const SIVBQ_KEY = { ...SIVB_KEY, mic: 'OTCM', tickerRoot: 'SIVBQ' }; + +/** AAPL + SIVB->SIVBQ via the real matchers; `aaplLastBar` varies per run. */ +function buildFixture(opts: { aaplLastBar?: string } = {}) { + const stageA = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'AAPL.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + { + source: 'eod', + sourceId: 'SIVB.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SIVBQ.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + ]); + const stageB = matchListingsStageB({ + instruments: stageA.instruments, + eodListings: [ + { + sourceId: 'AAPL.US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '1980-12-12', lastBarDate: opts.aaplLastBar ?? '2026-11-27' }, + }, + { + sourceId: 'SIVB.US', + ticker: 'SIVB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '1987-10-26', lastBarDate: '2023-03-10' }, + }, + { + sourceId: 'SIVBQ.US', + ticker: 'SIVBQ', + mic: 'OTCM', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2023-03-28', lastBarDate: '2024-11-07' }, + }, + ], + ibContracts: [], + tickerSources: [], + }); + const pass6 = linkDelistingChains( + { listings: stageB.listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2026-11-27' } + ); + const securityTypeByIsin = new Map([ + ['US0378331005', 'common'], + ['US78486Q1013', 'common'], + ]); + return { stageA, stageB, pass6, securityTypeByIsin }; +} + +describe.skipIf(!url)('persistSecurityMaster PostgreSQL QA edge cases', () => { + test('updates changed instrument fields in place, keeps instrument_id, and appends (never replaces) CUSIP history', async () => { + const f = await createIsolatedFixture(); + const run1 = await withClient(f.pool, c => persistSecurityMaster(c, buildFixture())); + const aaplInstrumentId = run1.instrumentIdByIsin.get('US0378331005'); + const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY)); + expect(aaplInstrumentId).toBeDefined(); + + // Stage A would quarantine an ISIN/CUSIP mismatch, so emulate a corrected upstream CUSIP and + // renamed issuer by editing the matcher output directly. + const base = buildFixture(); + const renamed = { + ...base, + stageA: { + ...base.stageA, + instruments: base.stageA.instruments.map(inst => + inst.primaryIsin === 'US0378331005' + ? { ...inst, primaryCusip: '037833101', canonicalName: 'Apple Incorporated' } + : inst + ), + }, + }; + const run2 = await withClient(f.pool, c => persistSecurityMaster(c, renamed)); + + expect(run2.instrumentsInserted).toBe(0); + expect(run2.instrumentsUpdated).toBe(1); + expect(run2.instrumentsUnchanged).toBe(1); + expect(run2.identifierHistoryInserted).toBe(1); // new CUSIP only + expect(run2.instrumentIdByIsin.get('US0378331005')).toBe(aaplInstrumentId!); + expect(run2.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))).toBe(aaplListingId!); + + const inst = ( + await f.pool.query<{ instrument_id: number; primary_cusip: string; canonical_name: string }>( + `SELECT instrument_id, btrim(primary_cusip) AS primary_cusip, canonical_name + FROM instrument WHERE primary_isin = 'US0378331005'` + ) + ).rows; + expect(inst).toEqual([ + { instrument_id: aaplInstrumentId!, primary_cusip: '037833101', canonical_name: 'Apple Incorporated' }, + ]); + + const history = ( + await f.pool.query<{ id_type: string; id_value: string }>( + `SELECT id_type, id_value FROM instrument_identifier_history + WHERE instrument_id = $1 ORDER BY id_type, id_value`, + [aaplInstrumentId] + ) + ).rows; + expect(history).toEqual([ + { id_type: 'CUSIP', id_value: '037833100' }, + { id_type: 'CUSIP', id_value: '037833101' }, + { id_type: 'ISIN', id_value: 'US0378331005' }, + ]); + }); + + test('extending listed_to updates the listing and its single symbol-history row in place', async () => { + const f = await createIsolatedFixture(); + const run1 = await withClient(f.pool, c => persistSecurityMaster(c, buildFixture())); + const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))!; + + const run2 = await withClient(f.pool, c => + persistSecurityMaster(c, buildFixture({ aaplLastBar: '2026-12-31' })) + ); + expect(run2.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))).toBe(aaplListingId); + expect(run2.listingsInserted).toBe(0); + expect(run2.listingsUpdated).toBe(1); + expect(run2.listingsUnchanged).toBe(2); + expect(run2.listingSymbolHistoryInserted).toBe(0); + expect(run2.listingSymbolHistoryUpdated).toBe(1); + expect(run2.listingSymbolHistoryUnchanged).toBe(2); + + const listing = ( + await f.pool.query<{ listed_to: string }>( + `SELECT to_char(listed_to, 'YYYY-MM-DD') AS listed_to FROM listing WHERE listing_id = $1`, + [aaplListingId] + ) + ).rows; + expect(listing).toEqual([{ listed_to: '2026-12-31' }]); + + const symbols = ( + await f.pool.query<{ ticker: string; valid_from: string; valid_to: string | null }>( + `SELECT ticker, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to + FROM listing_symbol_history WHERE listing_id = $1`, + [aaplListingId] + ) + ).rows; + expect(symbols).toEqual([{ ticker: 'AAPL', valid_from: '1980-12-12', valid_to: '2026-12-31' }]); + }); + + test('a re-run without pass6 leaves delist_reason, terminal_return and continuities untouched', async () => { + const f = await createIsolatedFixture(); + const full = buildFixture(); + const run1 = await withClient(f.pool, c => persistSecurityMaster(c, full)); + expect(run1.continuitiesInserted).toBe(1); + + const snapshot = async () => + ( + await f.pool.query( + `SELECT listing_id, delist_reason, terminal_return::text AS terminal_return + FROM listing ORDER BY listing_id` + ) + ).rows; + const before = await snapshot(); + const continuityBefore = (await f.pool.query('SELECT * FROM corporate_action_continuity')).rows; + + const run2 = await withClient(f.pool, c => + persistSecurityMaster(c, { + stageA: full.stageA, + stageB: full.stageB, + securityTypeByIsin: full.securityTypeByIsin, + }) + ); + + expect(run2.listingsUpdated).toBe(0); + expect(run2.listingsUnchanged).toBe(3); + expect(run2.pass6OutcomesApplied).toBe(0); + expect(run2.continuitiesInserted + run2.continuitiesUpdated + run2.continuitiesUnchanged).toBe(0); + expect(await snapshot()).toEqual(before); + expect((await f.pool.query('SELECT * FROM corporate_action_continuity')).rows).toEqual( + continuityBefore + ); + + const sivbId = run2.listingIdByKey.get(formatListingNaturalKey(SIVB_KEY)); + const sivbRow = before.find(r => r.listing_id === sivbId); + expect(sivbRow?.delist_reason).toBe('moved_to_otc'); + expect(run2.listingIdByKey.get(formatListingNaturalKey(SIVBQ_KEY))).toBeDefined(); + }); + + test('keeps price_corr when a matcher update keeps the same listing and clears it when the listing changes', async () => { + const f = await createIsolatedFixture(); + const base = buildFixture(); + const run1 = await withClient(f.pool, c => persistSecurityMaster(c, base)); + const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))!; + const sivbListingId = run1.listingIdByKey.get(formatListingNaturalKey(SIVB_KEY))!; + + const aaplMapping = base.stageB.providerMappings.find(m => m.sourceId === 'AAPL.US'); + expect(aaplMapping).toBeDefined(); + const validFrom = aaplMapping!.validFrom ?? '1900-01-01'; + await f.pool.query( + `UPDATE provider_mapping SET price_corr = 0.9876 + WHERE source = 'eod' AND source_id = 'AAPL.US' AND valid_from = $1::date`, + [validFrom] + ); + + const readMapping = async () => + ( + await f.pool.query<{ listing_id: number; valid_to: string | null; price_corr: string | null }>( + `SELECT listing_id, to_char(valid_to, 'YYYY-MM-DD') AS valid_to, price_corr::text AS price_corr + FROM provider_mapping + WHERE source = 'eod' AND source_id = 'AAPL.US' AND valid_from = $1::date`, + [validFrom] + ) + ).rows; + + // Same listing, new valid_to -> updated, price_corr retained. + const withNewValidTo = { + ...base, + stageB: { + ...base.stageB, + providerMappings: base.stageB.providerMappings.map(m => + m === aaplMapping ? { ...m, validTo: '2030-01-01' } : m + ), + }, + }; + const run2 = await withClient(f.pool, c => persistSecurityMaster(c, withNewValidTo)); + expect(run2.providerMappingsUpdated).toBe(1); + expect(await readMapping()).toEqual([ + { listing_id: aaplListingId, valid_to: '2030-01-01', price_corr: '0.9876' }, + ]); + + // Redirected to a different listing -> price_corr must not carry over. + const redirected = { + ...base, + stageB: { + ...base.stageB, + providerMappings: base.stageB.providerMappings.map(m => + m === aaplMapping ? { ...m, validTo: '2030-01-01', listingKey: SIVB_KEY } : m + ), + }, + }; + const run3 = await withClient(f.pool, c => persistSecurityMaster(c, redirected)); + expect(run3.providerMappingsUpdated).toBe(1); + expect(await readMapping()).toEqual([ + { listing_id: sivbListingId, valid_to: '2030-01-01', price_corr: null }, + ]); + }); + + test('an instrument that loses its security type on a later run is skipped without deleting or altering persisted rows', async () => { + const f = await createIsolatedFixture(); + const base = buildFixture(); + await withClient(f.pool, c => persistSecurityMaster(c, base)); + + const dump = async () => { + const out: Record = {}; + for (const [table, order] of [ + ['instrument', 'instrument_id'], + ['instrument_identifier_history', 'id_type, id_value'], + ['listing', 'listing_id'], + ['listing_symbol_history', 'listing_id, ticker, valid_from'], + ['provider_mapping', 'source, source_id, valid_from'], + ['corporate_action_continuity', 'from_listing_id, effective_date'], + ] as const) { + out[table] = (await f.pool.query(`SELECT * FROM ${table} ORDER BY ${order}`)).rows; + } + return out; + }; + const before = await dump(); + + const run2 = await withClient(f.pool, c => + persistSecurityMaster(c, { + ...base, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }) + ); + + expect(run2.instrumentsSkipped).toBe(1); + expect(run2.skippedByReason.instruments.missing_security_type).toBe(1); + expect(run2.skippedByReason.listings.skipped_instrument).toBe(2); + expect(run2.pass6OutcomesSkipped).toBe(2); // SIVB + SIVBQ + expect(run2.skippedByReason.continuities.missing_both_listings).toBe(1); + expect(run2.instrumentIdByIsin.has('US78486Q1013')).toBe(false); + expect(run2.instrumentsInserted + run2.instrumentsUpdated).toBe(0); + expect(run2.listingsInserted + run2.listingsUpdated).toBe(0); + expect(run2.providerMappingsInserted + run2.providerMappingsUpdated).toBe(0); + expect(await dump()).toEqual(before); + }); +}); diff --git a/test/postgres/security-master-persist.test.ts b/test/postgres/security-master-persist.test.ts new file mode 100644 index 00000000..ac5b0339 --- /dev/null +++ b/test/postgres/security-master-persist.test.ts @@ -0,0 +1,1979 @@ +import { randomUUID } from 'node:crypto'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool, type PoolClient } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + DEFAULT_OTC_MICS, + DEFAULT_VALID_FROM, + formatListingNaturalKey, + linkDelistingChains, + matchInstrumentsStageA, + matchListingsStageB, + persistSecurityMaster, + type DelistingChainResult, + type SecurityMasterQueryable, + type SecurityType, + type StageAMatchResult, + type StageBMatchResult, +} from '../../apps/stock/data-pipeline/src/security-master'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('security-master-persist-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +async function createIsolatedFixture(statementTimeoutMs = 15_000) { + 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 pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=${statementTimeoutMs} -c lock_timeout=15000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + 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: 'master' }); + + return { pool, schema, postgres }; +} + +async function withClient(pool: Pool, fn: (client: PoolClient) => Promise): Promise { + const client = await pool.connect(); + try { + return await fn(client); + } finally { + client.release(); + } +} + +async function getSevenTableCounts(pool: Pool): Promise> { + const tables = [ + 'instrument', + 'instrument_identifier_history', + 'listing', + 'listing_symbol_history', + 'provider_mapping', + 'resolution_conflict', + 'corporate_action_continuity', + ] as const; + const counts: Record = {}; + for (const table of tables) { + const res = await pool.query<{ count: number }>(`SELECT count(*)::int AS count FROM ${table}`); + counts[table] = res.rows[0]?.count ?? -1; + } + return counts; +} + +/** + * Builds the canonical M1 exit-criterion fixture through the real Stage A -> Stage B -> Pass 6 + * matchers: + * - AAPL (`US0378331005`) on XNAS with IB conid + EOD + QM mappings + * - FB (`US30303M1027`, 2012-2022 common) vs FB (`US4642872000`, 2025 ETF) on XNAS + * - SIVB (`US78486Q1013`) XNAS -> SIVBQ OTCM delisting continuity + * - SHOP (`CA82509L1076`) interlisted XTSE (CAD) + XNYS (USD) + * - Stage A conflict (`isin_cusip_mismatch`) + Stage B conflict (`ambiguous_ticker_span`) + */ +function buildExitCriterionFixture() { + const stageA = matchInstrumentsStageA([ + { + source: 'ib', + sourceId: '265598', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + { + source: 'eod', + sourceId: 'AAPL.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc', + }, + { + source: 'eod', + sourceId: 'FB_OLD.US', + isin: 'US30303M1027', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: 'Meta Platforms Inc.', + }, + { + source: 'eod', + sourceId: 'FB_ETF.US', + isin: 'US4642872000', + cusip: '464287200', + country: 'US', + currency: 'USD', + name: 'FB Thematic ETF', + }, + { + source: 'eod', + sourceId: 'SIVB.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SIVBQ.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SHOP.TO', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'CAD', + name: 'Shopify Inc.', + }, + { + source: 'eod', + sourceId: 'SHOP.US', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'US', + currency: 'USD', + name: 'Shopify Inc.', + }, + // Stage A conflict: mismatched ISIN vs CUSIP + { + source: 'eod', + sourceId: 'BAD_ISIN.US', + isin: 'US0378331005', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: 'Mismatched Corp', + }, + ]); + + const stageB = matchListingsStageB({ + instruments: stageA.instruments, + eodListings: [ + { + sourceId: 'AAPL.US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '1980-12-12', lastBarDate: '2026-11-27' }, + }, + { + sourceId: 'FB_OLD.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2012-05-18', lastBarDate: '2022-06-08' }, + }, + { + sourceId: 'FB_ETF.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2025-01-15', lastBarDate: '2026-11-27' }, + }, + { + sourceId: 'SIVB.US', + ticker: 'SIVB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '1987-10-26', lastBarDate: '2023-03-10' }, + }, + { + sourceId: 'SIVBQ.US', + ticker: 'SIVBQ', + mic: 'OTCM', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2023-03-28', lastBarDate: '2024-11-07' }, + }, + { + sourceId: 'SHOP.TO', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2015-05-21', lastBarDate: '2026-11-27' }, + }, + { + sourceId: 'SHOP.US', + ticker: 'SHOP', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2015-05-21', lastBarDate: '2026-11-27' }, + }, + ], + ibContracts: [ + { + sourceId: '265598', + conid: 265598, + currency: 'USD', + primaryExchange: 'NASDAQ', + }, + ], + tickerSources: [ + { + source: 'qm', + sourceId: 'AAPL:US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2010-01-04', lastBarDate: '2026-11-27' }, + }, + { + source: 'ceo', + sourceId: 'SHOP:TSX', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2016-01-04', lastBarDate: '2026-11-27' }, + }, + // Stage B conflict: ambiguous_ticker_span spanning both FB listings + { + source: 'qm', + sourceId: 'FB:US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-06-01' }, + }, + ], + }); + + const pass6 = linkDelistingChains( + { listings: stageB.listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2026-11-27' } + ); + + const securityTypeByIsin = new Map([ + ['US0378331005', 'common'], + ['US30303M1027', 'common'], + ['US4642872000', 'etf'], + ['US78486Q1013', 'common'], + ['CA82509L1076', 'common'], + ]); + + return { stageA, stageB, pass6, securityTypeByIsin }; +} + +function buildSyntheticBenchmarkInput(instrumentCount: number): { + stageA: StageAMatchResult; + stageB: StageBMatchResult; + securityTypeByIsin: Map; +} { + const instruments: StageAMatchResult['instruments'] = []; + const listings: StageBMatchResult['listings'] = []; + const providerMappings: StageBMatchResult['providerMappings'] = []; + const securityTypeByIsin = new Map(); + + const mics = ['XNAS', 'XNYS', 'ARCX', 'XTSE'] as const; + + for (let i = 0; i < instrumentCount; i++) { + const seq = String(i).padStart(9, '0'); + const mic = mics[i % mics.length] ?? 'XNAS'; + const isCanada = mic === 'XTSE'; + const country = isCanada ? 'CA' : 'US'; + const currency = isCanada ? 'CAD' : 'USD'; + const isin = `${country}${seq}0`; + const tickerRoot = `S${i}`; + + instruments.push({ + primaryIsin: isin, + primaryCusip: null, + issuerCountry: country, + canonicalName: `Synthetic Issuer ${i}`, + members: [{ source: 'eod', sourceId: `${tickerRoot}.${country}`, currency, method: 'tier1_isin' }], + }); + securityTypeByIsin.set(isin, i % 10 === 0 ? 'etf' : 'common'); + + const listingKey = { + primaryIsin: isin, + mic, + tickerRoot, + classSuffix: '', + currency, + }; + listings.push({ + ...listingKey, + ibConid: 1_000_000 + i, + ibPrimaryExchange: isCanada ? 'TSE' : 'NASDAQ', + listedFrom: '2015-01-02', + listedTo: null, + }); + + // 3 provider mappings per listing -> 60,000 mappings for 20,000 instruments + providerMappings.push( + { + source: 'eod', + sourceId: `${tickerRoot}.${country}`, + listingKey, + method: 'tier1_isin', + validFrom: null, + validTo: null, + }, + { + source: 'ib', + sourceId: String(1_000_000 + i), + listingKey, + method: 'tier1_isin', + validFrom: null, + validTo: null, + }, + { + source: 'qm', + sourceId: `${tickerRoot}:${country}`, + listingKey, + method: 'tier3_ticker_span', + validFrom: '2015-01-02', + validTo: null, + } + ); + } + + return { + stageA: { + instruments, + unresolved: [], + conflicts: [], + stats: { + totalInputRecords: instrumentCount, + totalInstruments: instrumentCount, + bySource: { + ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + eod: { total: instrumentCount, tier1Isin: instrumentCount, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + }, + }, + }, + stageB: { + listings, + providerMappings, + unresolved: [], + conflicts: [], + stats: { + totalListings: instrumentCount, + totalProviderMappings: providerMappings.length, + listingsWithIbConid: instrumentCount, + excludedFunds: 0, + bySource: { + eod: { total: instrumentCount, matched: instrumentCount, unresolved: 0, conflict: 0 }, + ib: { total: instrumentCount, matched: instrumentCount, unresolved: 0, conflict: 0 }, + qm: { total: instrumentCount, matched: instrumentCount, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }, + }, + securityTypeByIsin, + }; +} + +describe.skipIf(!url)('persistSecurityMaster PostgreSQL integration', () => { + test('happy path persists all 7 tables via real matchers and satisfies M1 exit-criterion shapes', async () => { + const f = await createIsolatedFixture(); + const fixture = buildExitCriterionFixture(); + + const result = await withClient(f.pool, client => persistSecurityMaster(client, fixture)); + const counts = await getSevenTableCounts(f.pool); + + expect(result.instrumentsInserted).toBe(5); + expect(result.instrumentsSkipped).toBe(0); + expect(result.identifierHistoryInserted).toBe(10); // 5 ISIN + 5 CUSIP + expect(result.listingsInserted).toBe(7); + expect(result.listingSymbolHistoryInserted).toBe(7); + expect(result.providerMappingsInserted).toBe(10); // 7 EOD + 1 IB + 1 QM + 1 CEO + expect(result.conflictsInserted).toBe(2); // 1 Stage A + 1 Stage B + expect(result.continuitiesInserted).toBe(1); // SIVB -> SIVBQ + expect(result.overridesApplied).toBe(0); + + // Returned counters reconcile exactly with SQL COUNT(*) per table. + expect(counts).toEqual({ + instrument: result.instrumentsInserted, + instrument_identifier_history: result.identifierHistoryInserted, + listing: result.listingsInserted, + listing_symbol_history: result.listingSymbolHistoryInserted, + provider_mapping: result.providerMappingsInserted, + resolution_conflict: result.conflictsInserted, + corporate_action_continuity: result.continuitiesInserted, + }); + + // Exit criterion 1a: FB (2012-2022 common) vs FB (2025 ETF) have distinct listing_ids. + const fbOldId = result.listingIdByKey.get( + formatListingNaturalKey({ + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }) + ); + const fbEtfId = result.listingIdByKey.get( + formatListingNaturalKey({ + primaryIsin: 'US4642872000', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }) + ); + expect(fbOldId).toBeDefined(); + expect(fbEtfId).toBeDefined(); + expect(fbOldId).not.toBe(fbEtfId); + + // Exit criterion 1b: SIVB -> SIVBQ continuity and delist_reason / terminal_return. + const sivbId = result.listingIdByKey.get( + formatListingNaturalKey({ + primaryIsin: 'US78486Q1013', + mic: 'XNAS', + tickerRoot: 'SIVB', + classSuffix: '', + currency: 'USD', + }) + ); + const sivbqId = result.listingIdByKey.get( + formatListingNaturalKey({ + primaryIsin: 'US78486Q1013', + mic: 'OTCM', + tickerRoot: 'SIVBQ', + classSuffix: '', + currency: 'USD', + }) + ); + expect(sivbId).toBeDefined(); + expect(sivbqId).toBeDefined(); + expect(sivbId).not.toBe(sivbqId); + + const sivbRows = ( + await f.pool.query<{ + listing_id: number; + delist_reason: string | null; + terminal_return: string | null; + }>( + `SELECT listing_id, delist_reason, terminal_return + FROM listing + WHERE listing_id = ANY($1::int4[]) + ORDER BY listing_id`, + [[sivbId, sivbqId]] + ) + ).rows; + expect(sivbRows.find(r => r.listing_id === sivbId)).toEqual({ + listing_id: sivbId!, + delist_reason: 'moved_to_otc', + terminal_return: null, + }); + expect(sivbRows.find(r => r.listing_id === sivbqId)).toEqual({ + listing_id: sivbqId!, + delist_reason: 'bankruptcy_cancelled', + terminal_return: '-1.000000', + }); + + const continuityRows = ( + await f.pool.query<{ + from_listing_id: number; + to_listing_id: number; + effective_date: string; + kind: string; + }>( + `SELECT from_listing_id, to_listing_id, to_char(effective_date, 'YYYY-MM-DD') AS effective_date, kind + FROM corporate_action_continuity` + ) + ).rows; + expect(continuityRows).toEqual([ + { + from_listing_id: sivbId!, + to_listing_id: sivbqId!, + effective_date: '2023-03-28', + kind: 'otc_delist_transfer', + }, + ]); + + // Interlisted SHOP shares one instrument_id and gets two distinct listing_ids. + const shopTsxId = result.listingIdByKey.get( + formatListingNaturalKey({ + primaryIsin: 'CA82509L1076', + mic: 'XTSE', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'CAD', + }) + ); + const shopNyseId = result.listingIdByKey.get( + formatListingNaturalKey({ + primaryIsin: 'CA82509L1076', + mic: 'XNYS', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'USD', + }) + ); + expect(shopTsxId).toBeDefined(); + expect(shopNyseId).toBeDefined(); + expect(shopTsxId).not.toBe(shopNyseId); + + const shopInstrumentIds = ( + await f.pool.query<{ instrument_id: number }>( + `SELECT DISTINCT instrument_id FROM listing WHERE listing_id = ANY($1::int4[])`, + [[shopTsxId, shopNyseId]] + ) + ).rows; + expect(shopInstrumentIds).toHaveLength(1); + }); + + test('is idempotent on re-run and preserves permanent instrument_id / listing_id across incremental additions and updates', async () => { + const f = await createIsolatedFixture(); + const fixture = buildExitCriterionFixture(); + + // Run 1: initial insert + const run1 = await withClient(f.pool, client => persistSecurityMaster(client, fixture)); + const countsAfterRun1 = await getSevenTableCounts(f.pool); + + // Run 2: identical re-run -> 0 inserted, 0 updated everywhere, identical permanent IDs + const run2 = await withClient(f.pool, client => persistSecurityMaster(client, fixture)); + const countsAfterRun2 = await getSevenTableCounts(f.pool); + + expect(countsAfterRun2).toEqual(countsAfterRun1); + expect(run2.instrumentsInserted).toBe(0); + expect(run2.instrumentsUpdated).toBe(0); + expect(run2.instrumentsUnchanged).toBe(5); + expect(run2.identifierHistoryInserted).toBe(0); + expect(run2.listingsInserted).toBe(0); + expect(run2.listingsUpdated).toBe(0); + expect(run2.listingsUnchanged).toBe(7); + expect(run2.listingSymbolHistoryInserted).toBe(0); + expect(run2.listingSymbolHistoryUpdated).toBe(0); + expect(run2.providerMappingsInserted).toBe(0); + expect(run2.providerMappingsUpdated).toBe(0); + expect(run2.providerMappingsUnchanged).toBe(10); + expect(run2.conflictsInserted).toBe(0); + expect(run2.conflictsUnchanged).toBe(2); + expect(run2.continuitiesInserted).toBe(0); + expect(run2.continuitiesUpdated).toBe(0); + expect(run2.continuitiesUnchanged).toBe(1); + + expect(Object.fromEntries(run2.instrumentIdByIsin)).toEqual( + Object.fromEntries(run1.instrumentIdByIsin) + ); + expect(Object.fromEntries(run2.listingIdByKey)).toEqual(Object.fromEntries(run1.listingIdByKey)); + + // Run 3: add a new listing (BRK.B) + update AAPL's listedTo and SHOP.US's ibConid + const updatedStageA: StageAMatchResult = { + ...fixture.stageA, + instruments: [ + ...fixture.stageA.instruments, + { + primaryIsin: 'US0846707026', + primaryCusip: '084670702', + issuerCountry: 'US', + canonicalName: 'Berkshire Hathaway Inc.', + members: [{ source: 'eod', sourceId: 'BRK-B.US', currency: 'USD', method: 'tier1_isin' }], + }, + ], + }; + const brkKey = { + primaryIsin: 'US0846707026', + mic: 'XNYS', + tickerRoot: 'BRK', + classSuffix: 'B', + currency: 'USD', + }; + const updatedStageB: StageBMatchResult = { + ...fixture.stageB, + listings: [ + ...fixture.stageB.listings.map(listing => + listing.primaryIsin === 'CA82509L1076' && listing.mic === 'XNYS' + ? { ...listing, ibConid: 199169591, ibPrimaryExchange: 'NYSE', listedTo: '2026-11-28' } + : listing + ), + { + ...brkKey, + ibConid: null, + ibPrimaryExchange: null, + listedFrom: '1996-05-09', + listedTo: null, + }, + ], + providerMappings: [ + ...fixture.stageB.providerMappings, + { + source: 'eod', + sourceId: 'BRK-B.US', + listingKey: brkKey, + method: 'tier1_isin', + validFrom: null, + validTo: null, + }, + ], + }; + const updatedTypes = new Map(fixture.securityTypeByIsin); + updatedTypes.set('US0846707026', 'common'); + + const run3 = await withClient(f.pool, client => + persistSecurityMaster(client, { + stageA: updatedStageA, + stageB: updatedStageB, + pass6: fixture.pass6, + securityTypeByIsin: updatedTypes, + }) + ); + + expect(run3.instrumentsInserted).toBe(1); + expect(run3.listingsInserted).toBe(1); + expect(run3.listingsUpdated).toBe(1); + expect(run3.listingSymbolHistoryInserted).toBe(1); + expect(run3.listingSymbolHistoryUpdated).toBe(1); + + // Every earlier listing_id is preserved unchanged. + for (const [key, prevId] of run1.listingIdByKey.entries()) { + expect(run3.listingIdByKey.get(key)).toBe(prevId); + } + + // Class suffix formatting in listing_symbol_history: BRK.B + const brkListingId = run3.listingIdByKey.get(formatListingNaturalKey(brkKey)); + const brkHistory = ( + await f.pool.query<{ ticker: string; valid_from: string }>( + `SELECT ticker, to_char(valid_from, 'YYYY-MM-DD') AS valid_from + FROM listing_symbol_history + WHERE listing_id = $1`, + [brkListingId] + ) + ).rows; + expect(brkHistory).toEqual([{ ticker: 'BRK.B', valid_from: '1996-05-09' }]); + }); + + test('override always wins over conflicting matcher output and inserts override-only mappings', async () => { + const f = await createIsolatedFixture(); + const fixture = buildExitCriterionFixture(); + + // Seed initial listings so override can point at a real target listing_id. + const initial = await withClient(f.pool, client => persistSecurityMaster(client, fixture)); + const aaplKey = formatListingNaturalKey({ + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }); + const shopNyseKey = formatListingNaturalKey({ + primaryIsin: 'CA82509L1076', + mic: 'XNYS', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'USD', + }); + const aaplId = initial.listingIdByKey.get(aaplKey)!; + const shopNyseId = initial.listingIdByKey.get(shopNyseKey)!; + + // 1) Override an existing matcher mapping (eod, AAPL.US, 1980-12-12) -> shopNyseId + // 2) Add an override-only mapping absent from matcher output (qm, MANUAL_OVR:US, 2021-01-01) -> aaplId + await f.pool.query( + `INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by) + VALUES + ('eod', 'AAPL.US', DATE '1980-12-12', DATE '2025-12-31', $1, 'conflict resolution', 'director'), + ('qm', 'MANUAL_OVR:US', DATE '2021-01-01', NULL, $2, 'manual addition', 'director')`, + [shopNyseId, aaplId] + ); + + const runWithOverrides = await withClient(f.pool, client => + persistSecurityMaster(client, fixture) + ); + expect(runWithOverrides.overridesApplied).toBe(2); + expect(runWithOverrides.providerMappingsInserted).toBe(1); // the override-only mapping + expect(runWithOverrides.providerMappingsUpdated).toBe(1); // AAPL.US redirected by override + expect(runWithOverrides.providerMappingsUnchanged).toBe(9); // remaining 9 matcher mappings + + const rowsAfterOverride = ( + await f.pool.query<{ + source: string; + source_id: string; + valid_from: string; + valid_to: string | null; + listing_id: number; + method: string; + confidence: string; + price_corr: string | null; + }>( + `SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to, listing_id, method, confidence::text, price_corr::text + FROM provider_mapping + WHERE (source = 'eod' AND source_id = 'AAPL.US') + OR (source = 'qm' AND source_id = 'MANUAL_OVR:US') + ORDER BY source, source_id` + ) + ).rows; + expect(rowsAfterOverride).toEqual([ + { + source: 'eod', + source_id: 'AAPL.US', + valid_from: '1980-12-12', + valid_to: '2025-12-31', + listing_id: shopNyseId, + method: 'override', + confidence: '1.000', + price_corr: null, + }, + { + source: 'qm', + source_id: 'MANUAL_OVR:US', + valid_from: '2021-01-01', + valid_to: null, + listing_id: aaplId, + method: 'override', + confidence: '1.000', + price_corr: null, + }, + ]); + + // Re-running with conflicting matcher output keeps override intact with 0 overwrites. + const secondRun = await withClient(f.pool, client => persistSecurityMaster(client, fixture)); + expect(secondRun.overridesApplied).toBe(2); + expect(secondRun.providerMappingsInserted).toBe(0); + expect(secondRun.providerMappingsUpdated).toBe(0); + expect(secondRun.providerMappingsUnchanged).toBe(11); + }); + + test('replaces loader-generated listing_symbol_history interval when listed_from changes while preserving unrelated aliases', async () => { + const f = await createIsolatedFixture(); + + const stageA = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'AAPL.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + ]); + const aaplKey = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const securityTypeByIsin = new Map([['US0378331005', 'common']]); + + // Load 1: no bar span yet -> listedFrom = null -> symbol history starts at 1900-01-01 + const stageBNoSpan = matchListingsStageB({ + instruments: stageA.instruments, + eodListings: [ + { + sourceId: 'AAPL.US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + ], + ibContracts: [], + tickerSources: [], + }); + + const run1 = await withClient(f.pool, client => + persistSecurityMaster(client, { stageA, stageB: stageBNoSpan, securityTypeByIsin }) + ); + const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(aaplKey))!; + expect(run1.listingSymbolHistoryInserted).toBe(1); + + // Seed two unrelated historical aliases on the same listing that must be preserved. + await f.pool.query( + `INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, valid_to, source) + VALUES + ($1, 'OLDT', DATE '1978-01-01', DATE '1980-12-11', 'eod'), + ($1, 'AAPL', DATE '1979-06-01', DATE '1980-06-01', 'manual')`, + [aaplListingId] + ); + + // Load 2: actual first bar date is supplied -> listed_from updates from NULL to 1980-12-12 + const stageBWithSpan = matchListingsStageB({ + instruments: stageA.instruments, + eodListings: [ + { + sourceId: 'AAPL.US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '1980-12-12', lastBarDate: '2026-11-27' }, + }, + ], + ibContracts: [], + tickerSources: [], + }); + + const run2 = await withClient(f.pool, client => + persistSecurityMaster(client, { stageA, stageB: stageBWithSpan, securityTypeByIsin }) + ); + expect(run2.listingIdByKey.get(formatListingNaturalKey(aaplKey))).toBe(aaplListingId); + expect(run2.listingsInserted).toBe(0); + expect(run2.listingsUpdated).toBe(1); + expect(run2.listingSymbolHistoryInserted).toBe(0); + expect(run2.listingSymbolHistoryUpdated).toBe(1); + + const historyRows = ( + await f.pool.query<{ + ticker: string; + valid_from: string; + valid_to: string | null; + source: string; + }>( + `SELECT ticker, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to, source + FROM listing_symbol_history + WHERE listing_id = $1 + ORDER BY ticker, valid_from, source`, + [aaplListingId] + ) + ).rows; + expect(historyRows).toEqual([ + { ticker: 'AAPL', valid_from: '1979-06-01', valid_to: '1980-06-01', source: 'manual' }, + { ticker: 'AAPL', valid_from: '1980-12-12', valid_to: '2026-11-27', source: 'eod' }, + { ticker: 'OLDT', valid_from: '1978-01-01', valid_to: '1980-12-11', source: 'eod' }, + ]); + + // Load 3: identical re-run is a no-op + const run3 = await withClient(f.pool, client => + persistSecurityMaster(client, { stageA, stageB: stageBWithSpan, securityTypeByIsin }) + ); + expect(run3.listingSymbolHistoryInserted).toBe(0); + expect(run3.listingSymbolHistoryUpdated).toBe(0); + expect(run3.listingSymbolHistoryUnchanged).toBe(1); + }); + + test('removes stale 1900-01-01 provider_mapping fallback on dated rerun and is idempotent thereafter', async () => { + const f = await createIsolatedFixture(); + + const stageA = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'FB.US', + isin: 'US30303M1027', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: 'Meta Platforms Inc.', + }, + ]); + const fbKey = { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }; + const securityTypeByIsin = new Map([['US30303M1027', 'common']]); + + const makeStageB = (validFrom: string | null): StageBMatchResult => ({ + listings: [ + { + ...fbKey, + ibConid: null, + ibPrimaryExchange: null, + listedFrom: validFrom, + listedTo: null, + }, + ], + providerMappings: [ + { + source: 'eod', + sourceId: 'FB.US', + listingKey: fbKey, + method: 'tier1_isin', + validFrom, + validTo: null, + }, + ], + unresolved: [], + conflicts: [], + stats: { + totalListings: 1, + totalProviderMappings: 1, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: 1, matched: 1, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }, + }); + + // Run 1: validFrom null -> writes 1900-01-01 fallback row + const run1 = await withClient(f.pool, client => + persistSecurityMaster(client, { stageA, stageB: makeStageB(null), securityTypeByIsin }) + ); + const fbListingId = run1.listingIdByKey.get(formatListingNaturalKey(fbKey))!; + expect(run1.providerMappingsInserted).toBe(1); + expect(run1.providerMappingsUpdated).toBe(0); + expect(run1.providerMappingsUnchanged).toBe(0); + expect(run1.providerMappingsDeletedStaleFallback).toBe(0); + + const rowsAfterRun1 = ( + await f.pool.query<{ valid_from: string; listing_id: number }>( + `SELECT to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id + FROM provider_mapping + WHERE source = 'eod' AND source_id = 'FB.US' + ORDER BY valid_from` + ) + ).rows; + expect(rowsAfterRun1).toEqual([{ valid_from: DEFAULT_VALID_FROM, listing_id: fbListingId }]); + + // Run 2: real validFrom supplied -> deletes 1900-01-01 fallback and keeps only 2012-05-18 + const run2 = await withClient(f.pool, client => + persistSecurityMaster(client, { + stageA, + stageB: makeStageB('2012-05-18'), + securityTypeByIsin, + }) + ); + expect(run2.providerMappingsInserted).toBe(1); + expect(run2.providerMappingsUpdated).toBe(0); + expect(run2.providerMappingsUnchanged).toBe(0); + expect(run2.providerMappingsDeletedStaleFallback).toBe(1); + + const rowsAfterRun2 = ( + await f.pool.query<{ valid_from: string; listing_id: number }>( + `SELECT to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id + FROM provider_mapping + WHERE source = 'eod' AND source_id = 'FB.US' + ORDER BY valid_from` + ) + ).rows; + expect(rowsAfterRun2).toEqual([{ valid_from: '2012-05-18', listing_id: fbListingId }]); + + // Run 3: identical dated rerun -> idempotent (0 deletes, 1 unchanged) + const run3 = await withClient(f.pool, client => + persistSecurityMaster(client, { + stageA, + stageB: makeStageB('2012-05-18'), + securityTypeByIsin, + }) + ); + expect(run3.providerMappingsInserted).toBe(0); + expect(run3.providerMappingsUpdated).toBe(0); + expect(run3.providerMappingsUnchanged).toBe(1); + expect(run3.providerMappingsDeletedStaleFallback).toBe(0); + + const rowsAfterRun3 = ( + await f.pool.query<{ valid_from: string; listing_id: number }>( + `SELECT to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id + FROM provider_mapping + WHERE source = 'eod' AND source_id = 'FB.US' + ORDER BY valid_from` + ) + ).rows; + expect(rowsAfterRun3).toEqual([{ valid_from: '2012-05-18', listing_id: fbListingId }]); + }); + + test('preserves override-protected 1900-01-01 provider_mapping rows on dated rerun', async () => { + const f = await createIsolatedFixture(); + + const stageA = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'A.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Listing A Corp', + }, + { + source: 'eod', + sourceId: 'B.US', + isin: 'US30303M1027', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: 'Listing B Corp', + }, + ]); + const keyA = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAA', + classSuffix: '', + currency: 'USD', + }; + const keyB = { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'BBB', + classSuffix: '', + currency: 'USD', + }; + const securityTypeByIsin = new Map([ + ['US0378331005', 'common'], + ['US30303M1027', 'common'], + ]); + + const listings = [ + { ...keyA, ibConid: null, ibPrimaryExchange: null, listedFrom: '2012-05-18', listedTo: null }, + { ...keyB, ibConid: null, ibPrimaryExchange: null, listedFrom: '2012-05-18', listedTo: null }, + ]; + const emptyStats = { + totalListings: 2, + totalProviderMappings: 3, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: 3, matched: 3, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }; + + // Run 1: seed listings and three 1900-01-01 fallback mappings pointing at listing A. + const run1 = await withClient(f.pool, client => + persistSecurityMaster(client, { + stageA, + stageB: { + listings, + providerMappings: [ + { source: 'eod', sourceId: 'OVR_MAT.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null }, + { source: 'eod', sourceId: 'OVR_NEW.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null }, + { source: 'eod', sourceId: 'OVR_METHOD_ONLY.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null }, + ], + unresolved: [], + conflicts: [], + stats: emptyStats, + }, + securityTypeByIsin, + }) + ); + const listingAId = run1.listingIdByKey.get(formatListingNaturalKey(keyA))!; + const listingBId = run1.listingIdByKey.get(formatListingNaturalKey(keyB))!; + + // Materialize override for OVR_MAT.US via a persist run before the dated rerun. + await f.pool.query( + `INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by) + VALUES ('eod', 'OVR_MAT.US', DATE '1900-01-01', NULL, $1, 'already materialized override', 'director')`, + [listingBId] + ); + await withClient(f.pool, client => + persistSecurityMaster(client, { + stageA, + stageB: { + listings, + providerMappings: [ + { source: 'eod', sourceId: 'OVR_MAT.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null }, + { source: 'eod', sourceId: 'OVR_NEW.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null }, + { source: 'eod', sourceId: 'OVR_METHOD_ONLY.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null }, + ], + unresolved: [], + conflicts: [], + stats: emptyStats, + }, + securityTypeByIsin, + }) + ); + + // Newly insert override for OVR_NEW.US (still method='tier1_isin' in provider_mapping) and + // directly mark OVR_METHOD_ONLY.US as method='override' (no row in override table). + await f.pool.query( + `INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by) + VALUES ('eod', 'OVR_NEW.US', DATE '1900-01-01', NULL, $1, 'unmaterialized override', 'director')`, + [listingBId] + ); + await f.pool.query( + `UPDATE provider_mapping + SET method = 'override', confidence = 1.000, listing_id = $1 + WHERE source = 'eod' AND source_id = 'OVR_METHOD_ONLY.US' AND valid_from = DATE '1900-01-01'`, + [listingBId] + ); + + // Run 2: dated rerun for all three source IDs -> none of the 1900-01-01 rows may be deleted. + const run2 = await withClient(f.pool, client => + persistSecurityMaster(client, { + stageA, + stageB: { + listings, + providerMappings: [ + { source: 'eod', sourceId: 'OVR_MAT.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null }, + { source: 'eod', sourceId: 'OVR_NEW.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null }, + { source: 'eod', sourceId: 'OVR_METHOD_ONLY.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null }, + ], + unresolved: [], + conflicts: [], + stats: emptyStats, + }, + securityTypeByIsin, + }) + ); + expect(run2.providerMappingsDeletedStaleFallback).toBe(0); + expect(run2.overridesApplied).toBe(2); + + const rows = ( + await f.pool.query<{ + source_id: string; + valid_from: string; + listing_id: number; + method: string; + confidence: string; + }>( + `SELECT source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id, method, confidence::text + FROM provider_mapping + WHERE source = 'eod' + ORDER BY source_id, valid_from` + ) + ).rows; + + expect(rows).toEqual([ + { source_id: 'OVR_MAT.US', valid_from: '1900-01-01', listing_id: listingBId, method: 'override', confidence: '1.000' }, + { source_id: 'OVR_MAT.US', valid_from: '2012-05-18', listing_id: listingAId, method: 'tier1_isin', confidence: '0.990' }, + { source_id: 'OVR_METHOD_ONLY.US', valid_from: '1900-01-01', listing_id: listingBId, method: 'override', confidence: '1.000' }, + { source_id: 'OVR_METHOD_ONLY.US', valid_from: '2012-05-18', listing_id: listingAId, method: 'tier1_isin', confidence: '0.990' }, + { source_id: 'OVR_NEW.US', valid_from: '1900-01-01', listing_id: listingBId, method: 'override', confidence: '1.000' }, + { source_id: 'OVR_NEW.US', valid_from: '2012-05-18', listing_id: listingAId, method: 'tier1_isin', confidence: '0.990' }, + ]); + }); + + test('stale-fallback cleanup preserves absent pairs, other sources, dated rows, and mixed runs while removing cross-listing fallbacks', async () => { + const f = await createIsolatedFixture(); + + const stageA = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'A.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Listing A Corp', + }, + { + source: 'eod', + sourceId: 'B.US', + isin: 'US30303M1027', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: 'Listing B Corp', + }, + ]); + const keyA = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAA', + classSuffix: '', + currency: 'USD', + }; + const keyB = { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'BBB', + classSuffix: '', + currency: 'USD', + }; + const securityTypeByIsin = new Map([ + ['US0378331005', 'common'], + ['US30303M1027', 'common'], + ]); + const listings = [ + { ...keyA, ibConid: null, ibPrimaryExchange: null, listedFrom: '2010-01-04', listedTo: null }, + { ...keyB, ibConid: null, ibPrimaryExchange: null, listedFrom: '2018-06-01', listedTo: null }, + ]; + const baseStats = { + totalListings: 2, + totalProviderMappings: 0, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }; + + // Run 1: seed initial rows covering all preservation boundaries + cross-listing fallback. + const run1 = await withClient(f.pool, client => + persistSecurityMaster(client, { + stageA, + stageB: { + listings, + providerMappings: [ + // Absent from Run 2 -> must be kept + { source: 'eod', sourceId: 'ABSENT.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null }, + // Same source_id under a different source ('qm') -> must be kept when 'eod' reruns dated + { source: 'qm', sourceId: 'SHARED.ID', listingKey: keyA, method: 'tier3_ticker_span', validFrom: null, validTo: null }, + { source: 'eod', sourceId: 'SHARED.ID', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null }, + // Existing dated row -> must never be deleted when another dated row is added + { source: 'eod', sourceId: 'DATED_KEEP.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2010-01-04', validTo: '2019-12-31' }, + // Mixed run (both 1900-01-01 and dated in Run 2) -> both must be kept + { source: 'eod', sourceId: 'MIXED.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: '2014-12-31' }, + // Cross-listing reassignment: 1900-01-01 points at listing A, Run 2 maps dated to listing B + { source: 'eod', sourceId: 'REASSIGN.US', listingKey: keyA, method: 'tier1_isin', validFrom: null, validTo: null }, + ], + unresolved: [], + conflicts: [], + stats: baseStats, + }, + securityTypeByIsin, + }) + ); + const listingAId = run1.listingIdByKey.get(formatListingNaturalKey(keyA))!; + const listingBId = run1.listingIdByKey.get(formatListingNaturalKey(keyB))!; + expect(run1.providerMappingsDeletedStaleFallback).toBe(0); + + // Run 2: + // - ABSENT.US omitted + // - (eod, SHARED.ID) dated -> deletes only (eod, SHARED.ID, 1900-01-01), keeps (qm, SHARED.ID, 1900-01-01) + // - (eod, DATED_KEEP.US) adds a second dated row -> keeps 2010-01-04 + // - (eod, MIXED.US) supplies both 1900-01-01 and 2015-01-01 -> keeps both + // - (eod, REASSIGN.US) dated to listing B -> deletes stale 1900-01-01 pointing at listing A + const run2 = await withClient(f.pool, client => + persistSecurityMaster(client, { + stageA, + stageB: { + listings, + providerMappings: [ + { source: 'eod', sourceId: 'SHARED.ID', listingKey: keyA, method: 'tier1_isin', validFrom: '2012-05-18', validTo: null }, + { source: 'eod', sourceId: 'DATED_KEEP.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2020-01-02', validTo: null }, + { source: 'eod', sourceId: 'MIXED.US', listingKey: keyA, method: 'tier1_isin', validFrom: DEFAULT_VALID_FROM, validTo: '2014-12-31' }, + { source: 'eod', sourceId: 'MIXED.US', listingKey: keyA, method: 'tier1_isin', validFrom: '2015-01-01', validTo: null }, + { source: 'eod', sourceId: 'REASSIGN.US', listingKey: keyB, method: 'tier1_isin', validFrom: '2018-06-01', validTo: null }, + ], + unresolved: [], + conflicts: [], + stats: baseStats, + }, + securityTypeByIsin, + }) + ); + + // Exactly 2 stale fallbacks removed: (eod, SHARED.ID) and (eod, REASSIGN.US) + expect(run2.providerMappingsDeletedStaleFallback).toBe(2); + expect(run2.providerMappingsInserted).toBe(4); + expect(run2.providerMappingsUpdated).toBe(0); + expect(run2.providerMappingsUnchanged).toBe(1); // (eod, MIXED.US, 1900-01-01) + + const allRows = ( + await f.pool.query<{ + source: string; + source_id: string; + valid_from: string; + listing_id: number; + }>( + `SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, listing_id + FROM provider_mapping + ORDER BY source, source_id, valid_from` + ) + ).rows; + + expect(allRows).toEqual([ + { source: 'eod', source_id: 'ABSENT.US', valid_from: '1900-01-01', listing_id: listingAId }, + { source: 'eod', source_id: 'DATED_KEEP.US', valid_from: '2010-01-04', listing_id: listingAId }, + { source: 'eod', source_id: 'DATED_KEEP.US', valid_from: '2020-01-02', listing_id: listingAId }, + { source: 'eod', source_id: 'MIXED.US', valid_from: '1900-01-01', listing_id: listingAId }, + { source: 'eod', source_id: 'MIXED.US', valid_from: '2015-01-01', listing_id: listingAId }, + { source: 'eod', source_id: 'REASSIGN.US', valid_from: '2018-06-01', listing_id: listingBId }, + { source: 'eod', source_id: 'SHARED.ID', valid_from: '2012-05-18', listing_id: listingAId }, + { source: 'qm', source_id: 'SHARED.ID', valid_from: '1900-01-01', listing_id: listingAId }, + ]); + }); + + test('stale-fallback deletes span multiple chunkSize batches in real PostgreSQL and roll back with the persist transaction', async () => { + const f = await createIsolatedFixture(); + + const stageA = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'A.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Listing A Corp', + }, + ]); + const keyA = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAA', + classSuffix: '', + currency: 'USD', + }; + const securityTypeByIsin = new Map([['US0378331005', 'common']]); + const makeStageB = (sourceIds: readonly string[], validFrom: string | null): StageBMatchResult => ({ + listings: [ + { ...keyA, ibConid: null, ibPrimaryExchange: null, listedFrom: '2010-01-04', listedTo: null }, + ], + providerMappings: sourceIds.map(sourceId => ({ + source: 'eod' as const, + sourceId, + listingKey: keyA, + method: 'tier1_isin' as const, + validFrom, + validTo: null, + })), + unresolved: [], + conflicts: [], + stats: { + totalListings: 1, + totalProviderMappings: sourceIds.length, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: sourceIds.length, matched: sourceIds.length, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }, + }); + const fallbackCount = async (): Promise => + Number( + ( + await f.pool.query<{ n: string }>( + `SELECT count(*) AS n FROM provider_mapping WHERE valid_from = DATE '1900-01-01'` + ) + ).rows[0]!.n + ); + + const rollbackIds = ['RB0.US', 'RB1.US', 'RB2.US']; + const chunkIds = ['C0.US', 'C1.US', 'C2.US', 'C3.US', 'C4.US']; + + // Seed 8 fallback rows. + const seed = await withClient(f.pool, client => + persistSecurityMaster(client, { + stageA, + stageB: makeStageB([...rollbackIds, ...chunkIds], null), + securityTypeByIsin, + }) + ); + expect(seed.providerMappingsInserted).toBe(8); + expect(await fallbackCount()).toBe(8); + const listingAId = seed.listingIdByKey.get(formatListingNaturalKey(keyA))!; + + // Atomicity: make the override-enforcement step (which runs after the stale-fallback DELETE) + // fail inside the same transaction; the deletes must roll back with it. + await f.pool.query( + `CREATE FUNCTION reject_override_write() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'qa: forced failure after stale-fallback delete'; END $$` + ); + await f.pool.query( + `CREATE TRIGGER reject_override_write BEFORE INSERT ON provider_mapping + FOR EACH ROW WHEN (NEW.method = 'override') EXECUTE FUNCTION reject_override_write()` + ); + await f.pool.query( + `INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by) + VALUES ('eod', 'TRIGGER_ONLY.US', DATE '1900-01-01', NULL, $1, 'qa forced failure', 'qa')`, + [listingAId] + ); + await expect( + withClient(f.pool, client => + persistSecurityMaster( + client, + { stageA, stageB: makeStageB(rollbackIds, '2012-05-18'), securityTypeByIsin }, + { chunkSize: 2 } + ) + ) + ).rejects.toThrow('qa: forced failure after stale-fallback delete'); + expect(await fallbackCount()).toBe(8); + expect( + Number( + ( + await f.pool.query<{ n: string }>( + `SELECT count(*) AS n FROM provider_mapping WHERE valid_from = DATE '2012-05-18'` + ) + ).rows[0]!.n + ) + ).toBe(0); + + await f.pool.query(`DROP TRIGGER reject_override_write ON provider_mapping`); + await f.pool.query(`DELETE FROM override WHERE source_id = 'TRIGGER_ONLY.US'`); + // Removing the override row leaves its 1900-01-01 provider_mapping row absent (never written). + + // Chunking: 5 dated-only pairs at chunkSize 2 -> 3 DELETE batches whose counts sum to 5. + const chunked = await withClient(f.pool, client => + persistSecurityMaster( + client, + { stageA, stageB: makeStageB(chunkIds, '2012-05-18'), securityTypeByIsin }, + { chunkSize: 2 } + ) + ); + expect(chunked.providerMappingsDeletedStaleFallback).toBe(5); + expect(chunked.providerMappingsInserted).toBe(5); + expect(chunked.providerMappingsUpdated).toBe(0); + expect(chunked.providerMappingsUnchanged).toBe(0); + + const remaining = ( + await f.pool.query<{ source_id: string; valid_from: string }>( + `SELECT source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from + FROM provider_mapping + ORDER BY source_id, valid_from` + ) + ).rows; + expect(remaining).toEqual([ + ...chunkIds.map(source_id => ({ source_id, valid_from: '2012-05-18' })), + ...rollbackIds.map(source_id => ({ source_id, valid_from: '1900-01-01' })), + ]); + }); + + test('persists Stage A, Stage B, and Pass 6 conflicts once and never reopens or modifies non-open rows', async () => { + const f = await createIsolatedFixture(); + const fixture = buildExitCriterionFixture(); + + const pass6WithConflict: DelistingChainResult = { + ...fixture.pass6, + conflicts: [ + { + conflictKind: 'ambiguous_otc_continuation', + detail: { + primaryIsin: 'US78486Q1013', + currency: 'USD', + fromListingKeys: [], + toListingKeys: [], + candidateListingKeys: [], + listedFrom: null, + listedTo: '2023-03-10', + reason: 'two OTC candidates', + }, + }, + ], + }; + + const run1 = await withClient(f.pool, client => + persistSecurityMaster(client, { ...fixture, pass6: pass6WithConflict }) + ); + expect(run1.conflictsInserted).toBe(3); + + // Manually resolve the Pass 6 conflict row. + await f.pool.query( + `UPDATE resolution_conflict + SET status = 'resolved', resolved_at = TIMESTAMPTZ '2026-11-27T12:00:00Z' + WHERE source = 'pass6' AND source_id = 'US78486Q1013' AND conflict_kind = 'ambiguous_otc_continuation'` + ); + + const run2 = await withClient(f.pool, client => + persistSecurityMaster(client, { ...fixture, pass6: pass6WithConflict }) + ); + expect(run2.conflictsInserted).toBe(0); + expect(run2.conflictsUnchanged).toBe(3); + + const conflictRows = ( + await f.pool.query<{ + source: string; + source_id: string; + conflict_kind: string; + status: string; + resolved_at: Date | null; + }>( + `SELECT source, source_id, conflict_kind, status, resolved_at + FROM resolution_conflict + ORDER BY source, source_id, conflict_kind` + ) + ).rows; + expect(conflictRows).toHaveLength(3); + const pass6Row = conflictRows.find(r => r.source === 'pass6'); + expect(pass6Row?.status).toBe('resolved'); + expect(pass6Row?.resolved_at).not.toBeNull(); + }); + + test('skips and counts instruments/listings/mappings/continuities without guessing on missing metadata or unknown MIC', async () => { + const f = await createIsolatedFixture(); + + const stageA = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'VALID.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + { + source: 'eod', + sourceId: 'NONAME.US', + isin: 'US30303M1027', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: null, + }, + { + source: 'eod', + sourceId: 'NOTYPE.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'No Security Type Corp', + }, + ]); + + const validKey = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const unknownMicKey = { + primaryIsin: 'US0378331005', + mic: 'XXXX', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const noNameKey = { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }; + const noTypeKey = { + primaryIsin: 'US78486Q1013', + mic: 'XNAS', + tickerRoot: 'SIVB', + classSuffix: '', + currency: 'USD', + }; + + const stageB: StageBMatchResult = { + listings: [ + { ...validKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null }, + { ...unknownMicKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null }, + { ...noNameKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null }, + { ...noTypeKey, ibConid: null, ibPrimaryExchange: null, listedFrom: '2020-01-01', listedTo: null }, + ], + providerMappings: [ + { source: 'eod', sourceId: 'AAPL.US', listingKey: validKey, method: 'tier1_isin', validFrom: null, validTo: null }, + { source: 'eod', sourceId: 'AAPL.XX', listingKey: unknownMicKey, method: 'tier1_isin', validFrom: null, validTo: null }, + { source: 'eod', sourceId: 'FB.US', listingKey: noNameKey, method: 'tier1_isin', validFrom: null, validTo: null }, + ], + unresolved: [], + conflicts: [], + stats: { + totalListings: 4, + totalProviderMappings: 3, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: 3, matched: 3, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }, + }; + + const pass6: DelistingChainResult = { + continuities: [ + { + fromListingKey: noTypeKey, + toListingKey: validKey, + effectiveDate: '2023-03-28', + kind: 'otc_delist_transfer', + }, + ], + listingOutcomes: [ + { listingKey: validKey, delistReason: 'active', terminalReturn: null }, + { listingKey: unknownMicKey, delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, + ], + conflicts: [], + stats: { + totalInputListings: 2, + processedListings: 2, + skippedMalformedEntries: 0, + skippedInvalidDates: 0, + skippedDuplicateKeys: 0, + continuitiesCreated: 1, + conflictsDetected: 0, + byOutcome: { active: 1, moved_to_otc: 0, bankruptcy_cancelled: 0, unknown_involuntary: 1 }, + }, + }; + + const result = await withClient(f.pool, client => + persistSecurityMaster(client, { + stageA, + stageB, + pass6, + securityTypeByIsin: new Map([ + ['US0378331005', 'common'], + ['US30303M1027', 'common'], + ]), + }) + ); + + expect(result.instrumentsInserted).toBe(1); + expect(result.instrumentsSkipped).toBe(2); + expect(result.skippedByReason.instruments).toEqual({ + missing_canonical_name: 1, + missing_security_type: 1, + }); + expect(result.listingsInserted).toBe(1); + expect(result.listingsSkipped).toBe(3); + expect(result.skippedByReason.listings).toEqual({ + skipped_instrument: 2, + missing_instrument: 0, + unknown_mic: 1, + }); + expect(result.providerMappingsInserted).toBe(1); + expect(result.providerMappingsSkipped).toBe(2); + expect(result.pass6OutcomesApplied).toBe(1); + expect(result.pass6OutcomesSkipped).toBe(1); + expect(result.continuitiesInserted).toBe(0); + expect(result.continuitiesSkipped).toBe(1); + expect(result.skippedByReason.continuities.missing_from_listing).toBe(1); + }); + + test('rolls back all 7 tables atomically on a late CHECK constraint violation after earlier phases wrote changes', async () => { + const f = await createIsolatedFixture(); + const fixture = buildExitCriterionFixture(); + + // Seed all 7 tables so both updates to existing rows and new inserts are exercised. + await withClient(f.pool, client => persistSecurityMaster(client, fixture)); + + const snapshotSevenTables = async () => ({ + instrument: ( + await f.pool.query( + `SELECT instrument_id, btrim(primary_isin) AS primary_isin, btrim(primary_cusip) AS primary_cusip, + canonical_name, security_type, btrim(issuer_country) AS issuer_country + FROM instrument ORDER BY instrument_id` + ) + ).rows, + instrument_identifier_history: ( + await f.pool.query( + `SELECT instrument_id, id_type, id_value, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to, source + FROM instrument_identifier_history ORDER BY id_type, id_value, valid_from` + ) + ).rows, + listing: ( + await f.pool.query( + `SELECT listing_id, instrument_id, mic, ticker_root, class_suffix, btrim(currency) AS currency, + ib_conid, ib_primary_exchange, to_char(listed_from, 'YYYY-MM-DD') AS listed_from, + to_char(listed_to, 'YYYY-MM-DD') AS listed_to, delist_reason, terminal_return + FROM listing ORDER BY listing_id` + ) + ).rows, + listing_symbol_history: ( + await f.pool.query( + `SELECT listing_id, ticker, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to, source + FROM listing_symbol_history ORDER BY listing_id, ticker, valid_from` + ) + ).rows, + provider_mapping: ( + await f.pool.query( + `SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to, listing_id, method, + confidence::text, price_corr::text + FROM provider_mapping ORDER BY source, source_id, valid_from` + ) + ).rows, + resolution_conflict: ( + await f.pool.query( + `SELECT conflict_id, source, source_id, conflict_kind, detail, status + FROM resolution_conflict ORDER BY conflict_id` + ) + ).rows, + corporate_action_continuity: ( + await f.pool.query( + `SELECT from_listing_id, to_listing_id, to_char(effective_date, 'YYYY-MM-DD') AS effective_date, kind + FROM corporate_action_continuity ORDER BY from_listing_id, effective_date` + ) + ).rows, + }); + + const before = await snapshotSevenTables(); + + // Mutate phases 1-6 (update existing instrument/listing, add new instrument/listing/mapping/conflict), + // then fail in phase 7 (corporate_action_continuity.kind CHECK constraint). + const newIsin = 'US0846707026'; + const newKey = { + primaryIsin: newIsin, + mic: 'XNYS', + tickerRoot: 'BRK', + classSuffix: 'B', + currency: 'USD', + }; + const mutatedStageA: StageAMatchResult = { + ...fixture.stageA, + instruments: [ + ...fixture.stageA.instruments.map(inst => + inst.primaryIsin === 'US0378331005' + ? { ...inst, canonicalName: 'Apple Inc. MUTATED' } + : inst + ), + { + primaryIsin: newIsin, + primaryCusip: '084670702', + issuerCountry: 'US', + canonicalName: 'Berkshire Hathaway Inc.', + members: [{ source: 'eod', sourceId: 'BRK-B.US', currency: 'USD', method: 'tier1_isin' }], + }, + ], + conflicts: [ + ...fixture.stageA.conflicts, + { + source: 'eod', + sourceId: 'ROLLBACK_TEST.US', + conflictKind: 'isin_cusip_mismatch', + detail: { isin: newIsin, cusip: '084670702', country: 'US', derivedIsin: null }, + }, + ], + }; + const mutatedStageB: StageBMatchResult = { + ...fixture.stageB, + listings: [ + ...fixture.stageB.listings.map(l => + l.primaryIsin === 'CA82509L1076' && l.mic === 'XNYS' + ? { ...l, ibConid: 999999, listedTo: '2026-11-28' } + : l + ), + { + ...newKey, + ibConid: null, + ibPrimaryExchange: null, + listedFrom: '1996-05-09', + listedTo: null, + }, + ], + providerMappings: [ + ...fixture.stageB.providerMappings, + { + source: 'eod', + sourceId: 'BRK-B.US', + listingKey: newKey, + method: 'tier1_isin', + validFrom: null, + validTo: null, + }, + ], + }; + const mutatedPass6: DelistingChainResult = { + ...fixture.pass6, + continuities: [ + ...fixture.pass6.continuities.map(c => ({ + ...c, + kind: 'bogus_kind' as typeof c.kind, + })), + ], + }; + const mutatedTypes = new Map(fixture.securityTypeByIsin); + mutatedTypes.set(newIsin, 'common'); + + await expect( + withClient(f.pool, client => + persistSecurityMaster(client, { + stageA: mutatedStageA, + stageB: mutatedStageB, + pass6: mutatedPass6, + securityTypeByIsin: mutatedTypes, + }) + ) + ).rejects.toThrow(/corporate_action_continuity|kind/); + + const after = await snapshotSevenTables(); + expect(after).toEqual(before); + }); + + test('rejects overlapping calls on one shared PoolClient without creating duplicate listings', async () => { + const f = await createIsolatedFixture(); + + const stageA = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'AAPL.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + ]); + const securityTypeByIsin = new Map([['US0378331005', 'common']]); + const emptyListingsStageB = matchListingsStageB({ + instruments: stageA.instruments, + eodListings: [], + ibContracts: [], + tickerSources: [], + }); + const withNewListingStageB = matchListingsStageB({ + instruments: stageA.instruments, + eodListings: [ + { + sourceId: 'AAPL.US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '1980-12-12', lastBarDate: '2026-11-27' }, + }, + ], + ibContracts: [], + tickerSources: [], + }); + + // Seed the existing instrument first, then overlap two loads adding the same new listing on one client. + await withClient(f.pool, client => + persistSecurityMaster(client, { stageA, stageB: emptyListingsStageB, securityTypeByIsin }) + ); + + const sharedClient = await f.pool.connect(); + try { + const [first, second] = await Promise.allSettled([ + persistSecurityMaster(sharedClient, { + stageA, + stageB: withNewListingStageB, + securityTypeByIsin, + }), + persistSecurityMaster(sharedClient, { + stageA, + stageB: withNewListingStageB, + securityTypeByIsin, + }), + ]); + + expect(first.status).toBe('fulfilled'); + expect(second.status).toBe('rejected'); + if (second.status === 'rejected') { + expect(String(second.reason)).toMatch(/overlapping calls on the same client/); + } + + const counts = await getSevenTableCounts(f.pool); + expect(counts.instrument).toBe(1); + expect(counts.listing).toBe(1); + expect(counts.provider_mapping).toBe(1); + + // Sequential reuse of the same PoolClient succeeds once the first call has finished. + const followUp = await persistSecurityMaster(sharedClient, { + stageA, + stageB: withNewListingStageB, + securityTypeByIsin, + }); + expect(followUp.listingsInserted).toBe(0); + expect(followUp.listingsUnchanged).toBe(1); + } finally { + sharedClient.release(); + } + }); + + test('serializes two concurrent writers via pg_advisory_xact_lock without duplicate listings', async () => { + const f = await createIsolatedFixture(); + const fixture = buildExitCriterionFixture(); + + const [c1, c2] = await Promise.all([f.pool.connect(), f.pool.connect()]); + try { + const [r1, r2] = await Promise.all([ + persistSecurityMaster(c1, fixture), + persistSecurityMaster(c2, fixture), + ]); + + expect(Object.fromEntries(r1.listingIdByKey)).toEqual(Object.fromEntries(r2.listingIdByKey)); + expect(r1.listingsInserted + r2.listingsInserted).toBe(7); + + const counts = await getSevenTableCounts(f.pool); + expect(counts.instrument).toBe(5); + expect(counts.listing).toBe(7); + expect(counts.provider_mapping).toBe(10); + } finally { + c1.release(); + c2.release(); + } + }); + + test('batches SQL statements in O(ceil(N / chunkSize)) round trips on a real PoolClient', async () => { + const f = await createIsolatedFixture(); + const input = buildSyntheticBenchmarkInput(600); + + let queryCount = 0; + const result = await withClient(f.pool, async client => { + const countingClient: SecurityMasterQueryable = { + release: () => undefined, + query: (text, values) => { + queryCount += 1; + return client.query(text, values as unknown[]); + }, + }; + return persistSecurityMaster(countingClient, input, { chunkSize: 200 }); + }); + + expect(result.instrumentsInserted).toBe(600); + expect(result.listingsInserted).toBe(600); + expect(result.providerMappingsInserted).toBe(1800); + expect(queryCount).toBeLessThan(40); + }); + + test( + 'fixed-seed throughput benchmark: persists 20,000 instruments, 20,000 listings, and 60,000 mappings', + async () => { + const f = await createIsolatedFixture(120_000); + const instrumentCount = 20_000; + const input = buildSyntheticBenchmarkInput(instrumentCount); + + const t0 = performance.now(); + const result = await withClient(f.pool, client => persistSecurityMaster(client, input)); + const elapsedSec = (performance.now() - t0) / 1000; + + const totalCoreRows = + result.instrumentsInserted + result.listingsInserted + result.providerMappingsInserted; + const totalAllRows = + totalCoreRows + result.identifierHistoryInserted + result.listingSymbolHistoryInserted; + + expect(result.instrumentsInserted).toBe(instrumentCount); + expect(result.listingsInserted).toBe(instrumentCount); + expect(result.providerMappingsInserted).toBe(instrumentCount * 3); + + const counts = await getSevenTableCounts(f.pool); + expect(counts.instrument).toBe(instrumentCount); + expect(counts.listing).toBe(instrumentCount); + expect(counts.provider_mapping).toBe(instrumentCount * 3); + + console.info( + `[security-master-persist benchmark] ${instrumentCount} instruments, ${instrumentCount} listings, ${instrumentCount * 3} mappings (${totalAllRows} total rows) persisted in ${elapsedSec.toFixed(2)}s (${Math.round(totalCoreRows / elapsedSec)} core rows/s, ${Math.round(totalAllRows / elapsedSec)} total rows/s)` + ); + }, + 120_000 + ); +}); diff --git a/test/postgres/security-master-run.test.ts b/test/postgres/security-master-run.test.ts new file mode 100644 index 00000000..06561ad4 --- /dev/null +++ b/test/postgres/security-master-run.test.ts @@ -0,0 +1,511 @@ +import { randomUUID } from 'node:crypto'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool, type PoolClient } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import type { BarSpan } from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; +import { + classifySourceExchanges, + composeSecurityMasterRun, + CONTINUITY_KIND_OTC_DELIST_TRANSFER, + formatListingNaturalKey, + persistSecurityMaster, + type FxRateByDateRecord, + type SampleCloseRecord, + type SecurityMasterQueryable, + type SecurityMasterSourcesResult, + type SecurityType, + type StageASourceRecord, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBTickerSourceInput, +} from '../../apps/stock/data-pipeline/src/security-master'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('security-master-run-pg-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +async function createIsolatedFixture(statementTimeoutMs = 15_000) { + 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 pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=${statementTimeoutMs} -c lock_timeout=15000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + 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: 'master' }); + + return { pool, schema, postgres }; +} + +async function withClient(pool: Pool, fn: (client: PoolClient) => Promise): Promise { + const client = await pool.connect(); + try { + return await fn(client); + } finally { + client.release(); + } +} + +async function getSevenTableCounts(pool: Pool): Promise> { + const tables = [ + 'instrument', + 'instrument_identifier_history', + 'listing', + 'listing_symbol_history', + 'provider_mapping', + 'resolution_conflict', + 'corporate_action_continuity', + ] as const; + const counts: Record = {}; + for (const table of tables) { + const res = await pool.query<{ count: number }>(`SELECT count(*)::int AS count FROM ${table}`); + counts[table] = res.rows[0]?.count ?? -1; + } + return counts; +} + +function makeEmptyCollectionStats( + collection: 'eodSymbols' | 'ibSymbols' | 'qmSymbols' | 'ceoSymbols' | 'eodSymbolChange' +) { + return { + collection, + docsRead: 0, + emitted: 0, + invalidIdentifiersNulled: 0, + skips: { + missingId: 0, + invalidFieldType: 0, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 0, + outOfScopeCountry: 0, + }, + }; +} + +function buildComposedExitCriterionRun() { + const stageARecords: StageASourceRecord[] = [ + { + source: 'ib', + sourceId: '265598', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + { + source: 'eod', + sourceId: 'AAPL.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc', + }, + { + source: 'eod', + sourceId: 'FB_OLD.US', + isin: 'US30303M1027', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: 'Meta Platforms Inc', + }, + { + source: 'eod', + sourceId: 'FB_ETF.US', + isin: 'US4642872000', + cusip: '464287200', + country: 'US', + currency: 'USD', + name: 'FB Thematic ETF', + }, + { + source: 'eod', + sourceId: 'SIVB.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SIVBQ.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SHOP.TO', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'CAD', + name: 'Shopify Inc.', + }, + { + source: 'eod', + sourceId: 'SHOP.US', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'USD', + name: 'Shopify Inc.', + }, + { + source: 'ib', + sourceId: '2001', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'CAD', + name: 'Shopify Inc.', + }, + { + source: 'ib', + sourceId: '2002', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'USD', + name: 'Shopify Inc.', + }, + ]; + + const eodListings: StageBEodListingInput[] = [ + { sourceId: 'AAPL.US', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'FB_OLD.US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'FB_ETF.US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'SIVB.US', ticker: 'SIVB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'SIVBQ.US', ticker: 'SIVBQ', mic: 'OTCM', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'SHOP.TO', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue', currency: 'CAD', span: null }, + { sourceId: 'SHOP.US', ticker: 'SHOP', mic: 'XNYS', role: 'primary_venue', currency: 'USD', span: null }, + ]; + + const ibContracts: StageBIbContractInput[] = [ + { sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: '2001', conid: 2001, currency: 'CAD', primaryExchange: 'TSE' }, + { sourceId: '2002', conid: 2002, currency: 'USD', primaryExchange: 'NYSE' }, + ]; + + const tickerSources: StageBTickerSourceInput[] = [ + { source: 'qm', sourceId: 'AAPL:US', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { source: 'qm', sourceId: 'FB_OLD:US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { source: 'qm', sourceId: 'FB_ETF:US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { source: 'qm', sourceId: 'SHOP:CA', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue', currency: 'CAD', span: null }, + { + source: 'ceo', + sourceId: 'ceo:SHOP', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-11-28' }, + }, + ]; + + const barSpans: BarSpan[] = [ + { source: 'eod', sourceId: 'AAPL.US', firstBarDate: '2010-01-04', lastBarDate: '2025-11-28', barCount: 4000 }, + { source: 'eod', sourceId: 'FB_OLD.US', firstBarDate: '2012-05-18', lastBarDate: '2022-06-08', barCount: 2530 }, + { source: 'eod', sourceId: 'FB_ETF.US', firstBarDate: '2025-01-02', lastBarDate: '2025-11-28', barCount: 230 }, + { source: 'eod', sourceId: 'SIVB.US', firstBarDate: '2015-01-02', lastBarDate: '2023-03-10', barCount: 2060 }, + { source: 'eod', sourceId: 'SIVBQ.US', firstBarDate: '2023-03-28', lastBarDate: '2024-11-07', barCount: 410 }, + { source: 'eod', sourceId: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 }, + { source: 'eod', sourceId: 'SHOP.US', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 }, + { source: 'qm', sourceId: 'AAPL:US', firstBarDate: '2015-01-02', lastBarDate: '2025-11-28', barCount: 2700 }, + { source: 'qm', sourceId: 'FB_OLD:US', firstBarDate: '2014-01-02', lastBarDate: '2022-06-08', barCount: 2100 }, + { source: 'qm', sourceId: 'FB_ETF:US', firstBarDate: '2025-02-03', lastBarDate: '2025-11-28', barCount: 205 }, + { source: 'qm', sourceId: 'SHOP:CA', firstBarDate: '2018-01-02', lastBarDate: '2025-11-28', barCount: 1980 }, + ]; + + const securityTypeByIsin = new Map([ + ['US0378331005', 'common'], + ['US30303M1027', 'common'], + ['US4642872000', 'etf'], + ['US78486Q1013', 'common'], + ['CA82509L1076', 'common'], + ]); + + const sources: SecurityMasterSourcesResult = { + stageARecords, + stageBInput: { + eodListings, + ibContracts, + tickerSources, + symbolChanges: [], + }, + securityTypeRecords: [], + securityTypeByIsin, + securityTypeStats: { + totalRecords: 0, + mapped: 0, + missingType: 0, + unknownType: 0, + invalidIsin: 0, + isinsResolved: securityTypeByIsin.size, + isinsConflicting: 0, + conflictsTruncated: 0, + }, + securityTypeLoaderStats: { + totalRecords: 0, + mapped: 0, + missingType: 0, + unknownType: 0, + invalidIsin: 0, + isinsResolved: securityTypeByIsin.size, + isinsConflicting: 0, + conflictsTruncated: 0, + }, + unknownSecurityTypes: [], + securityTypeConflicts: [], + stats: { + eodSymbols: makeEmptyCollectionStats('eodSymbols'), + ibSymbols: makeEmptyCollectionStats('ibSymbols'), + qmSymbols: makeEmptyCollectionStats('qmSymbols'), + ceoSymbols: makeEmptyCollectionStats('ceoSymbols'), + eodSymbolChange: makeEmptyCollectionStats('eodSymbolChange'), + }, + }; + + const exchanges = classifySourceExchanges([ + { source: 'eod', sourceCode: 'NASDAQ', name: 'NASDAQ', country: 'US', operatingMic: 'XNAS' }, + { source: 'eod', sourceCode: 'NYSE', name: 'NYSE', country: 'US', operatingMic: 'XNYS' }, + { source: 'eod', sourceCode: 'TO', name: 'TSX', country: 'CA', operatingMic: 'XTSE' }, + { source: 'eod', sourceCode: 'OTC', name: 'OTC', country: 'US', operatingMic: 'OTCM' }, + ]); + + const dates = [ + '2025-01-02', + '2025-01-03', + '2025-01-06', + '2025-01-07', + '2025-01-08', + '2025-01-09', + ]; + const aaplPrices = [185.0, 188.5, 184.2, 191.0, 195.4, 193.1]; + const shopCadPrices = [140.0, 145.0, 138.0, 148.5, 152.0, 149.0]; + + const sampleCloses: SampleCloseRecord[] = []; + const fxRates: FxRateByDateRecord[] = []; + for (let i = 0; i < dates.length; i++) { + const date = dates[i]!; + const aapl = aaplPrices[i]!; + const shop = shopCadPrices[i]!; + fxRates.push({ date, usdCad: 1.38 + i * 0.005 }); + // AAPL: confirmed + sampleCloses.push({ source: 'eod', sourceId: 'AAPL.US', date, close: aapl }); + sampleCloses.push({ source: 'qm', sourceId: 'AAPL:US', date, close: aapl * 1.001 }); + // SHOP XTSE: two Pass 4 mismatches sharing left endpoint (ceo:SHOP vs eod:SHOP.TO, ceo:SHOP vs qm:SHOP:CA) + // and eod:SHOP.TO vs qm:SHOP:CA -> all three pairs mismatch! + sampleCloses.push({ source: 'ceo', sourceId: 'ceo:SHOP', date, close: shop }); + sampleCloses.push({ source: 'eod', sourceId: 'SHOP.TO', date, close: shop * 1.5 }); + sampleCloses.push({ source: 'qm', sourceId: 'SHOP:CA', date, close: shop * 2.2 }); + } + + return composeSecurityMasterRun( + { sources, barSpans, exchanges, sampleCloses, fxRates }, + { asOfDate: '2025-11-28' } + ); +} + +describe('composeSecurityMasterRun -> persistSecurityMaster PostgreSQL integration', () => { + test('persists FB vs FB-ETF distinct listing_ids, SIVB -> SIVBQ continuity, Pass 4 conflicts (including shared left endpoint), and is idempotent on re-run', async () => { + const { pool } = await createIsolatedFixture(); + const composed = buildComposedExitCriterionRun(); + + // First run + const first = await withClient(pool, client => + persistSecurityMaster(client as unknown as SecurityMasterQueryable, composed.persistInput) + ); + + expect(first.instrumentsInserted).toBe(5); + expect(first.listingsInserted).toBe(7); + expect(first.continuitiesInserted).toBe(1); + expect(first.conflictsInserted).toBe(composed.pass4!.conflicts.length); + expect(first.conflictsInserted).toBeGreaterThanOrEqual(3); + + // 1. Two distinct listing_ids and instrument_ids for FB common vs FB ETF + const fbCommonKey = formatListingNaturalKey({ + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }); + const fbEtfKey = formatListingNaturalKey({ + primaryIsin: 'US4642872000', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }); + const fbCommonListingId = first.listingIdByKey.get(fbCommonKey); + const fbEtfListingId = first.listingIdByKey.get(fbEtfKey); + expect(fbCommonListingId).toBeDefined(); + expect(fbEtfListingId).toBeDefined(); + expect(fbCommonListingId).not.toBe(fbEtfListingId); + + const fbRows = await pool.query<{ + listing_id: number; + instrument_id: number; + primary_isin: string; + security_type: string; + }>( + `SELECT l.listing_id, l.instrument_id, i.primary_isin, i.security_type + FROM listing l + JOIN instrument i ON i.instrument_id = l.instrument_id + WHERE l.ticker_root = 'FB' + ORDER BY i.primary_isin` + ); + expect(fbRows.rows.length).toBe(2); + expect(fbRows.rows[0]?.primary_isin).toBe('US30303M1027'); + expect(fbRows.rows[0]?.security_type).toBe('common'); + expect(fbRows.rows[1]?.primary_isin).toBe('US4642872000'); + expect(fbRows.rows[1]?.security_type).toBe('etf'); + expect(fbRows.rows[0]?.listing_id).not.toBe(fbRows.rows[1]?.listing_id); + + // 2. SIVB -> SIVBQ continuity row and delist outcomes + const sivbKey = formatListingNaturalKey({ + primaryIsin: 'US78486Q1013', + mic: 'XNAS', + tickerRoot: 'SIVB', + classSuffix: '', + currency: 'USD', + }); + const sivbqKey = formatListingNaturalKey({ + primaryIsin: 'US78486Q1013', + mic: 'OTCM', + tickerRoot: 'SIVBQ', + classSuffix: '', + currency: 'USD', + }); + const sivbListingId = first.listingIdByKey.get(sivbKey); + const sivbqListingId = first.listingIdByKey.get(sivbqKey); + expect(sivbListingId).toBeDefined(); + expect(sivbqListingId).toBeDefined(); + + const continuityRows = await pool.query<{ + from_listing_id: number; + to_listing_id: number; + kind: string; + effective_date: string; + }>( + `SELECT from_listing_id, to_listing_id, kind, effective_date::text + FROM corporate_action_continuity` + ); + expect(continuityRows.rows.length).toBe(1); + expect(continuityRows.rows[0]).toEqual({ + from_listing_id: sivbListingId!, + to_listing_id: sivbqListingId!, + kind: CONTINUITY_KIND_OTC_DELIST_TRANSFER, + effective_date: '2023-03-28', + }); + + const sivbDelistRows = await pool.query<{ + ticker_root: string; + delist_reason: string | null; + terminal_return: string | null; + }>( + `SELECT ticker_root, delist_reason, terminal_return::text + FROM listing + WHERE listing_id IN ($1, $2) + ORDER BY ticker_root`, + [sivbListingId, sivbqListingId] + ); + expect(sivbDelistRows.rows).toEqual([ + { ticker_root: 'SIVB', delist_reason: 'moved_to_otc', terminal_return: null }, + { ticker_root: 'SIVBQ', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1.000000' }, + ]); + + // 3. Pass 4 price_ratio_mismatch rows persisted with both endpoints in JSONB detail + const conflictRows = await pool.query<{ + source: string; + source_id: string; + conflict_kind: string; + detail: { left: { source: string; sourceId: string }; right: { source: string; sourceId: string } }; + status: string; + }>( + `SELECT source, source_id, conflict_kind, detail, status + FROM resolution_conflict + ORDER BY source, source_id, detail::text` + ); + expect(conflictRows.rows.length).toBe(composed.pass4!.conflicts.length); + const sharedLeftRows = conflictRows.rows.filter( + r => r.source === 'ceo' && r.source_id === 'ceo:SHOP' && r.conflict_kind === 'price_ratio_mismatch' + ); + expect(sharedLeftRows.length).toBe(2); + expect(sharedLeftRows.map(r => r.detail.right.sourceId).sort()).toEqual([ + 'SHOP.TO', + 'SHOP:CA', + ]); + for (const row of conflictRows.rows) { + expect(row.status).toBe('open'); + expect(row.detail.left.sourceId).toBe(row.source_id); + expect(row.detail.right.sourceId.length).toBeGreaterThan(0); + } + + const countsAfterFirst = await getSevenTableCounts(pool); + + // 4. Second identical run changes zero IDs and inserts zero rows across all 7 tables + const second = await withClient(pool, client => + persistSecurityMaster(client as unknown as SecurityMasterQueryable, composed.persistInput) + ); + + expect(second.instrumentsInserted).toBe(0); + expect(second.instrumentsUpdated).toBe(0); + expect(second.identifierHistoryInserted).toBe(0); + expect(second.listingsInserted).toBe(0); + expect(second.listingsUpdated).toBe(0); + expect(second.listingSymbolHistoryInserted).toBe(0); + expect(second.listingSymbolHistoryUpdated).toBe(0); + expect(second.providerMappingsInserted).toBe(0); + expect(second.providerMappingsUpdated).toBe(0); + expect(second.conflictsInserted).toBe(0); + expect(second.conflictsUnchanged).toBe(composed.pass4!.conflicts.length); + expect(second.continuitiesInserted).toBe(0); + expect(second.continuitiesUpdated).toBe(0); + expect(second.continuitiesUnchanged).toBe(1); + + expect(Array.from(second.instrumentIdByIsin.entries())).toEqual( + Array.from(first.instrumentIdByIsin.entries()) + ); + expect(Array.from(second.listingIdByKey.entries())).toEqual( + Array.from(first.listingIdByKey.entries()) + ); + + const countsAfterSecond = await getSevenTableCounts(pool); + expect(countsAfterSecond).toEqual(countsAfterFirst); + }); +}); diff --git a/test/postgres/signal-study.test.ts b/test/postgres/signal-study.test.ts new file mode 100644 index 00000000..96fd6474 --- /dev/null +++ b/test/postgres/signal-study.test.ts @@ -0,0 +1,262 @@ +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 type { EventStudyInput, SignalCrossSection } from '@stock-bot/calculations'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { analyzeSignal, runEventStudy } from '@stock-bot/research'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('signal-study-postgres-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); +const VAULT_CUTOFF = '2025-05-01'; + +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 pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + 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 }; +} + +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 = 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 makeSignalPanel(dates: readonly string[], nNames: number, seed: number): SignalCrossSection[] { + const rand = createSeededRng(seed); + const ids = Array.from({ length: nNames }, (_, i) => i + 1); + return dates.map((date, t) => { + const signal = new Float64Array(nNames); + const forwardReturn = new Float64Array(nNames); + const slope = 0.002 + ((t % 5) - 2) * 0.0004; + for (let i = 0; i < nNames; i += 1) { + const s = rand() * 2 - 1; + signal[i] = s; + forwardReturn[i] = 0.0005 + slope * s + 0.015 * (rand() * 2 - 1); + } + return { date, ids, signal, forwardReturn }; + }); +} + +function makeEventStudyInput(dates: readonly string[], eventDayIndices: readonly number[], seed: number): EventStudyInput { + const rand = createSeededRng(seed); + const entityReturns = new Map(); + for (let entityId = 1; entityId <= 4; entityId += 1) { + const series = new Float64Array(dates.length); + for (let t = 0; t < dates.length; t += 1) { + series[t] = (rand() - 0.5) * 0.02; + } + entityReturns.set(entityId, series); + } + const benchmarkReturns = new Float64Array(dates.length); + for (let t = 0; t < dates.length; t += 1) { + benchmarkReturns[t] = (rand() - 0.5) * 0.01; + } + return { + sessionDates: dates, + entityReturns, + benchmarkReturns, + events: eventDayIndices.map((dayIndex, idx) => ({ + entityId: (idx % 4) + 1, + dayIndex, + })), + }; +} + +describe.skipIf(!url)('signal-study runners PostgreSQL integration', () => { + test('appends 3 trials (2 signal_ic + 1 event_study), fences Vault dates, computes clusterSize=2 DSR, and writes 0 rows on insufficient_data', async () => { + const f = await createIsolatedFixture(); + + const preDates = makeBusinessDates('2025-03-03', 35); + const postDates = ['2025-05-01', '2025-05-02', '2025-05-05']; + const allPanelDates = [...preDates, ...postDates]; + + const sig1 = await analyzeSignal(f.pool, { + principalId: 'operator', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'rank(ret_20d) - zscore(vol_20d)', + params: { lookback: 20 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + panel: makeSignalPanel(allPanelDates, 20, 1001), + vaultCutoffDate: VAULT_CUTOFF, + }); + + expect(sig1.status).toBe('ok'); + if (sig1.status !== 'ok') { + return; + } + expect(sig1.analysis.diagnostics.vaultExcludedDates).toBe(3); + expect(sig1.trial.sampleEnd < VAULT_CUTOFF).toBe(true); + expect(sig1.deflatedSharpe.clusterSize).toBe(1); + + const sig2 = await analyzeSignal(f.pool, { + principalId: 'operator', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'rank(ret_10d) + zscore(turnover_20d)', + params: { lookback: 10 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + panel: makeSignalPanel(allPanelDates, 20, 2002), + vaultCutoffDate: VAULT_CUTOFF, + }); + + expect(sig2.status).toBe('ok'); + if (sig2.status !== 'ok') { + return; + } + expect(sig2.analysis.diagnostics.vaultExcludedDates).toBe(3); + expect(sig2.trial.sampleEnd < VAULT_CUTOFF).toBe(true); + expect(sig2.trial.expressionHash).not.toBe(sig1.trial.expressionHash); + expect(sig2.deflatedSharpe.clusterSize).toBe(2); + expect(sig2.deflatedSharpe.pairsUsed).toBe(0); + expect(sig2.deflatedSharpe.pairsSkipped).toBe(1); + expect(sig2.deflatedSharpe.effectiveTrials).toBe(2); + expect(Number.isFinite(sig2.deflatedSharpe.effectiveTrials)).toBe(true); + + const eventDates = makeBusinessDates('2025-02-03', 70); + const cutoffIdx = eventDates.findIndex(d => d >= VAULT_CUTOFF); + expect(cutoffIdx).toBeGreaterThan(35); + + const evtRes = await runEventStudy(f.pool, { + principalId: 'operator', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'earnings_beat_car', + params: { minSurprisePct: 5 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + input: makeEventStudyInput( + eventDates, + [8, 12, 16, 20, 24, 28, cutoffIdx - 3, cutoffIdx + 1], + 3003 + ), + vaultCutoffDate: VAULT_CUTOFF, + options: { preDays: 3, postDays: 5, minEvents: 5 }, + }); + + expect(evtRes.status).toBe('ok'); + if (evtRes.status !== 'ok') { + return; + } + expect(evtRes.vaultExcludedEvents).toBe(2); + expect(evtRes.trial.sampleEnd < VAULT_CUTOFF).toBe(true); + expect(evtRes.deflatedSharpe.clusterSize).toBe(3); + expect(evtRes.deflatedSharpe.pairsUsed).toBe(0); + expect(evtRes.deflatedSharpe.pairsSkipped).toBe(3); + expect(evtRes.deflatedSharpe.effectiveTrials).toBe(3); + + // Insufficient-data run must append 0 additional rows. + const insufRes = await analyzeSignal(f.pool, { + principalId: 'operator', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'too_short_signal', + params: {}, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + panel: makeSignalPanel(['2025-04-30', '2025-05-01'], 10, 4004), + vaultCutoffDate: VAULT_CUTOFF, + }); + expect(insufRes.status).toBe('insufficient_data'); + + const dbResult = await f.pool.query<{ + trial_id: string; + stage: string; + n_obs: number; + expression_hash: string; + sample_end: string; + }>( + `SELECT trial_id, stage, n_obs, expression_hash, sample_end::text AS sample_end + FROM trial_ledger + ORDER BY trial_id ASC` + ); + + expect(dbResult.rows).toHaveLength(3); + expect(dbResult.rows.map(r => r.stage)).toEqual(['signal_ic', 'signal_ic', 'event_study']); + expect(dbResult.rows[0]!.n_obs).toBe(sig1.trial.nObs); + expect(dbResult.rows[1]!.n_obs).toBe(sig2.trial.nObs); + expect(dbResult.rows[2]!.n_obs).toBe(evtRes.trial.nObs); + + const hashes = new Set(dbResult.rows.map(r => r.expression_hash)); + expect(hashes.size).toBe(3); + + for (const row of dbResult.rows) { + expect(row.sample_end < VAULT_CUTOFF).toBe(true); + } + }); +}); diff --git a/test/postgres/trial-ledger-writer.test.ts b/test/postgres/trial-ledger-writer.test.ts new file mode 100644 index 00000000..fcc85cca --- /dev/null +++ b/test/postgres/trial-ledger-writer.test.ts @@ -0,0 +1,478 @@ +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 { deflatedSharpeRatio, effectiveIndependentTrials } from '@stock-bot/calculations'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + TrialLedgerError, + buildTrialRow, + canonicalExpressionHash, + clusterDeflatedSharpe, + loadClusterTrials, + recordTrials, + type TrialRowInput, +} from '@stock-bot/research'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('trial-ledger-writer-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); +const VAULT_CUTOFF = '2025-05-01'; + +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 pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + // 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`); +} + +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 createGaussianSampler(seed: number): () => number { + const next = createSeededRng(seed); + let spare: number | null = null; + return () => { + if (spare !== null) { + const value = spare; + spare = null; + return value; + } + let u = 0; + while (u <= 1e-12) { + u = next(); + } + const v = next(); + const mag = Math.sqrt(-2 * Math.log(u)); + const theta = 2 * Math.PI * v; + spare = mag * Math.sin(theta); + return mag * Math.cos(theta); + }; +} + +function makeBusinessDates(startDate: string, count: number): string[] { + const out = 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 makeSeries(seed: number, length: number, mean = 0.0005, std = 0.01): number[] { + const gauss = createGaussianSampler(seed); + const out = new Array(length); + for (let i = 0; i < length; i += 1) { + out[i] = mean + std * gauss(); + } + return out; +} + +describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', () => { + test('3-horizon recordTrials inserts 3 ascending rows, round-trips REAL series, rejects bad batch atomically, and preserves immutability triggers', async () => { + const f = await createIsolatedFixture(); + + const horizons = [ + { label: '1d', bucket: 'swing_1_10d' as const, seed: 1001 }, + { label: '5d', bucket: 'swing_1_10d' as const, seed: 1002 }, + { label: '20d', bucket: 'position_10d_plus' as const, seed: 1003 }, + ]; + + const rows = horizons.map(h => + buildTrialRow({ + principalId: 'operator', + stage: 'signal_ic', + universeMarket: 'US_EQ', + horizonBucket: h.bucket, + expressionHash: canonicalExpressionHash({ + expression: 'rank(ret_20d) - zscore(vol_20d)', + params: { lookback: 20 }, + universe: 'US_EQ', + sampleStart: '2020-01-02', + sampleEnd: '2024-12-31', + horizon: h.label, + }), + sampleStart: '2020-01-02', + sampleEnd: '2024-12-31', + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(h.seed, 25), + }) + ); + + const receipts = await recordTrials(f.pool, rows); + expect(receipts).toHaveLength(3); + expect(receipts[0]!.trialId).toBeLessThan(receipts[1]!.trialId); + expect(receipts[1]!.trialId).toBeLessThan(receipts[2]!.trialId); + + const swingRows = await loadClusterTrials(f.pool, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + const positionRows = await loadClusterTrials(f.pool, { + universeMarket: 'US_EQ', + horizonBucket: 'position_10d_plus', + }); + expect(swingRows).toHaveLength(2); + expect(positionRows).toHaveLength(1); + + // Verify daily_series round-trips within IEEE-754 REAL precision (float4 text parses to float64 with identical float32 bits). + for (let i = 0; i < rows[0]!.dailySeries.length; i += 1) { + expect(Math.fround(swingRows[0]!.dailySeries[i]!)).toBe(Math.fround(rows[0]!.dailySeries[i]!)); + } + + // Batch with one invalid row throws TrialLedgerError and inserts 0 additional rows. + const badBatch: TrialRowInput[] = [ + { + principalId: 'operator', + stage: 'event_study', + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + expressionHash: 'b'.repeat(64), + sampleStart: '2020-01-02', + sampleEnd: '2024-12-31', + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(2001, 10), + }, + { + principalId: 'operator', + stage: 'event_study', + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + expressionHash: 'c'.repeat(64), + sampleStart: '2020-01-02', + sampleEnd: VAULT_CUTOFF, // violates exclusive vault fence + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(2002, 10), + }, + ]; + + try { + await recordTrials(f.pool, badBatch); + throw new Error('Expected VAULT_FENCE_VIOLATION'); + } catch (error) { + expect(error).toBeInstanceOf(TrialLedgerError); + expect((error as TrialLedgerError).code).toBe('VAULT_FENCE_VIOLATION'); + } + + const caRows = await loadClusterTrials(f.pool, { + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + }); + expect(caRows).toHaveLength(0); + + // Existing append-only triggers still block UPDATE, DELETE, and TRUNCATE. + const expectedMsg = /Retained research evidence cannot be rewritten or deleted/; + await expectPgErrorCode( + f.pool.query('UPDATE trial_ledger SET n_obs = 999'), + '23514', + expectedMsg + ); + await expectPgErrorCode(f.pool.query('DELETE FROM trial_ledger'), '23514', expectedMsg); + await expectPgErrorCode(f.pool.query('TRUNCATE trial_ledger'), '23514', expectedMsg); + + const totalCount = (await f.pool.query('SELECT count(*)::int AS c FROM trial_ledger')).rows[0] + .c as number; + expect(totalCount).toBe(3); + }); + + test('computes N-hat and DSR end-to-end through PostgreSQL for near-duplicate vs independent clusters, cluster isolation, and asOf', async () => { + const f = await createIsolatedFixture(); + const nObs = 500; + const clusterK = 12; + const sessionDates = makeBusinessDates('2022-01-03', nObs); + const sampleStart = sessionDates[0]!; + const sampleEnd = sessionDates[nObs - 1]!; + + // 1. Near-duplicate cluster in (US_EQ, swing_1_10d): target pairwise rho ~ 0.97 + const factorGauss = createGaussianSampler(9001); + const baseFactor = new Array(nObs); + for (let t = 0; t < nObs; t += 1) { + baseFactor[t] = 0.0008 + 0.01 * factorGauss(); + } + const noiseGauss = createGaussianSampler(9002); + const nearDupRows = new Array(clusterK); + const loading = Math.sqrt(0.97); + const noiseWeight = Math.sqrt(1 - 0.97); + for (let k = 0; k < clusterK; k += 1) { + const series = new Array(nObs); + for (let t = 0; t < nObs; t += 1) { + series[t] = loading * (baseFactor[t] as number) + noiseWeight * 0.01 * noiseGauss(); + } + nearDupRows[k] = { + principalId: 'operator', + stage: 'screen', + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expressionHash: canonicalExpressionHash({ + expression: `dup_signal_${k}`, + params: { k }, + universe: 'US_EQ', + sampleStart, + sampleEnd, + horizon: '5d', + }), + sampleStart, + sampleEnd, + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: series, + }; + } + + const nearDupReceipts = await recordTrials(f.pool, nearDupRows); + + // 2. Independent cluster in (CA_EQ, swing_1_10d) — also tests cluster isolation from US_EQ! + const indepRows = new Array(clusterK); + for (let k = 0; k < clusterK; k += 1) { + indepRows[k] = { + principalId: 'operator', + stage: 'screen', + universeMarket: 'CA_EQ', + horizonBucket: 'swing_1_10d', + expressionHash: canonicalExpressionHash({ + expression: `indep_signal_${k}`, + params: { k }, + universe: 'CA_EQ', + sampleStart, + sampleEnd, + horizon: '5d', + }), + sampleStart, + sampleEnd, + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(5000 + k, nObs, 0.0005, 0.01), + }; + } + const indepReceipts = await recordTrials(f.pool, indepRows); + + // 3. Another cluster in (US_EQ, position_10d_plus) to verify horizon_bucket isolation. + await recordTrials(f.pool, [ + { + principalId: 'operator', + stage: 'engine_backtest', + universeMarket: 'US_EQ', + horizonBucket: 'position_10d_plus', + expressionHash: 'd'.repeat(64), + sampleStart, + sampleEnd, + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(7777, nObs), + }, + ]); + + const nearDupDsr = await clusterDeflatedSharpe(f.pool, { + trialId: nearDupReceipts[0]!.trialId, + sessionDates, + }); + expect(nearDupDsr.clusterSize).toBe(clusterK); + expect(nearDupDsr.meanCorrelation).not.toBeNull(); + expect(nearDupDsr.meanCorrelation!).toBeGreaterThan(0.95); + expect(nearDupDsr.effectiveTrials).toBeLessThan(clusterK * 0.25); + + const indepDsr = await clusterDeflatedSharpe(f.pool, { + trialId: indepReceipts[0]!.trialId, + sessionDates, + }); + expect(indepDsr.clusterSize).toBe(clusterK); + expect(indepDsr.effectiveTrials).toBeGreaterThan(clusterK * 0.85); + expect(indepDsr.effectiveTrials).toBeLessThanOrEqual(clusterK); + + // Direct deflatedSharpeRatio parity within 1e-9 on the persisted cluster rows. + const persistedNearDup = await loadClusterTrials(f.pool, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }); + const directEff = effectiveIndependentTrials(persistedNearDup.map(r => r.dailySeries)); + const directDsr = deflatedSharpeRatio({ + sharpeUnann: persistedNearDup[0]!.sharpeUnann, + nObs: persistedNearDup[0]!.nObs, + skewness: persistedNearDup[0]!.skewness, + kurtosis: persistedNearDup[0]!.kurtosis, + nHat: directEff.nHat, + clusterSharpes: persistedNearDup.map(r => r.sharpeUnann), + }); + expect(directDsr).not.toBeNull(); + expect(Math.abs((nearDupDsr.dsr ?? Number.NaN) - directDsr!.dsr)).toBeLessThan(1e-9); + + // Writer receipt timestamp round-trip: exact receipt timestamp with Z and +00:00 select the same rows. + const receiptTs = nearDupReceipts[clusterK - 1]!.createdAt; + const atReceiptZ = await loadClusterTrials(f.pool, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + asOf: receiptTs, + }); + const atReceiptOffset = await loadClusterTrials(f.pool, { + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + asOf: receiptTs.replace(/Z$/, '+00:00'), + }); + expect(atReceiptZ).toHaveLength(clusterK); + expect(atReceiptOffset.map(r => r.trialId)).toEqual(atReceiptZ.map(r => r.trialId)); + + // Deterministic asOf ordering fixture: explicit distinct microsecond created_at values (no wall-clock sleep). + const olderRow = buildTrialRow({ + principalId: 'operator', + stage: 'screen', + universeMarket: 'FX', + horizonBucket: 'intraday', + expressionHash: 'e'.repeat(64), + sampleStart, + sampleEnd, + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(9998, 10), + }); + const newerRow = buildTrialRow({ + principalId: 'operator', + stage: 'screen', + universeMarket: 'FX', + horizonBucket: 'intraday', + expressionHash: 'f'.repeat(64), + sampleStart, + sampleEnd, + vaultCutoffDate: VAULT_CUTOFF, + dailySeries: makeSeries(9999, 10), + }); + + await f.pool.query( + `INSERT INTO trial_ledger ( + created_at, principal_id, campaign_id, stage, universe_market, horizon_bucket, + hypothesis_id, expression_hash, sample_start, sample_end, n_obs, + sharpe_unann, skewness, kurtosis, daily_series + ) VALUES + ($1::timestamptz, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12::double precision, $13::double precision, $14::double precision, $15::real[]), + ($16::timestamptz, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27::double precision, $28::double precision, $29::double precision, $30::real[])`, + [ + '2025-04-01T10:00:00.123456Z', + olderRow.principalId, + olderRow.campaignId, + olderRow.stage, + olderRow.universeMarket, + olderRow.horizonBucket, + olderRow.hypothesisId, + olderRow.expressionHash, + olderRow.sampleStart, + olderRow.sampleEnd, + olderRow.nObs, + olderRow.sharpeUnann, + olderRow.skewness, + olderRow.kurtosis, + olderRow.dailySeries, + '2025-04-01T10:00:00.123457Z', + newerRow.principalId, + newerRow.campaignId, + newerRow.stage, + newerRow.universeMarket, + newerRow.horizonBucket, + newerRow.hypothesisId, + newerRow.expressionHash, + newerRow.sampleStart, + newerRow.sampleEnd, + newerRow.nObs, + newerRow.sharpeUnann, + newerRow.skewness, + newerRow.kurtosis, + newerRow.dailySeries, + ] + ); + + const fxAll = await loadClusterTrials(f.pool, { + universeMarket: 'FX', + horizonBucket: 'intraday', + }); + const fxAtZ = await loadClusterTrials(f.pool, { + universeMarket: 'FX', + horizonBucket: 'intraday', + asOf: '2025-04-01T10:00:00.123456Z', + }); + const fxAtPlusZero = await loadClusterTrials(f.pool, { + universeMarket: 'FX', + horizonBucket: 'intraday', + asOf: '2025-04-01T10:00:00.123456+00:00', + }); + const fxAtPlusTwo = await loadClusterTrials(f.pool, { + universeMarket: 'FX', + horizonBucket: 'intraday', + asOf: '2025-04-01T12:00:00.123456+02:00', + }); + expect(fxAll).toHaveLength(2); + expect(fxAtZ).toHaveLength(1); + expect(fxAtPlusZero).toHaveLength(1); + expect(fxAtPlusTwo).toHaveLength(1); + expect(fxAtPlusZero[0]!.trialId).toBe(fxAtZ[0]!.trialId); + expect(fxAtPlusTwo[0]!.trialId).toBe(fxAtZ[0]!.trialId); + }); +}); diff --git a/test/unit/security-master-match-report-edge.test.ts b/test/unit/security-master-match-report-edge.test.ts new file mode 100644 index 00000000..fc74ca8e --- /dev/null +++ b/test/unit/security-master-match-report-edge.test.ts @@ -0,0 +1,267 @@ +import { describe, expect, test } from 'bun:test'; +import { + buildMatchReport, + generateOverrideSeedSql, + generateOverrideTemplateSql, + renderConflictsCsv, + renderMatchReportMarkdown, + sourceCountryKey, + type MatchReport, + type OverrideSeedRow, + type StageAMatchResult, + type StageBMatchResult, + type UnifiedConflictRow, +} from '../../apps/stock/data-pipeline/src/security-master'; + +function makeEmptyStageA(): StageAMatchResult { + return { + instruments: [], + unresolved: [], + conflicts: [], + stats: { + totalInputRecords: 0, + totalInstruments: 0, + bySource: { + ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + eod: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + }, + }, + }; +} + +function makeEmptyStageB(): StageBMatchResult { + return { + listings: [], + providerMappings: [], + unresolved: [], + conflicts: [], + stats: { + totalListings: 0, + totalProviderMappings: 0, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }, + }; +} + +function reportWithConflicts(conflicts: UnifiedConflictRow[]): MatchReport { + return { + ...buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }), + conflicts, + }; +} + +const validRow: OverrideSeedRow = { + source: 'eod', + sourceId: 'BRK-B.US', + validFrom: '2020-01-15', + validTo: null, + primaryIsin: 'US0846707026', + mic: 'XNYS', + tickerRoot: 'BRK', + classSuffix: 'B', + currency: 'USD', + reason: 'class share mapping', + createdBy: 'director', +}; + +describe('buildMatchReport edge cases', () => { + test('empty exchange classification yields null mappedPct and fails exchangesMapped100', () => { + const report = buildMatchReport({ + exchanges: { mapped: [], unresolved: [] }, + stageA: makeEmptyStageA(), + stageB: makeEmptyStageB(), + }); + + expect(report.exchangeCoverage).toEqual({ mapped: 0, unresolved: 0, total: 0, mappedPct: null }); + expect(report.meetsExitThresholds.exchangesMapped100).toBe(false); + }); + + test('one failing eligible source fails equitiesResolved95 even when others pass', () => { + const stageB = makeEmptyStageB(); + stageB.stats.bySource.eod = { total: 100, matched: 100, unresolved: 0, conflict: 0 }; + stageB.stats.bySource.qm = { total: 100, matched: 94, unresolved: 6, conflict: 0 }; + + const report = buildMatchReport({ stageA: makeEmptyStageA(), stageB }); + + expect(report.meetsExitThresholds.equitiesResolved95).toBe(false); + expect(buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: 0.94 }).meetsExitThresholds.equitiesResolved95).toBe(true); + }); + + test('minResolvedPct boundaries 0 and 1 are accepted; 1 requires every eligible record matched', () => { + const stageB = makeEmptyStageB(); + stageB.stats.bySource.eod = { total: 10, matched: 10, unresolved: 0, conflict: 0 }; + stageB.stats.bySource.ib = { total: 10, matched: 0, unresolved: 10, conflict: 0 }; + + expect(buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: 0 }).meetsExitThresholds.equitiesResolved95).toBe(true); + expect(buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: 1 }).meetsExitThresholds.equitiesResolved95).toBe(false); + expect(() => buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: Number.POSITIVE_INFINITY })).toThrow(/minResolvedPct/); + }); + + test('non-excluded unresolved reasons stay in the eligible denominator', () => { + const stageB = makeEmptyStageB(); + stageB.stats.bySource.ceo = { total: 4, matched: 2, unresolved: 2, conflict: 0 }; + stageB.unresolved = [ + { source: 'ceo', sourceId: 'C1', reason: 'missing_mic', primaryIsin: null }, + { source: 'ceo', sourceId: 'C2', reason: 'forex_venue', primaryIsin: null }, + ]; + + const ceo = buildMatchReport({ stageA: makeEmptyStageA(), stageB }).resolutionBySource.find(r => r.source === 'ceo'); + + expect(ceo?.excludedByDesign).toBe(1); + expect(ceo?.eligibleTotal).toBe(3); + expect(ceo?.eligibleResolvedPct).toBeCloseTo(2 / 3, 12); + }); + + test('sourceCountries accepts a plain record, NUL-separated fallback keys, and normalizes case', () => { + const stageB = makeEmptyStageB(); + stageB.unresolved = [ + { source: 'eod', sourceId: 'X.TO', reason: 'missing_mic', primaryIsin: null }, + { source: 'qm', sourceId: 'Y:US', reason: 'excluded_fund', primaryIsin: null }, + { source: 'ib', sourceId: 'UNKNOWN', reason: 'missing_mic', primaryIsin: null }, + ]; + + const report = buildMatchReport({ + stageA: makeEmptyStageA(), + stageB, + sourceCountries: { + [sourceCountryKey('eod', 'X.TO')]: ' ca ', + 'qm\u0000Y:US': 'us', + }, + }); + + expect(report.resolutionByCountry).toEqual([ + { country: 'CA', total: 1, matched: 0, unresolved: 1, conflict: 0, excludedByDesign: 0, eligibleTotal: 1, resolvedPct: 0, eligibleResolvedPct: 0 }, + { country: 'US', total: 1, matched: 0, unresolved: 1, conflict: 0, excludedByDesign: 1, eligibleTotal: 0, resolvedPct: 0, eligibleResolvedPct: null }, + ]); + }); + + test('does not mutate input pass results and copies stats objects', () => { + const stageA = makeEmptyStageA(); + stageA.conflicts = [ + { source: 'eod', sourceId: 'Z', conflictKind: 'duplicate_source_id', detail: { isin: 'B', cusip: null, country: 'US', derivedIsin: null } }, + { source: 'eod', sourceId: 'A', conflictKind: 'duplicate_source_id', detail: { isin: 'A', cusip: null, country: 'US', derivedIsin: null } }, + ]; + const before = JSON.stringify(stageA); + + const report = buildMatchReport({ stageA, stageB: makeEmptyStageB() }); + + expect(JSON.stringify(stageA)).toBe(before); + expect(report.conflicts.map(c => c.sourceId)).toEqual(['A', 'Z']); + }); +}); + +describe('render edge cases', () => { + test('canonical detail JSON sorts nested keys, drops undefined, normalizes -0 identically in CSV and Markdown', () => { + const a = reportWithConflicts([ + { pass: 'stage_b', source: 'ib', sourceId: '1', conflictKind: 'k', detail: { z: { b: 1, a: [{ y: 2, x: -0 }] }, a: undefined } }, + ]); + const b = reportWithConflicts([ + { pass: 'stage_b', source: 'ib', sourceId: '1', conflictKind: 'k', detail: { z: { a: [{ x: 0, y: 2 }], b: 1 } } }, + ]); + + const csv = renderConflictsCsv(a); + + expect(csv).toBe(renderConflictsCsv(b)); + expect(csv).toContain('"{""z"":{""a"":[{""x"":0,""y"":2}],""b"":1}}"'); + expect(renderMatchReportMarkdown(a)).toBe(renderMatchReportMarkdown(b)); + }); + + test('CSV uses CRLF terminators and an empty report is header-only', () => { + expect(renderConflictsCsv(reportWithConflicts([]))).toBe('pass,source,source_id,conflict_kind,detail_json\r\n'); + }); + + test('Markdown sample exactly at maxConflictRows reports no remaining CSV rows', () => { + const rows: UnifiedConflictRow[] = [1, 2, 3].map(i => ({ pass: 'pass4', source: 'qm', sourceId: `S${i}`, conflictKind: 'k', detail: {} })); + + const md = renderMatchReportMarkdown(reportWithConflicts(rows), { maxConflictRows: 3 }); + + expect(md).toContain('Showing 3 of 3 conflicts.'); + expect(md).not.toContain('more in CSV'); + }); + + test('Markdown escapes lone CR in reason column of unresolved breakdown', () => { + const report = buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }); + report.unresolvedByReason.stageB = [{ source: 'a|b', reason: 'x\ry', count: 2 }]; + + const md = renderMatchReportMarkdown(report); + + expect(md).toContain('| a\\|b | x y | 2 |'); + }); +}); + +describe('override SQL edge cases', () => { + test('accepts leap day 2000-02-29 and validTo == validFrom; rejects 1900-02-29 and month 13', () => { + const sql = generateOverrideSeedSql([{ ...validRow, validFrom: '2000-02-29', validTo: '2000-02-29' }]); + + expect(sql).toContain("DATE '2000-02-29',\n DATE '2000-02-29',"); + expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '1900-02-29' }])).toThrow(/validFrom/); + expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2024-13-01' }])).toThrow(/validFrom/); + expect(() => generateOverrideSeedSql([{ ...validRow, validTo: '2024-01-01T00:00:00Z' }])).toThrow(/validTo/); + }); + + test('exact boundary lengths (16-char source, 64-char sourceId) are accepted', () => { + const sql = generateOverrideSeedSql([{ ...validRow, source: 's'.repeat(16), sourceId: 'i'.repeat(64) }]); + + expect(sql).toContain(`'${'s'.repeat(16)}'`); + expect(sql).toContain(`'${'i'.repeat(64)}'`); + }); + + test('undefined validFrom and explicit default are treated as the same key (exact dup dedup; conflicting dup throws)', () => { + const explicit = { ...validRow, validFrom: '1900-01-01', validTo: undefined }; + const implicit = { ...validRow, validFrom: undefined, validTo: null }; + + expect(generateOverrideSeedSql([explicit, implicit]).match(/INSERT INTO override/g)?.length).toBe(1); + expect(() => generateOverrideSeedSql([explicit, { ...implicit, mic: 'XNAS' }])).toThrow(/Conflicting duplicate/); + }); + + test('same source/sourceId with different validFrom yields two statements sorted by validFrom', () => { + const sql = generateOverrideSeedSql([{ ...validRow, validFrom: '2022-01-01' }, { ...validRow, validFrom: '2021-01-01' }]); + + const first = sql.indexOf("DATE '2021-01-01'"); + const second = sql.indexOf("DATE '2022-01-01'"); + expect(first).toBeGreaterThan(-1); + expect(second).toBeGreaterThan(first); + }); + + test('NUL in natural-key and date fields is rejected', () => { + expect(() => generateOverrideSeedSql([{ ...validRow, mic: 'XN\0S' }])).toThrow(/NUL/); + expect(() => generateOverrideSeedSql([{ ...validRow, classSuffix: '\0' }])).toThrow(/NUL/); + expect(() => generateOverrideSeedSql([{ ...validRow, createdBy: 'a\0' }])).toThrow(/NUL/); + expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2020-01-0\0' }])).toThrow(/NUL/); + }); + + test('template warns and emits NULL marker for overlong source, and escapes newline in conflictKind', () => { + const tpl = generateOverrideTemplateSql( + reportWithConflicts([{ pass: 'stage_b', source: 'x'.repeat(17), sourceId: 'ok', conflictKind: "evil\nDROP TABLE override; '", detail: {} }]) + ); + + for (const line of tpl.split('\n')) { + if (line.trim().length > 0) { + expect(line.startsWith('--')).toBe(true); + } + } + expect(tpl).toContain('-- WARNING: Cannot store raw source in PostgreSQL (length (17) exceeds 16-character limit)'); + expect(tpl).toContain('-- NULL /* TODO: replace with valid source */,'); + expect(tpl).toContain("-- 'ok',"); + expect(tpl).not.toContain('\nDROP'); + }); + + test('template has one candidate per source-attributed conflict including duplicates of the same sourceId', () => { + const tpl = generateOverrideTemplateSql( + reportWithConflicts([ + { pass: 'stage_a', source: 'eod', sourceId: 'DUP', conflictKind: 'duplicate_source_id', detail: { n: 1 } }, + { pass: 'stage_a', source: 'eod', sourceId: 'DUP', conflictKind: 'duplicate_source_id', detail: { n: 2 } }, + { pass: 'pass6', source: null, sourceId: null, conflictKind: 'invalid_listing_dates', detail: {} }, + ]) + ); + + expect(tpl.match(/-- INSERT INTO override/g)?.length).toBe(2); + }); +}); diff --git a/test/unit/security-master-match-report.test.ts b/test/unit/security-master-match-report.test.ts new file mode 100644 index 00000000..8fe87dc9 --- /dev/null +++ b/test/unit/security-master-match-report.test.ts @@ -0,0 +1,1085 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { + buildMatchReport, + classifySourceExchanges, + crossCheckPrices, + DEFAULT_MAX_CONFLICT_ROWS, + DEFAULT_MIN_RESOLVED_PCT, + DEFAULT_OTC_MICS, + DEFAULT_OVERRIDE_VALID_FROM, + EXCLUDED_BY_DESIGN_STAGE_B_REASONS, + generateOverrideSeedSql, + generateOverrideTemplateSql, + linkDelistingChains, + MATCH_REPORT_PASSES, + matchInstrumentsStageA, + matchListingsStageB, + renderConflictsCsv, + renderMatchReportMarkdown, + sourceCountryKey, + type MatchReport, + type OverrideSeedRow, + type StageAMatchResult, + type StageBMatchResult, + type StageBSource, + type StageBUnresolvedReason, + type UnifiedConflictRow, +} from '../../apps/stock/data-pipeline/src/security-master'; + +const matchReportSourcePath = fileURLToPath( + new URL('../../apps/stock/data-pipeline/src/security-master/match-report.ts', import.meta.url) +); + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function shuffleWithSeed(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rng = makeRng(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const tmp = copy[i]; + const swap = copy[j]; + if (tmp !== undefined && swap !== undefined) { + copy[i] = swap; + copy[j] = tmp; + } + } + return copy; +} + +/** + * Minimal strict RFC 4180 CSV parser supporting quoted fields, doubled quotes, and embedded CR/LF. + */ +function parseRfc4180Csv(input: string): string[][] { + const rows: string[][] = []; + let row: string[] = []; + let field = ''; + let inQuotes = false; + let i = 0; + + while (i < input.length) { + const ch = input[i]; + if (inQuotes) { + if (ch === '"') { + if (input[i + 1] === '"') { + field += '"'; + i += 2; + } else { + inQuotes = false; + i += 1; + } + } else { + field += ch; + i += 1; + } + continue; + } + + if (ch === '"' && field.length === 0) { + inQuotes = true; + i += 1; + } else if (ch === ',') { + row.push(field); + field = ''; + i += 1; + } else if (ch === '\r' && input[i + 1] === '\n') { + row.push(field); + rows.push(row); + row = []; + field = ''; + i += 2; + } else if (ch === '\n') { + row.push(field); + rows.push(row); + row = []; + field = ''; + i += 1; + } else { + field += ch; + i += 1; + } + } + + if (inQuotes) { + throw new Error('Unterminated quoted CSV field'); + } + if (field.length > 0 || row.length > 0) { + row.push(field); + rows.push(row); + } + return rows; +} + +function makeEmptyStageA(): StageAMatchResult { + return { + instruments: [], + unresolved: [], + conflicts: [], + stats: { + totalInputRecords: 0, + totalInstruments: 0, + bySource: { + ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + eod: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + }, + }, + }; +} + +function makeEmptyStageB(): StageBMatchResult { + return { + listings: [], + providerMappings: [], + unresolved: [], + conflicts: [], + stats: { + totalListings: 0, + totalProviderMappings: 0, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }, + }; +} + +function buildRealPipelineFixture() { + const exchanges = classifySourceExchanges([ + { source: 'eod', code: 'US', operatingMic: 'XNAS', country: 'US', currency: 'USD' }, + { source: 'eod', code: 'TO', operatingMic: 'XTSE', country: 'CA', currency: 'CAD' }, + { source: 'ceo', code: 'TSX', country: 'CA', currency: 'CAD' }, + { source: 'ib', code: 'UNKNOWN_EX', country: 'US', currency: 'USD' }, + ]); + + // Valid ISINs: + // Apple: US0378331005 (CUSIP 037833100) + // Royal Bank of Canada: CA7800871021 (CUSIP 780087102) + // Microsoft: US5949181045 (CUSIP 594918104) + const stageA = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'AAPL.US', + isin: 'US0378331005', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + { + source: 'ib', + sourceId: '265598', + isin: 'US0378331005', + country: 'US', + currency: 'USD', + name: 'APPLE INC', + }, + { + source: 'eod', + sourceId: 'RY.TO', + cusip: '780087102', + country: 'CA', + currency: 'CAD', + name: 'Royal Bank of Canada', + }, + { + source: 'eod', + sourceId: 'RY.US', + isin: 'CA7800871021', + country: 'US', + currency: 'USD', + name: 'Royal Bank of Canada', + }, + { + source: 'eod', + sourceId: 'BADFUND.US', + isin: 'US5949181045', + country: 'US', + currency: 'USD', + name: 'Excluded Mutual Fund', + }, + // Stage A conflict: ISIN vs CUSIP mismatch + { + source: 'eod', + sourceId: 'MISMATCH.US', + isin: 'US0378331005', + cusip: '594918104', + country: 'US', + currency: 'USD', + }, + // Stage A unresolved: missing both ISIN and CUSIP + { + source: 'ib', + sourceId: 'NOID_1', + country: 'US', + currency: 'USD', + }, + ]); + + const stageB = matchListingsStageB({ + instruments: stageA.instruments, + eodListings: [ + { + sourceId: 'AAPL.US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2010-01-04', lastBarDate: '2025-01-10' }, + }, + { + sourceId: 'RY.TO', + ticker: 'RY', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2010-01-04', lastBarDate: '2025-01-10' }, + }, + { + sourceId: 'RY.US', + ticker: 'RY', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2010-01-04', lastBarDate: '2024-06-01' }, + }, + { + sourceId: 'BADFUND.US', + ticker: 'BADF', + mic: null, + role: 'excluded_fund', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-01-02' }, + }, + ], + ibContracts: [ + { + sourceId: '265598', + conid: 265598, + currency: 'USD', + primaryExchange: 'NASDAQ', + }, + ], + tickerSources: [ + { + source: 'qm', + sourceId: 'AAPL:US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2015-01-02', lastBarDate: '2025-01-10' }, + }, + { + source: 'ceo', + sourceId: 'ceo:RY', + ticker: 'RY', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2018-01-02', lastBarDate: '2025-01-10' }, + }, + // Duplicate sourceId in tickerSources -> Stage B conflict + { + source: 'ceo', + sourceId: 'ceo:RY', + ticker: 'RY', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2018-01-02', lastBarDate: '2025-01-10' }, + }, + ], + }); + + const sampleDates = [ + '2024-01-02', + '2024-01-03', + '2024-01-04', + '2024-01-05', + '2024-01-08', + '2024-01-09', + ]; + const priceCrossCheck = crossCheckPrices({ + pairs: [ + { + left: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' }, + right: { source: 'qm', sourceId: 'AAPL:US', currency: 'USD' }, + }, + { + left: { source: 'eod', sourceId: 'RY.TO', currency: 'CAD' }, + right: { source: 'ceo', sourceId: 'ceo:RY', currency: 'CAD' }, + }, + ], + closes: [ + // Confirmed pair (ratio ~1.0, correlation 1.0) + ...sampleDates.flatMap((date, idx) => [ + { source: 'eod', sourceId: 'AAPL.US', date, close: 180 + idx * 2 }, + { source: 'qm', sourceId: 'AAPL:US', date, close: 180 + idx * 2 }, + ]), + // Ratio mismatch pair (2x price difference -> emits price_ratio_mismatch conflict) + ...sampleDates.flatMap((date, idx) => [ + { source: 'eod', sourceId: 'RY.TO', date, close: 100 + idx * 2 }, + { source: 'ceo', sourceId: 'ceo:RY', date, close: 200 + idx * 4 }, + ]), + ], + usdCadByDate: sampleDates.map(date => ({ date, usdCad: 1.35 })), + }); + + const delistingChains = linkDelistingChains( + { + listings: [ + ...stageB.listings, + // OTC continuation for RY.US (ended 2024-06-01 -> OTC starts 2024-06-04) + { + primaryIsin: 'CA7800871021', + mic: 'OTCM', + tickerRoot: 'RYOTC', + classSuffix: '', + currency: 'USD', + ibConid: null, + ibPrimaryExchange: null, + listedFrom: '2024-06-04', + listedTo: '2025-01-10', + }, + // Invalid dates listing -> triggers Pass 6 conflict (source: null, sourceId: null) + { + primaryIsin: 'US0378331005', + mic: 'XNYS', + tickerRoot: 'AAPLBAD', + classSuffix: '', + currency: 'USD', + ibConid: null, + ibPrimaryExchange: null, + listedFrom: '2025-05-01', + listedTo: '2024-01-01', + }, + ], + otcMics: DEFAULT_OTC_MICS, + }, + { asOfDate: '2025-01-10' } + ); + + const sourceCountries = new Map([ + [sourceCountryKey('eod', 'AAPL.US'), 'US'], + [sourceCountryKey('ib', '265598'), 'US'], + [sourceCountryKey('qm', 'AAPL:US'), 'US'], + [sourceCountryKey('eod', 'RY.TO'), 'CA'], + [sourceCountryKey('ceo', 'ceo:RY'), 'CA'], + [sourceCountryKey('eod', 'RY.US'), 'US'], + [sourceCountryKey('eod', 'BADFUND.US'), 'US'], + ]); + + return { exchanges, stageA, stageB, priceCrossCheck, delistingChains, sourceCountries }; +} + +describe('security-master match-report purity & exports', () => { + test('re-exports all public functions/constants and contains zero I/O or wall-clock calls', () => { + expect(typeof buildMatchReport).toBe('function'); + expect(typeof renderMatchReportMarkdown).toBe('function'); + expect(typeof renderConflictsCsv).toBe('function'); + expect(typeof generateOverrideSeedSql).toBe('function'); + expect(typeof generateOverrideTemplateSql).toBe('function'); + expect(DEFAULT_MIN_RESOLVED_PCT).toBe(0.95); + expect(DEFAULT_MAX_CONFLICT_ROWS).toBe(200); + expect(DEFAULT_OVERRIDE_VALID_FROM).toBe('1900-01-01'); + expect(EXCLUDED_BY_DESIGN_STAGE_B_REASONS).toEqual([ + 'excluded_fund', + 'composite_venue', + 'ats_routing_venue', + 'forex_venue', + ]); + expect(MATCH_REPORT_PASSES).toEqual(['stage_a', 'stage_b', 'pass4', 'pass6']); + + const sourceText = readFileSync(matchReportSourcePath, 'utf8'); + expect(sourceText).not.toMatch(/from\s+['"](?:node:)?(?:fs|net|http|https|dgram|tls|child_process)['"]/); + expect(sourceText).not.toMatch(/from\s+['"](?:pg|mongodb|@stock-bot\/postgres|@stock-bot\/mongodb)['"]/); + expect(sourceText).not.toContain('Date.now'); + expect(sourceText).not.toContain('new Date'); + }); +}); + +describe('buildMatchReport', () => { + test('reconciles real Stage A, Stage B, Pass 4, and Pass 6 outputs accurately', () => { + const fixture = buildRealPipelineFixture(); + const report = buildMatchReport(fixture); + + expect(report.exchangeCoverage).toEqual({ + mapped: fixture.exchanges.mapped.length, + unresolved: fixture.exchanges.unresolved.length, + total: fixture.exchanges.mapped.length + fixture.exchanges.unresolved.length, + mappedPct: + fixture.exchanges.mapped.length / + (fixture.exchanges.mapped.length + fixture.exchanges.unresolved.length), + }); + expect(report.meetsExitThresholds.exchangesMapped100).toBe(false); + + for (const row of report.resolutionBySource) { + const expected = fixture.stageB.stats.bySource[row.source]; + expect(row.total).toBe(expected.total); + expect(row.matched).toBe(expected.matched); + expect(row.unresolved).toBe(expected.unresolved); + expect(row.conflict).toBe(expected.conflict); + } + + const eodRow = report.resolutionBySource.find(r => r.source === 'eod'); + expect(eodRow?.excludedByDesign).toBe(1); + expect(eodRow?.eligibleTotal).toBe(3); + expect(eodRow?.eligibleResolvedPct).toBe(1); + + const expectedTotalConflicts = + fixture.stageA.conflicts.length + + fixture.stageB.conflicts.length + + fixture.priceCrossCheck.conflicts.length + + fixture.delistingChains.conflicts.length; + expect(expectedTotalConflicts).toBeGreaterThanOrEqual(4); + expect(report.conflicts.length).toBe(expectedTotalConflicts); + + const countSum = report.conflictsByPassKind.reduce((acc, row) => acc + row.count, 0); + expect(countSum).toBe(expectedTotalConflicts); + + expect(report.priceCrossCheck).toEqual({ + pairsIn: fixture.priceCrossCheck.stats.pairsIn, + invalidPairs: fixture.priceCrossCheck.stats.invalidPairs, + conflictsEmitted: fixture.priceCrossCheck.stats.conflictsEmitted, + byVerdict: fixture.priceCrossCheck.stats.byVerdict, + }); + + expect(report.delistingChains).toEqual({ + totalInputListings: fixture.delistingChains.stats.totalInputListings, + processedListings: fixture.delistingChains.stats.processedListings, + continuitiesCreated: fixture.delistingChains.stats.continuitiesCreated, + conflictsDetected: fixture.delistingChains.stats.conflictsDetected, + byOutcome: fixture.delistingChains.stats.byOutcome, + }); + expect(report.delistingChains?.continuitiesCreated).toBe(1); + + const pass6Conflict = report.conflicts.find(c => c.pass === 'pass6'); + expect(pass6Conflict).toBeDefined(); + expect(pass6Conflict?.source).toBeNull(); + expect(pass6Conflict?.sourceId).toBeNull(); + + // Country resolution populated for US and CA + expect(report.resolutionByCountry.map(c => c.country)).toEqual(['CA', 'US']); + const usCountry = report.resolutionByCountry.find(c => c.country === 'US'); + expect(usCountry?.excludedByDesign).toBe(1); + }); + + test('computes eligibleResolvedPct exclusions, null zero-denominators, and exact exit thresholds', () => { + const excludedReasons: StageBUnresolvedReason[] = [ + 'excluded_fund', + 'composite_venue', + 'ats_routing_venue', + 'forex_venue', + ]; + + const stageB = makeEmptyStageB(); + // eod: 19 matched, 1 real unresolved, 4 excluded-by-design => total=24, eligible=20, eligibleResolvedPct=19/20=0.95 + stageB.stats.bySource.eod = { total: 24, matched: 19, unresolved: 5, conflict: 0 }; + // ib: 2 excluded-by-design only => total=2, eligible=0 => eligibleResolvedPct = null (not NaN/Infinity) + stageB.stats.bySource.ib = { total: 2, matched: 0, unresolved: 2, conflict: 0 }; + // qm & ceo: total=0 => both pcts null + stageB.unresolved = [ + ...excludedReasons.map((reason, idx) => ({ + source: 'eod' as StageBSource, + sourceId: `EOD_EXCL_${idx}`, + reason, + primaryIsin: null, + })), + { + source: 'eod', + sourceId: 'EOD_MISSING_MIC', + reason: 'missing_mic', + primaryIsin: null, + }, + { + source: 'ib', + sourceId: 'IB_ATS_1', + reason: 'ats_routing_venue', + primaryIsin: null, + }, + { + source: 'ib', + sourceId: 'IB_FX_1', + reason: 'forex_venue', + primaryIsin: null, + }, + ]; + + const mappedExchanges = classifySourceExchanges([ + { source: 'ceo', code: 'TSX', country: 'CA', currency: 'CAD' }, + ]); + + const atThreshold = buildMatchReport( + { exchanges: mappedExchanges, stageA: makeEmptyStageA(), stageB }, + { minResolvedPct: 0.95 } + ); + + const eod = atThreshold.resolutionBySource.find(r => r.source === 'eod'); + expect(eod?.excludedByDesign).toBe(4); + expect(eod?.eligibleTotal).toBe(20); + expect(eod?.resolvedPct).toBeCloseTo(19 / 24, 12); + expect(eod?.eligibleResolvedPct).toBe(0.95); + + const ib = atThreshold.resolutionBySource.find(r => r.source === 'ib'); + expect(ib?.excludedByDesign).toBe(2); + expect(ib?.eligibleTotal).toBe(0); + expect(ib?.resolvedPct).toBe(0); + expect(ib?.eligibleResolvedPct).toBeNull(); + + const qm = atThreshold.resolutionBySource.find(r => r.source === 'qm'); + expect(qm?.resolvedPct).toBeNull(); + expect(qm?.eligibleResolvedPct).toBeNull(); + + expect(atThreshold.meetsExitThresholds).toEqual({ + exchangesMapped100: true, + equitiesResolved95: true, + }); + + // Flips to false right above 0.95 + const aboveThreshold = buildMatchReport( + { exchanges: mappedExchanges, stageA: makeEmptyStageA(), stageB }, + { minResolvedPct: 0.9501 } + ); + expect(aboveThreshold.meetsExitThresholds.equitiesResolved95).toBe(false); + + // 18/20 = 0.90 fails default 0.95 + const belowStageB = makeEmptyStageB(); + belowStageB.stats.bySource.eod = { total: 20, matched: 18, unresolved: 2, conflict: 0 }; + const belowReport = buildMatchReport({ + exchanges: mappedExchanges, + stageA: makeEmptyStageA(), + stageB: belowStageB, + }); + expect(belowReport.meetsExitThresholds.equitiesResolved95).toBe(false); + + // Unresolved exchange flips exchangesMapped100 to false + const unresolvedExchanges = classifySourceExchanges([ + { source: 'ceo', code: 'TSX', country: 'CA', currency: 'CAD' }, + { source: 'ib', code: 'BAD_EX', country: 'US', currency: 'USD' }, + ]); + const unresolvedExReport = buildMatchReport({ + exchanges: unresolvedExchanges, + stageA: makeEmptyStageA(), + stageB, + }); + expect(unresolvedExReport.meetsExitThresholds.exchangesMapped100).toBe(false); + + // All-zero input returns false for both thresholds and never NaN + const emptyReport = buildMatchReport({ + stageA: makeEmptyStageA(), + stageB: makeEmptyStageB(), + }); + expect(emptyReport.meetsExitThresholds).toEqual({ + exchangesMapped100: false, + equitiesResolved95: false, + }); + expect(emptyReport.exchangeCoverage).toBeNull(); + + // Invalid minResolvedPct throws + expect(() => + buildMatchReport( + { stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }, + { minResolvedPct: -0.01 } + ) + ).toThrow(); + expect(() => + buildMatchReport( + { stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }, + { minResolvedPct: 1.01 } + ) + ).toThrow(); + expect(() => + buildMatchReport( + { stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }, + { minResolvedPct: Number.NaN } + ) + ).toThrow(); + }); + + test('produces byte-identical Markdown, CSV, and SQL under shuffled inputs and omits timestamps', () => { + const fixture = buildRealPipelineFixture(); + // Add extra tie-breaking conflicts (same pass/kind/source/sourceId, different detail) + const stageAConflicts = [ + ...fixture.stageA.conflicts, + { + source: 'eod' as const, + sourceId: 'DUP.US', + conflictKind: 'duplicate_source_id' as const, + detail: { isin: 'US0378331005', cusip: null, country: 'US', derivedIsin: null }, + }, + { + source: 'eod' as const, + sourceId: 'DUP.US', + conflictKind: 'duplicate_source_id' as const, + detail: { isin: 'US5949181045', cusip: null, country: 'US', derivedIsin: null }, + }, + ]; + const pass6Conflicts = [ + ...fixture.delistingChains.conflicts, + { + conflictKind: 'invalid_listing_dates' as const, + detail: { + primaryIsin: 'CA7800871021', + currency: 'CAD', + fromListingKeys: [], + toListingKeys: [], + candidateListingKeys: [], + listedFrom: '2024-09-01', + listedTo: '2024-01-01', + reason: 'listed_to_before_listed_from', + }, + }, + ]; + + const baselineReport = buildMatchReport({ + exchanges: fixture.exchanges, + stageA: { ...fixture.stageA, conflicts: stageAConflicts }, + stageB: fixture.stageB, + priceCrossCheck: fixture.priceCrossCheck, + delistingChains: { ...fixture.delistingChains, conflicts: pass6Conflicts }, + sourceCountries: fixture.sourceCountries, + }); + + const shuffledReport = buildMatchReport({ + exchanges: { + mapped: shuffleWithSeed(fixture.exchanges.mapped, 11), + unresolved: shuffleWithSeed(fixture.exchanges.unresolved, 12), + }, + stageA: { + ...fixture.stageA, + unresolved: shuffleWithSeed(fixture.stageA.unresolved, 13), + conflicts: shuffleWithSeed(stageAConflicts, 14), + }, + stageB: { + ...fixture.stageB, + unresolved: shuffleWithSeed(fixture.stageB.unresolved, 15), + conflicts: shuffleWithSeed(fixture.stageB.conflicts, 16), + }, + priceCrossCheck: { + ...fixture.priceCrossCheck, + conflicts: shuffleWithSeed(fixture.priceCrossCheck.conflicts, 17), + }, + delistingChains: { + ...fixture.delistingChains, + conflicts: shuffleWithSeed(pass6Conflicts, 18), + }, + sourceCountries: fixture.sourceCountries, + }); + + const mdA = renderMatchReportMarkdown(baselineReport); + const mdB = renderMatchReportMarkdown(shuffledReport); + expect(mdA).toBe(mdB); + + const csvA = renderConflictsCsv(baselineReport); + const csvB = renderConflictsCsv(shuffledReport); + expect(csvA).toBe(csvB); + + const tplA = generateOverrideTemplateSql(baselineReport); + const tplB = generateOverrideTemplateSql(shuffledReport); + expect(tplA).toBe(tplB); + + const overrideRows: OverrideSeedRow[] = [ + { + source: 'qm', + sourceId: 'RY:CA', + validFrom: '2020-01-01', + validTo: null, + primaryIsin: 'CA7800871021', + mic: 'XTSE', + tickerRoot: 'RY', + classSuffix: '', + currency: 'CAD', + reason: 'Manual override B', + createdBy: 'director', + }, + { + source: 'eod', + sourceId: 'AAPL.US', + validFrom: '1900-01-01', + validTo: '2025-12-31', + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + reason: 'Manual override A', + createdBy: 'director', + }, + ]; + const sqlA = generateOverrideSeedSql(overrideRows); + const sqlB = generateOverrideSeedSql(shuffleWithSeed(overrideRows, 99)); + expect(sqlA).toBe(sqlB); + + // No ISO timestamps anywhere in Markdown or SQL + const isoTimestampPattern = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/; + expect(mdA).not.toMatch(isoTimestampPattern); + expect(sqlA).not.toMatch(isoTimestampPattern); + expect(tplA).not.toMatch(isoTimestampPattern); + }); +}); + +describe('renderConflictsCsv', () => { + test('emits RFC 4180 CSV with uncapped rows, proper quoting, empty Pass 6 source fields, and lossless JSON round-trip', () => { + const conflicts: UnifiedConflictRow[] = []; + // 205 synthetic conflicts (> DEFAULT_MAX_CONFLICT_ROWS=200) to prove CSV has no cap + for (let i = 0; i < 205; i++) { + conflicts.push({ + pass: 'stage_b', + source: 'qm', + sourceId: `SYM_${String(i).padStart(3, '0')}`, + conflictKind: 'ambiguous_ticker_span', + detail: { zKey: i, aKey: `row-${i}` }, + }); + } + // Special characters requiring RFC 4180 quoting: comma, double quotes, CR/LF + conflicts.push({ + pass: 'stage_a', + source: 'eod', + sourceId: 'ODD,"ID"\nLINE2', + conflictKind: 'isin_cusip_mismatch', + detail: { + zeta: 'a,b,"c"\r\nd', + alpha: 42, + }, + }); + // Pass 6 conflict with null source / sourceId + conflicts.push({ + pass: 'pass6', + source: null, + sourceId: null, + conflictKind: 'ambiguous_otc_continuation', + detail: { primaryIsin: 'US0378331005', reason: 'multiple_otc_candidates' }, + }); + + const report: MatchReport = { + ...buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }), + conflicts, + }; + + const csv = renderConflictsCsv(report); + const parsed = parseRfc4180Csv(csv); + + expect(parsed[0]).toEqual(['pass', 'source', 'source_id', 'conflict_kind', 'detail_json']); + expect(parsed.length).toBe(1 + conflicts.length); + + const oddRow = parsed.find(r => r[0] === 'stage_a'); + expect(oddRow).toBeDefined(); + expect(oddRow?.[1]).toBe('eod'); + expect(oddRow?.[2]).toBe('ODD,"ID"\nLINE2'); + expect(oddRow?.[3]).toBe('isin_cusip_mismatch'); + // Stable key order: alpha before zeta + expect(oddRow?.[4]).toBe('{"alpha":42,"zeta":"a,b,\\"c\\"\\r\\nd"}'); + expect(JSON.parse(oddRow?.[4] ?? '{}')).toEqual({ + alpha: 42, + zeta: 'a,b,"c"\r\nd', + }); + + const pass6Row = parsed.find(r => r[0] === 'pass6'); + expect(pass6Row).toEqual([ + 'pass6', + '', + '', + 'ambiguous_otc_continuation', + '{"primaryIsin":"US0378331005","reason":"multiple_otc_candidates"}', + ]); + }); +}); + +describe('renderMatchReportMarkdown', () => { + test('escapes pipes and newlines, caps conflict sample with remaining count, and renders valid empty tables', () => { + const conflicts: UnifiedConflictRow[] = [ + { + pass: 'stage_a', + source: 'eod', + sourceId: 'A|B\nC\\D', + conflictKind: 'isin_cusip_mismatch', + detail: { note: 'line1\r\nline2|pipe' }, + }, + { + pass: 'stage_b', + source: 'ib', + sourceId: 'IB_1', + conflictKind: 'ambiguous_ib_listing', + detail: { primaryIsin: 'US0378331005' }, + }, + { + pass: 'pass4', + source: 'ceo', + sourceId: 'ceo:RY', + conflictKind: 'price_ratio_mismatch', + detail: { medianRatio: 2 }, + }, + { + pass: 'pass6', + source: null, + sourceId: null, + conflictKind: 'invalid_listing_dates', + detail: { reason: 'listed_to_before_listed_from' }, + }, + ]; + + const report: MatchReport = { + ...buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }), + conflicts, + }; + + const mdAll = renderMatchReportMarkdown(report, { maxConflictRows: 10 }); + expect(mdAll).toContain('A\\|B C\\\\D'); + expect(mdAll).toContain('{"note":"line1\\\\r\\\\nline2\\|pipe"}'); + expect(mdAll).toContain('Showing 4 of 4 conflicts.'); + + const md = renderMatchReportMarkdown(report, { maxConflictRows: 2 }); + expect(md).toContain('Showing 2 of 4 conflicts (2 more in CSV).'); + + // Verify table rows in Conflict Sample have no broken newlines + const sampleSection = md.split('## Conflict Sample')[1] ?? ''; + const tableLines = sampleSection + .split('\n') + .filter(line => line.startsWith('|')); + // header + separator + 2 data rows = 4 lines + expect(tableLines.length).toBe(4); + + // maxConflictRows: 0 still shows remaining count + const mdZeroCap = renderMatchReportMarkdown(report, { maxConflictRows: 0 }); + expect(mdZeroCap).toContain('Showing 0 of 4 conflicts (4 more in CSV).'); + + // Empty report renders valid tables with zero counts + const emptyReport = buildMatchReport({ + stageA: makeEmptyStageA(), + stageB: makeEmptyStageB(), + }); + const emptyMd = renderMatchReportMarkdown(emptyReport); + expect(emptyMd).toContain('| 0 | 0 | 0 | N/A |'); + expect(emptyMd).toContain('| eod | 0 | 0 | 0 | 0 | 0 | 0 | N/A | N/A |'); + expect(emptyMd).toContain('| confirmed | 0 |'); + expect(emptyMd).toContain('| active | 0 |'); + expect(emptyMd).toContain('No open conflicts (0 total).'); + + // Invalid maxConflictRows throws + expect(() => renderMatchReportMarkdown(emptyReport, { maxConflictRows: -1 })).toThrow(); + expect(() => renderMatchReportMarkdown(emptyReport, { maxConflictRows: 1.5 })).toThrow(); + }); +}); + +describe('generateOverrideSeedSql & generateOverrideTemplateSql', () => { + const validRow: OverrideSeedRow = { + source: 'eod', + sourceId: 'AAPL.US', + validFrom: '2020-01-15', + validTo: '2025-12-31', + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + reason: "O'Brien fix", + createdBy: 'director', + }; + + test('emits portable natural-key INSERT ... SELECT ... ON CONFLICT DO NOTHING, escapes quotes, deduplicates exact duplicates, and handles empty input', () => { + const emptySql = generateOverrideSeedSql([]); + expect(emptySql.trim().length).toBeGreaterThan(0); + expect(emptySql).not.toContain('INSERT INTO'); + for (const line of emptySql.split('\n')) { + if (line.trim().length > 0) { + expect(line.startsWith('--')).toBe(true); + } + } + + const sql = generateOverrideSeedSql([validRow, { ...validRow }]); + const insertMatches = sql.match(/INSERT INTO override/g) ?? []; + expect(insertMatches.length).toBe(1); + expect(sql).toContain("'O''Brien fix'"); + expect(sql).toContain("DATE '2020-01-15'"); + expect(sql).toContain("DATE '2025-12-31'"); + expect(sql).toContain('FROM listing l'); + expect(sql).toContain('JOIN instrument i ON i.instrument_id = l.instrument_id'); + expect(sql).toContain("WHERE i.primary_isin = 'US0378331005'"); + expect(sql).toContain("AND l.mic = 'XNAS'"); + expect(sql).toContain("AND l.ticker_root = 'AAPL'"); + expect(sql).toContain("AND l.class_suffix = ''"); + expect(sql).toContain("AND l.currency = 'USD'"); + expect(sql).toContain('WHERE matched.listing_id IS NOT NULL'); + expect(sql).not.toContain('ORDER BY l.listing_id'); + expect(sql).not.toContain('LIMIT 1'); + expect(sql).toContain('ON CONFLICT (source, source_id, valid_from) DO NOTHING;'); + + // Default validFrom and null validTo + const defaultDatesSql = generateOverrideSeedSql([ + { ...validRow, validFrom: undefined, validTo: undefined }, + ]); + expect(defaultDatesSql).toContain("DATE '1900-01-01'"); + expect(defaultDatesSql).toContain('\n NULL,\n'); + }); + + test('throws clear validation errors on invalid fields, dates, NUL bytes, and conflicting duplicates', () => { + expect(() => generateOverrideSeedSql([{ ...validRow, sourceId: '' }])).toThrow(/sourceId/); + expect(() => generateOverrideSeedSql([{ ...validRow, sourceId: ' ' }])).toThrow(/sourceId/); + expect(() => generateOverrideSeedSql([{ ...validRow, sourceId: 'x'.repeat(65) }])).toThrow( + /sourceId/ + ); + expect(() => generateOverrideSeedSql([{ ...validRow, source: '' }])).toThrow(/source/); + expect(() => generateOverrideSeedSql([{ ...validRow, source: 's'.repeat(17) }])).toThrow( + /source/ + ); + expect(() => generateOverrideSeedSql([{ ...validRow, reason: '' }])).toThrow(/reason/); + expect(() => generateOverrideSeedSql([{ ...validRow, createdBy: ' ' }])).toThrow(/createdBy/); + expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2024-02-30' }])).toThrow( + /validFrom/ + ); + expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2023-02-29' }])).toThrow( + /validFrom/ + ); + expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2024-1-01' }])).toThrow( + /validFrom/ + ); + expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '0000-01-01' }])).toThrow( + /validFrom/ + ); + expect(() => generateOverrideSeedSql([{ ...validRow, validTo: '2024-02-30' }])).toThrow( + /validTo/ + ); + expect(() => + generateOverrideSeedSql([{ ...validRow, validFrom: '2024-06-01', validTo: '2024-05-31' }]) + ).toThrow(/validTo/); + expect(() => generateOverrideSeedSql([{ ...validRow, reason: 'bad\0nul' }])).toThrow(/NUL/); + expect(() => generateOverrideSeedSql([{ ...validRow, sourceId: 'A\0B' }])).toThrow(/NUL/); + expect(() => generateOverrideSeedSql([{ ...validRow, primaryIsin: 'X'.repeat(13) }])).toThrow( + /primaryIsin/ + ); + expect(() => generateOverrideSeedSql([{ ...validRow, mic: 'X'.repeat(11) }])).toThrow(/mic/); + expect(() => generateOverrideSeedSql([{ ...validRow, tickerRoot: 'X'.repeat(25) }])).toThrow( + /tickerRoot/ + ); + expect(() => generateOverrideSeedSql([{ ...validRow, classSuffix: 'X'.repeat(13) }])).toThrow( + /classSuffix/ + ); + expect(() => generateOverrideSeedSql([{ ...validRow, currency: 'USDD' }])).toThrow(/currency/); + + // Conflicting duplicate on (source, sourceId, validFrom) + expect(() => + generateOverrideSeedSql([validRow, { ...validRow, reason: 'Different reason' }]) + ).toThrow(/Conflicting duplicate/); + }); + + test('generateOverrideTemplateSql comments out every non-blank line, preserves CR/LF via E-string literals, warns on unstorable IDs, and omits Pass 6 conflicts', () => { + const conflicts: UnifiedConflictRow[] = [ + { + pass: 'stage_a', + source: 'eod', + sourceId: "BAD\r\nDROP'\\TABLE override;--", + conflictKind: 'isin_cusip_mismatch', + detail: {}, + }, + { + pass: 'stage_a', + source: 'eod', + sourceId: 'UNSTORABLE\0ID', + conflictKind: 'isin_cusip_mismatch', + detail: {}, + }, + { + pass: 'stage_b', + source: 'ib', + sourceId: '12345', + conflictKind: 'ambiguous_ib_listing', + detail: {}, + }, + { + pass: 'pass4', + source: 'ceo', + sourceId: 'ceo:RY', + conflictKind: 'price_ratio_mismatch', + detail: {}, + }, + // Pass 6 conflict without source/sourceId must NOT emit a template statement + { + pass: 'pass6', + source: null, + sourceId: null, + conflictKind: 'ambiguous_otc_continuation', + detail: {}, + }, + ]; + + const report: MatchReport = { + ...buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }), + conflicts, + }; + + const templateSql = generateOverrideTemplateSql(report); + for (const line of templateSql.split('\n')) { + if (line.trim().length > 0) { + expect(line.startsWith('--')).toBe(true); + } + } + + const commentedInserts = templateSql.match(/-- INSERT INTO override/g) ?? []; + expect(commentedInserts.length).toBe(4); + expect(templateSql).not.toContain('ambiguous_otc_continuation'); + expect(templateSql).not.toContain('ORDER BY l.listing_id'); + expect(templateSql).not.toContain('LIMIT 1'); + expect(templateSql).toContain('-- WHERE matched.listing_id IS NOT NULL'); + + // CR/LF source_id is preserved via a single-line PostgreSQL E'...' literal + expect(templateSql).toContain("-- E'BAD\\r\\nDROP''\\\\TABLE override;--',"); + // Unstorable NUL-byte source_id gets a diagnostic warning and non-insertable NULL marker instead of silent mangling + expect(templateSql).toContain( + '-- WARNING: Cannot store raw source_id in PostgreSQL (contains NUL byte); correct source_id before applying.' + ); + expect(templateSql).toContain('-- NULL /* TODO: replace with valid source_id */,'); + expect(templateSql).not.toContain('TODO_CORRECT_SOURCE_ID'); + + // Empty conflicts report still produces only comments + const emptyTemplate = generateOverrideTemplateSql( + buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }) + ); + for (const line of emptyTemplate.split('\n')) { + if (line.trim().length > 0) { + expect(line.startsWith('--')).toBe(true); + } + } + expect(emptyTemplate).toContain('No source-attributed open conflicts'); + }); + + test('renderMatchReportMarkdown emits Status: skipped when priceCrossCheck is null and omits it when supplied', () => { + const reportWithoutPass4 = buildMatchReport({ + stageA: makeEmptyStageA(), + stageB: makeEmptyStageB(), + }); + expect(reportWithoutPass4.priceCrossCheck).toBeNull(); + const mdSkipped = renderMatchReportMarkdown(reportWithoutPass4); + expect(mdSkipped).toContain( + '## Pass 4 Price Cross-Check Verdicts\n\n- Status: skipped (no sample closes supplied)\n- Pairs In: 0' + ); + + const pass4 = crossCheckPrices({ + pairs: [], + closes: [], + usdCadByDate: [], + }); + const reportWithPass4 = buildMatchReport({ + stageA: makeEmptyStageA(), + stageB: makeEmptyStageB(), + priceCrossCheck: pass4, + }); + expect(reportWithPass4.priceCrossCheck).not.toBeNull(); + const mdExecuted = renderMatchReportMarkdown(reportWithPass4); + expect(mdExecuted).not.toContain('Status: skipped'); + expect(mdExecuted).toContain('## Pass 4 Price Cross-Check Verdicts\n\n- Pairs In: 0'); + }); +}); diff --git a/test/unit/security-master-persist.test.ts b/test/unit/security-master-persist.test.ts new file mode 100644 index 00000000..5dfd8147 --- /dev/null +++ b/test/unit/security-master-persist.test.ts @@ -0,0 +1,1390 @@ +import { describe, expect, test } from 'bun:test'; +import { + canonicalizeJsonValue, + DEFAULT_VALID_FROM, + formatListingNaturalKey, + MAX_PERSIST_CHUNK_SIZE, + persistSecurityMaster, + PROVIDER_MAPPING_CONFIDENCE, + SECURITY_MASTER_PERSIST_LOCK_NAMESPACE, + stableJsonStringify, + type DelistingChainResult, + type PersistSecurityMasterInput, + type PriceCrossCheckConflictRecord, + type PriceCrossCheckResult, + type SecurityMasterQueryable, + type SecurityMasterQueryResult, + type SecurityType, + type StageAMatchResult, + type StageBMatchResult, +} from '../../apps/stock/data-pipeline/src/security-master'; + +interface RecordedQuery { + text: string; + values: readonly unknown[] | undefined; +} + +function emptyStageA(): StageAMatchResult { + return { + instruments: [], + unresolved: [], + conflicts: [], + stats: { + totalInputRecords: 0, + totalInstruments: 0, + bySource: { + ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + eod: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, + }, + }, + }; +} + +function emptyStageB(): StageBMatchResult { + return { + listings: [], + providerMappings: [], + unresolved: [], + conflicts: [], + stats: { + totalListings: 0, + totalProviderMappings: 0, + listingsWithIbConid: 0, + excludedFunds: 0, + bySource: { + eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, + }, + }, + }; +} + +function createMockClient( + handler?: ( + text: string, + values: readonly unknown[] | undefined, + index: number + ) => SecurityMasterQueryResult | Promise +): { client: SecurityMasterQueryable; queries: RecordedQuery[] } { + const queries: RecordedQuery[] = []; + let nextInstrumentId = 100; + let nextListingId = 1000; + + const client: SecurityMasterQueryable = { + release: () => undefined, + async query>( + text: string, + values?: readonly unknown[] + ): Promise> { + const index = queries.length; + queries.push({ text, values }); + if (handler) { + return (await handler(text, values, index)) as SecurityMasterQueryResult; + } + + if (text.startsWith('SELECT mic FROM exchange')) { + return { + rows: [{ mic: 'XNAS' }, { mic: 'XNYS' }, { mic: 'XTSE' }, { mic: 'OTCM' }], + } as unknown as SecurityMasterQueryResult; + } + if (text.startsWith('INSERT INTO instrument (')) { + const isins = (values?.[0] as string[]) ?? []; + return { + rows: isins.map(isin => ({ + instrument_id: nextInstrumentId++, + primary_isin: isin, + })), + } as unknown as SecurityMasterQueryResult; + } + if (text.startsWith('INSERT INTO instrument_identifier_history')) { + const ids = (values?.[0] as number[]) ?? []; + return { + rows: ids.map(() => ({ inserted: 1 })), + } as unknown as SecurityMasterQueryResult; + } + if (text.startsWith('INSERT INTO listing (')) { + const instrumentIds = (values?.[0] as number[]) ?? []; + const mics = (values?.[1] as string[]) ?? []; + const roots = (values?.[2] as string[]) ?? []; + const suffixes = (values?.[3] as string[]) ?? []; + const currencies = (values?.[4] as string[]) ?? []; + return { + rows: instrumentIds.map((instrumentId, i) => ({ + listing_id: nextListingId++, + instrument_id: instrumentId, + mic: mics[i], + ticker_root: roots[i], + class_suffix: suffixes[i], + currency: currencies[i], + })), + } as unknown as SecurityMasterQueryResult; + } + if (text.includes('INTO listing_symbol_history')) { + const firstCol = (values?.[0] as unknown[]) ?? []; + return { + rows: [{ inserted_count: firstCol.length, updated_count: 0 }], + } as unknown as SecurityMasterQueryResult; + } + if (text.startsWith('INSERT INTO provider_mapping')) { + const sources = (values?.[0] as string[]) ?? []; + const sourceIds = (values?.[1] as string[]) ?? []; + const validFroms = (values?.[2] as string[]) ?? []; + return { + rows: sources.map((source, i) => ({ + source, + source_id: sourceIds[i], + valid_from: validFroms[i], + inserted: true, + })), + } as unknown as SecurityMasterQueryResult; + } + if (text.startsWith('INSERT INTO corporate_action_continuity')) { + const firstCol = (values?.[0] as unknown[]) ?? []; + return { + rows: firstCol.map(() => ({ inserted: true })), + } as unknown as SecurityMasterQueryResult; + } + if (text.includes('WITH enforced AS')) { + return { + rows: [], + } as unknown as SecurityMasterQueryResult; + } + return { rows: [] } as SecurityMasterQueryResult; + }, + }; + + return { client, queries }; +} + +describe('persistSecurityMaster unit tests', () => { + test('rejects a pg.Pool-shaped object and non-queryable inputs', async () => { + const fakePool = { + totalCount: 1, + idleCount: 1, + waitingCount: 0, + query: async () => ({ rows: [] }), + } as unknown as SecurityMasterQueryable; + + const emptyInput: PersistSecurityMasterInput = { + stageA: emptyStageA(), + stageB: emptyStageB(), + securityTypeByIsin: new Map(), + }; + + await expect(persistSecurityMaster(fakePool, emptyInput)).rejects.toThrow(/PoolClient/); + await expect( + persistSecurityMaster(null as unknown as SecurityMasterQueryable, emptyInput) + ).rejects.toThrow(/query\(\)/); + }); + + test('validates chunkSize bounds', async () => { + const { client } = createMockClient(); + const emptyInput: PersistSecurityMasterInput = { + stageA: emptyStageA(), + stageB: emptyStageB(), + securityTypeByIsin: new Map(), + }; + + await expect(persistSecurityMaster(client, emptyInput, { chunkSize: 0 })).rejects.toThrow( + RangeError + ); + await expect(persistSecurityMaster(client, emptyInput, { chunkSize: -5 })).rejects.toThrow( + RangeError + ); + await expect(persistSecurityMaster(client, emptyInput, { chunkSize: 1.5 })).rejects.toThrow( + RangeError + ); + await expect( + persistSecurityMaster(client, emptyInput, { chunkSize: MAX_PERSIST_CHUNK_SIZE + 1 }) + ).rejects.toThrow(RangeError); + }); + + test('empty input fast path runs only BEGIN, advisory lock, override CTE, and COMMIT', async () => { + const { client, queries } = createMockClient(); + const result = await persistSecurityMaster(client, { + stageA: emptyStageA(), + stageB: emptyStageB(), + securityTypeByIsin: new Map(), + }); + + expect(queries.map(q => q.text.trim().split('\n')[0])).toEqual([ + 'BEGIN', + 'SELECT pg_advisory_xact_lock($1::int4, hashtext(current_schema()))', + 'WITH enforced AS (', + 'COMMIT', + ]); + expect(queries[1]?.values).toEqual([SECURITY_MASTER_PERSIST_LOCK_NAMESPACE]); + expect(result.instrumentsInserted).toBe(0); + expect(result.listingsInserted).toBe(0); + expect(result.providerMappingsInserted).toBe(0); + expect(result.providerMappingsDeletedStaleFallback).toBe(0); + expect(result.overridesApplied).toBe(0); + }); + + test('parameterizes all SQL values and never interpolates untrusted strings into SQL text', async () => { + const { client, queries } = createMockClient(); + const hostileName = "O'Brien Corp; DROP TABLE instrument; --"; + const hostileSourceId = "BAD'ID;DELETE"; + + const stageA = emptyStageA(); + stageA.instruments.push({ + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: hostileName, + members: [{ source: 'ib', sourceId: hostileSourceId, currency: 'USD', method: 'tier1_isin' }], + }); + stageA.conflicts.push({ + source: 'eod', + sourceId: hostileSourceId, + conflictKind: 'isin_cusip_mismatch', + detail: { + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + derivedIsin: null, + }, + }); + + const stageB = emptyStageB(); + const key = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + stageB.listings.push({ + ...key, + ibConid: 265598, + ibPrimaryExchange: 'NASDAQ', + listedFrom: '1980-12-12', + listedTo: null, + }); + stageB.providerMappings.push({ + source: 'ib', + sourceId: hostileSourceId, + listingKey: key, + method: 'tier1_isin', + validFrom: null, + validTo: null, + }); + + await persistSecurityMaster(client, { + stageA, + stageB, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }); + + for (const q of queries) { + expect(q.text).not.toContain(hostileName); + expect(q.text).not.toContain(hostileSourceId); + expect(q.text).not.toContain('US0378331005'); + } + + const mappingInsert = queries.find(q => q.text.startsWith('INSERT INTO provider_mapping')); + expect(mappingInsert?.values?.[2]).toEqual([DEFAULT_VALID_FROM]); + expect(mappingInsert?.values?.[6]).toEqual([ + PROVIDER_MAPPING_CONFIDENCE.tier1_isin.toFixed(3), + ]); + }); + + test('statement count scales with O(ceil(N / chunkSize)) rather than O(N)', async () => { + const count = 600; + const chunkSize = 200; + const stageA = emptyStageA(); + const stageB = emptyStageB(); + const securityTypeByIsin = new Map(); + + for (let i = 0; i < count; i++) { + const isin = `US${String(i).padStart(9, '0')}0`; + const cusip = String(i).padStart(9, '0'); + stageA.instruments.push({ + primaryIsin: isin, + primaryCusip: cusip, + issuerCountry: 'US', + canonicalName: `Corp ${i}`, + members: [{ source: 'eod', sourceId: `T${i}.US`, currency: 'USD', method: 'tier1_isin' }], + }); + securityTypeByIsin.set(isin, 'common'); + const key = { + primaryIsin: isin, + mic: 'XNAS', + tickerRoot: `T${i}`, + classSuffix: '', + currency: 'USD', + }; + stageB.listings.push({ + ...key, + ibConid: null, + ibPrimaryExchange: null, + listedFrom: '2020-01-01', + listedTo: null, + }); + stageB.providerMappings.push({ + source: 'eod', + sourceId: `T${i}.US`, + listingKey: key, + method: 'tier1_isin', + validFrom: null, + validTo: null, + }); + stageB.providerMappings.push({ + source: 'qm', + sourceId: `T${i}:US`, + listingKey: key, + method: 'tier3_ticker_span', + validFrom: '2020-01-01', + validTo: null, + }); + } + + const { client, queries } = createMockClient(); + const result = await persistSecurityMaster( + client, + { stageA, stageB, securityTypeByIsin }, + { chunkSize } + ); + + expect(result.instrumentsInserted).toBe(count); + expect(result.listingsInserted).toBe(count); + expect(result.providerMappingsInserted).toBe(count * 2); + // 3 chunks for instruments (select+insert), 6 for id_history (ISIN+CUSIP), + // 1 exchange select, 3+3+3 for listings (select+insert+symbol_history), + // 6 for provider_mapping, plus BEGIN/lock/override/COMMIT = 31 queries total << 600 rows. + expect(queries.length).toBeLessThan(40); + }); + + test('canonicalizes JSONB keys deterministically regardless of property insertion order', () => { + const a = { z: 1, a: { d: 2, b: [3, undefined, { y: true, x: false }] }, dropMe: undefined }; + const b = { a: { b: [3, null, { x: false, y: true }], d: 2 }, z: 1 }; + + expect(stableJsonStringify(a)).toBe(stableJsonStringify(b)); + expect(canonicalizeJsonValue(Number.NaN)).toBeNull(); + }); + + test('selects best member source for instrument_identifier_history (tier1_isin > tier2_cusip, ib > eod)', async () => { + const stageA = emptyStageA(); + stageA.instruments.push( + { + primaryIsin: 'US0000000010', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Tier1 IB wins over EOD', + members: [ + { source: 'eod', sourceId: 'A.US', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: '1', currency: 'USD', method: 'tier1_isin' }, + ], + }, + { + primaryIsin: 'US0000000020', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Tier1 EOD wins over Tier2 IB', + members: [ + { source: 'ib', sourceId: '2', currency: 'USD', method: 'tier2_cusip' }, + { source: 'eod', sourceId: 'B.US', currency: 'USD', method: 'tier1_isin' }, + ], + }, + { + primaryIsin: 'US0000000030', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Empty members falls back to eod', + members: [], + } + ); + + const { client, queries } = createMockClient(); + await persistSecurityMaster(client, { + stageA, + stageB: emptyStageB(), + securityTypeByIsin: new Map([ + ['US0000000010', 'common'], + ['US0000000020', 'common'], + ['US0000000030', 'common'], + ]), + }); + + const idHistoryQuery = queries.find(q => + q.text.startsWith('INSERT INTO instrument_identifier_history') + ); + expect(idHistoryQuery?.values?.[4]).toEqual(['ib', 'eod', 'eod']); + }); + + test('rejects duplicate input natural keys and duplicate DB listing rows', async () => { + const { client } = createMockClient(); + + // 1. Duplicate primaryIsin + const dupIsin = emptyStageA(); + dupIsin.instruments.push( + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple', + members: [], + }, + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple Dup', + members: [], + } + ); + await expect( + persistSecurityMaster(client, { + stageA: dupIsin, + stageB: emptyStageB(), + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }) + ).rejects.toThrow(/Duplicate primaryIsin/); + + // 2. Duplicate listing natural key + const stageA = emptyStageA(); + stageA.instruments.push({ + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple', + members: [], + }); + const dupListing = emptyStageB(); + const key = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + dupListing.listings.push( + { ...key, ibConid: null, ibPrimaryExchange: null, listedFrom: null, listedTo: null }, + { ...key, ibConid: 1, ibPrimaryExchange: 'NASDAQ', listedFrom: null, listedTo: null } + ); + await expect( + persistSecurityMaster(client, { + stageA, + stageB: dupListing, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }) + ).rejects.toThrow(/Duplicate listing natural key/); + + // 3. Duplicate provider_mapping PK + const dupMapping = emptyStageB(); + dupMapping.listings.push({ + ...key, + ibConid: null, + ibPrimaryExchange: null, + listedFrom: null, + listedTo: null, + }); + dupMapping.providerMappings.push( + { + source: 'eod', + sourceId: 'AAPL.US', + listingKey: key, + method: 'tier1_isin', + validFrom: null, + validTo: null, + }, + { + source: 'eod', + sourceId: 'AAPL.US', + listingKey: key, + method: 'tier1_isin', + validFrom: DEFAULT_VALID_FROM, + validTo: null, + } + ); + await expect( + persistSecurityMaster(client, { + stageA, + stageB: dupMapping, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }) + ).rejects.toThrow(/Duplicate provider_mapping primary key/); + + // 4. Duplicate Pass 6 listing outcome + const dupPass6: DelistingChainResult = { + continuities: [], + listingOutcomes: [ + { listingKey: key, delistReason: 'active', terminalReturn: null }, + { listingKey: key, delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, + ], + conflicts: [], + stats: { + totalInputListings: 1, + processedListings: 1, + skippedMalformedEntries: 0, + skippedInvalidDates: 0, + skippedDuplicateKeys: 0, + continuitiesCreated: 0, + conflictsDetected: 0, + byOutcome: { active: 1, moved_to_otc: 0, bankruptcy_cancelled: 0, unknown_involuntary: 0 }, + }, + }; + const singleStageB = emptyStageB(); + singleStageB.listings.push({ + ...key, + ibConid: null, + ibPrimaryExchange: null, + listedFrom: null, + listedTo: null, + }); + await expect( + persistSecurityMaster(client, { + stageA, + stageB: singleStageB, + pass6: dupPass6, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }) + ).rejects.toThrow(/Duplicate listing outcome key/); + + // 5. Duplicate existing DB listing rows for incoming natural key + const { client: dupDbClient, queries: dupDbQueries } = createMockClient(text => { + if (text.startsWith('SELECT') && text.includes('FROM instrument')) { + return { + rows: [ + { + instrument_id: 7, + primary_isin: 'US0378331005', + primary_cusip: '037833100', + canonical_name: 'Apple', + security_type: 'common', + issuer_country: 'US', + }, + ], + }; + } + if (text.startsWith('SELECT mic FROM exchange')) { + return { rows: [{ mic: 'XNAS' }] }; + } + if (text.startsWith('SELECT') && text.includes('FROM listing')) { + return { + rows: [ + { + listing_id: 1, + instrument_id: 7, + mic: 'XNAS', + ticker_root: 'AAPL', + class_suffix: '', + currency: 'USD', + ib_conid: null, + ib_primary_exchange: null, + listed_from: null, + listed_to: null, + delist_reason: null, + terminal_return: null, + }, + { + listing_id: 2, + instrument_id: 7, + mic: 'XNAS', + ticker_root: 'AAPL', + class_suffix: '', + currency: 'USD', + ib_conid: null, + ib_primary_exchange: null, + listed_from: '2020-01-01', + listed_to: null, + delist_reason: null, + terminal_return: null, + }, + ], + }; + } + return { rows: [] }; + }); + + await expect( + persistSecurityMaster(dupDbClient, { + stageA, + stageB: singleStageB, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }) + ).rejects.toThrow(/duplicate rows for natural key/); + expect(dupDbQueries.at(-1)?.text).toBe('ROLLBACK'); + }); + + test('executes ROLLBACK and rethrows original error on mid-run failure (even if ROLLBACK fails)', async () => { + const boom = new Error('injected check violation'); + const { client, queries } = createMockClient(text => { + if (text.startsWith('INSERT INTO instrument (')) { + throw boom; + } + if (text === 'ROLLBACK') { + throw new Error('rollback also failed'); + } + return { rows: [] }; + }); + + const stageA = emptyStageA(); + stageA.instruments.push({ + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple Inc.', + members: [], + }); + + await expect( + persistSecurityMaster(client, { + stageA, + stageB: emptyStageB(), + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }) + ).rejects.toBe(boom); + + expect(queries.some(q => q.text === 'BEGIN')).toBe(true); + expect(queries.some(q => q.text === 'ROLLBACK')).toBe(true); + expect(queries.some(q => q.text === 'COMMIT')).toBe(false); + expect(formatListingNaturalKey({ + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + })).toBe('US0378331005\u0000XNAS\u0000AAPL\u0000\u0000USD'); + }); + + test('rejects overlapping calls on the same client before issuing BEGIN and allows sequential reuse', async () => { + let releaseFirstBegin!: () => void; + const firstBeginPaused = new Promise(resolve => { + releaseFirstBegin = resolve; + }); + let beginCount = 0; + + const { client, queries } = createMockClient(async text => { + if (text === 'BEGIN') { + beginCount += 1; + if (beginCount === 1) { + await firstBeginPaused; + } + } + return { rows: [] }; + }); + + const emptyInput: PersistSecurityMasterInput = { + stageA: emptyStageA(), + stageB: emptyStageB(), + securityTypeByIsin: new Map(), + }; + + const firstCall = persistSecurityMaster(client, emptyInput); + const secondCall = persistSecurityMaster(client, emptyInput); + + await expect(secondCall).rejects.toThrow(/overlapping calls on the same client/); + // Second call must reject before issuing a second BEGIN. + expect(queries.filter(q => q.text === 'BEGIN')).toHaveLength(1); + + releaseFirstBegin(); + const firstResult = await firstCall; + expect(firstResult.instrumentsInserted).toBe(0); + + // Once the first call completes, sequential reuse of the same client succeeds. + const thirdResult = await persistSecurityMaster(client, emptyInput); + expect(thirdResult.instrumentsInserted).toBe(0); + expect(queries.filter(q => q.text === 'BEGIN')).toHaveLength(2); + }); + + test('counts each provider_mapping key once across matcher and override outcomes', async () => { + const stageA = emptyStageA(); + stageA.instruments.push({ + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple Inc.', + members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }], + }); + const key = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const stageB = emptyStageB(); + stageB.listings.push({ + ...key, + ibConid: null, + ibPrimaryExchange: null, + listedFrom: '1980-12-12', + listedTo: null, + }); + stageB.providerMappings.push( + // Existing row skipped by matcher because override exists, then updated by override + { + source: 'eod', + sourceId: 'AAPL.US', + listingKey: key, + method: 'tier1_isin', + validFrom: '1980-12-12', + validTo: null, + }, + // Fresh row inserted by matcher, then immediately updated by override -> net outcome: inserted + { + source: 'ib', + sourceId: '265598', + listingKey: key, + method: 'tier1_isin', + validFrom: '1980-12-12', + validTo: null, + }, + // Existing row unchanged by matcher and not in override -> unchanged + { + source: 'qm', + sourceId: 'AAPL:US', + listingKey: key, + method: 'tier3_ticker_span', + validFrom: '2010-01-04', + validTo: null, + } + ); + + const { client } = createMockClient((text, values) => { + if (text.startsWith('SELECT mic FROM exchange')) { + return { rows: [{ mic: 'XNAS' }] }; + } + if (text.startsWith('INSERT INTO instrument (')) { + return { rows: [{ instrument_id: 1, primary_isin: 'US0378331005' }] }; + } + if (text.startsWith('INSERT INTO instrument_identifier_history')) { + const ids = (values?.[0] as number[]) ?? []; + return { rows: ids.map(() => ({ inserted: 1 })) }; + } + if (text.startsWith('INSERT INTO listing (')) { + return { + rows: [ + { + listing_id: 10, + instrument_id: 1, + mic: 'XNAS', + ticker_root: 'AAPL', + class_suffix: '', + currency: 'USD', + }, + ], + }; + } + if (text.includes('INTO listing_symbol_history')) { + return { rows: [{ inserted_count: 1, updated_count: 0 }] }; + } + if (text.startsWith('INSERT INTO provider_mapping')) { + // Only the fresh ib row is inserted by matcher; eod is skipped by override guard; qm unchanged. + return { + rows: [ + { source: 'ib', source_id: '265598', valid_from: '1980-12-12', inserted: true }, + ], + }; + } + if (text.includes('WITH enforced AS')) { + return { + rows: [ + { source: 'eod', source_id: 'AAPL.US', valid_from: '1980-12-12', inserted: false }, + { source: 'ib', source_id: '265598', valid_from: '1980-12-12', inserted: false }, + { source: 'qm', source_id: 'OVR_NEW:US', valid_from: '2021-01-01', inserted: true }, + { source: 'qm', source_id: 'OVR_SAME:US', valid_from: '2021-01-01', inserted: null }, + ], + }; + } + return { rows: [] }; + }); + + const result = await persistSecurityMaster(client, { + stageA, + stageB, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }); + + expect(result.overridesApplied).toBe(4); + expect(result.providerMappingsInserted).toBe(2); // ib (fresh+overridden) + OVR_NEW + expect(result.providerMappingsUpdated).toBe(1); // eod (existing+overridden) + expect(result.providerMappingsUnchanged).toBe(2); // qm AAPL:US + OVR_SAME + }); + + test('pass4 omitted leaves conflict SQL and counts identical to non-Pass-4 behavior', async () => { + const stageA = emptyStageA(); + stageA.conflicts.push({ + source: 'eod', + sourceId: 'BAD.US', + conflictKind: 'isin_cusip_mismatch', + detail: { + isin: 'US0378331005', + cusip: '594918104', + country: 'US', + derivedIsin: 'US5949181045', + }, + }); + const stageB = emptyStageB(); + + const { client, queries } = createMockClient(); + const result = await persistSecurityMaster(client, { + stageA, + stageB, + securityTypeByIsin: new Map(), + }); + + expect(result.conflictsInserted).toBe(1); + expect(result.conflictsUnchanged).toBe(0); + expect(result.conflictsDeduplicated).toBe(0); + + // Must run ONLY the 3-column non-Pass-4 existence query, never the Pass 4 JSONB detail query. + const conflictSelects = queries.filter(q => q.text.includes('FROM resolution_conflict rc')); + expect(conflictSelects.length).toBe(1); + expect(conflictSelects[0]?.text).not.toContain('rc.detail = u.detail'); + }); + + test('pass4 supplied preserves distinct pairs sharing a left endpoint, deduplicates exact duplicates, and checks rc.detail = u.detail', async () => { + const stageA = emptyStageA(); + const stageB = emptyStageB(); + + const conflictPair1: PriceCrossCheckConflictRecord = { + source: 'eod', + sourceId: 'AAPL.US', + conflictKind: 'price_ratio_mismatch', + detail: { + left: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' }, + right: { source: 'qm', sourceId: 'AAPL:US', currency: 'USD' }, + verdict: 'ratio_mismatch', + usableDates: 5, + medianRatio: 1.5, + priceCorr: 0.99, + ratioTolerance: 0.02, + minCorrelation: 0.9, + }, + }; + const conflictPair2SameLeft: PriceCrossCheckConflictRecord = { + source: 'eod', + sourceId: 'AAPL.US', + conflictKind: 'price_ratio_mismatch', + detail: { + left: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' }, + right: { source: 'ceo', sourceId: 'AAPL', currency: 'USD' }, + verdict: 'ratio_mismatch', + usableDates: 5, + medianRatio: 2.0, + priceCorr: 0.98, + ratioTolerance: 0.02, + minCorrelation: 0.9, + }, + }; + + const pass4: PriceCrossCheckResult = { + results: [], + conflicts: [conflictPair1, conflictPair2SameLeft, conflictPair1], // 1 exact duplicate + stats: { + pairsIn: 2, + invalidPairs: 0, + byVerdict: { + unsupported_currency_pair: 0, + insufficient_data: 0, + ratio_mismatch: 2, + low_correlation: 0, + confirmed: 0, + }, + conflictsEmitted: 3, + droppedInvalidCloses: 0, + droppedConflictingCloses: 0, + droppedInvalidFxRates: 0, + droppedConflictingFxRates: 0, + skippedMissingFxDates: 0, + }, + }; + + // First run: neither pair exists in DB -> both inserted, 1 exact duplicate deduplicated. + const first = createMockClient(); + const firstResult = await persistSecurityMaster(first.client, { + stageA, + stageB, + pass4, + securityTypeByIsin: new Map(), + }); + + expect(firstResult.conflictsInserted).toBe(2); + expect(firstResult.conflictsUnchanged).toBe(0); + expect(firstResult.conflictsDeduplicated).toBe(1); + + const pass4Selects = first.queries.filter( + q => q.text.includes('FROM resolution_conflict rc') && q.text.includes('rc.detail = u.detail') + ); + expect(pass4Selects.length).toBe(1); + // Regression: PostgreSQL UTF-8 text/varchar rejects NUL bytes (\u0000); Pass 4 existence check + // must pass integer row indices ($5::int4[]) rather than NUL-delimited internal keys. + expect(pass4Selects[0]?.values?.[4]).toEqual([0, 1]); + for (const param of pass4Selects[0]?.values ?? []) { + if (Array.isArray(param)) { + for (const item of param) { + if (typeof item === 'string') { + expect(item.includes('\u0000')).toBe(false); + } + } + } + } + const conflictInserts = first.queries.filter(q => + q.text.startsWith('INSERT INTO resolution_conflict') + ); + expect(conflictInserts.length).toBe(1); + expect((conflictInserts[0]?.values?.[0] as string[]).length).toBe(2); + + // Second run: simulate pair 1 (index 0 in sorted slice) already existing in DB -> only pair 2 inserted. + const second = createMockClient(text => { + if (text.includes('FROM resolution_conflict rc') && text.includes('rc.detail = u.detail')) { + return { rows: [{ row_idx: 0 }] }; + } + return { rows: [] }; + }); + + const secondResult = await persistSecurityMaster(second.client, { + stageA, + stageB, + pass4, + securityTypeByIsin: new Map(), + }); + + expect(secondResult.conflictsUnchanged).toBe(1); + expect(secondResult.conflictsInserted).toBe(1); + expect(secondResult.conflictsDeduplicated).toBe(1); + }); + + test('rejects invalid pass4.conflicts shape before BEGIN', async () => { + const { client, queries } = createMockClient(); + await expect( + persistSecurityMaster(client, { + stageA: emptyStageA(), + stageB: emptyStageB(), + pass4: { conflicts: 'bad' } as unknown as PriceCrossCheckResult, + securityTypeByIsin: new Map(), + }) + ).rejects.toThrow(TypeError); + expect(queries.length).toBe(0); + }); + + test('selects deduplicated dated-only stale-fallback targets with override guards and parameterized SQL', async () => { + const hostileSourceId = "HOSTILE'ID;DELETE"; + const stageA = emptyStageA(); + stageA.instruments.push({ + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple Inc.', + members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }], + }); + const validKey = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const missingKey = { + primaryIsin: 'US0378331005', + mic: 'XXXX', + tickerRoot: 'MISS', + classSuffix: '', + currency: 'USD', + }; + const stageB = emptyStageB(); + stageB.listings.push({ + ...validKey, + ibConid: null, + ibPrimaryExchange: null, + listedFrom: '2012-05-18', + listedTo: null, + }); + stageB.providerMappings.push( + // Dated-only with two dated rows -> must appear ONCE in staleFallbackTargets + { + source: 'eod', + sourceId: 'DATED_MULTI.US', + listingKey: validKey, + method: 'tier1_isin', + validFrom: '2012-05-18', + validTo: '2019-12-31', + }, + { + source: 'eod', + sourceId: 'DATED_MULTI.US', + listingKey: validKey, + method: 'tier1_isin', + validFrom: '2020-01-01', + validTo: null, + }, + // Dated-only with hostile sourceId -> must be parameterized, never interpolated + { + source: 'qm', + sourceId: hostileSourceId, + listingKey: validKey, + method: 'tier3_ticker_span', + validFrom: '2015-01-02', + validTo: null, + }, + // Fallback-only (null) -> excluded + { + source: 'eod', + sourceId: 'FALLBACK_NULL.US', + listingKey: validKey, + method: 'tier1_isin', + validFrom: null, + validTo: null, + }, + // Fallback-only (explicit DEFAULT_VALID_FROM) -> excluded + { + source: 'eod', + sourceId: 'FALLBACK_EXPLICIT.US', + listingKey: validKey, + method: 'tier1_isin', + validFrom: DEFAULT_VALID_FROM, + validTo: null, + }, + // Mixed fallback-first then dated -> excluded + { + source: 'eod', + sourceId: 'MIXED_FB_FIRST.US', + listingKey: validKey, + method: 'tier1_isin', + validFrom: null, + validTo: '2014-12-31', + }, + { + source: 'eod', + sourceId: 'MIXED_FB_FIRST.US', + listingKey: validKey, + method: 'tier1_isin', + validFrom: '2015-01-01', + validTo: null, + }, + // Mixed dated-first then fallback -> excluded + { + source: 'eod', + sourceId: 'MIXED_DATED_FIRST.US', + listingKey: validKey, + method: 'tier1_isin', + validFrom: '2015-01-01', + validTo: null, + }, + { + source: 'eod', + sourceId: 'MIXED_DATED_FIRST.US', + listingKey: validKey, + method: 'tier1_isin', + validFrom: DEFAULT_VALID_FROM, + validTo: '2014-12-31', + }, + // Dated mapping whose listing is skipped (missing_listing) -> excluded + { + source: 'eod', + sourceId: 'SKIPPED_LISTING.US', + listingKey: missingKey, + method: 'tier1_isin', + validFrom: '2018-01-01', + validTo: null, + } + ); + + const { client, queries } = createMockClient((text, values) => { + if (text.startsWith('SELECT mic FROM exchange')) { + return { rows: [{ mic: 'XNAS' }] }; + } + if (text.startsWith('INSERT INTO instrument (')) { + return { rows: [{ instrument_id: 1, primary_isin: 'US0378331005' }] }; + } + if (text.startsWith('INSERT INTO instrument_identifier_history')) { + const ids = (values?.[0] as number[]) ?? []; + return { rows: ids.map(() => ({ inserted: 1 })) }; + } + if (text.startsWith('INSERT INTO listing (')) { + return { + rows: [ + { + listing_id: 10, + instrument_id: 1, + mic: 'XNAS', + ticker_root: 'AAPL', + class_suffix: '', + currency: 'USD', + }, + ], + }; + } + if (text.includes('INTO listing_symbol_history')) { + return { rows: [{ inserted_count: 1, updated_count: 0 }] }; + } + if (text.startsWith('INSERT INTO provider_mapping')) { + const sources = (values?.[0] as string[]) ?? []; + const sourceIds = (values?.[1] as string[]) ?? []; + const validFroms = (values?.[2] as string[]) ?? []; + return { + rows: sources.map((source, i) => ({ + source, + source_id: sourceIds[i], + valid_from: validFroms[i], + inserted: true, + })), + }; + } + if (text.includes('DELETE FROM provider_mapping')) { + return { rows: [{ deleted_count: 2 }] }; + } + return { rows: [] }; + }); + + const result = await persistSecurityMaster(client, { + stageA, + stageB, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }); + + const deleteQueries = queries.filter(q => q.text.includes('DELETE FROM provider_mapping')); + expect(deleteQueries).toHaveLength(1); + const dq = deleteQueries[0]!; + expect(dq.text).toContain("pm.method <> 'override'"); + expect(dq.text).toContain('NOT EXISTS'); + expect(dq.text).toContain('FROM override o'); + expect(dq.text).not.toContain(hostileSourceId); + expect(dq.values).toEqual([ + ['eod', 'qm'], + ['DATED_MULTI.US', hostileSourceId], + DEFAULT_VALID_FROM, + ]); + + expect(result.providerMappingsDeletedStaleFallback).toBe(2); + expect(result.providerMappingsInserted).toBe(9); + expect(result.providerMappingsUpdated).toBe(0); + expect(result.providerMappingsUnchanged).toBe(0); + expect(result.providerMappingsSkipped).toBe(1); + }); + + test('batches stale-fallback deletes by chunkSize and sums counts independently of upsert totals', async () => { + const stageA = emptyStageA(); + stageA.instruments.push({ + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple Inc.', + members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }], + }); + const key = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const stageB = emptyStageB(); + stageB.listings.push({ + ...key, + ibConid: null, + ibPrimaryExchange: null, + listedFrom: '2012-05-18', + listedTo: null, + }); + for (let i = 0; i < 5; i++) { + stageB.providerMappings.push({ + source: 'eod', + sourceId: `S${i}.US`, + listingKey: key, + method: 'tier1_isin', + validFrom: '2012-05-18', + validTo: null, + }); + } + + const chunkDeleteCounts = [1, 2, 0]; + let deleteChunkIdx = 0; + const { client, queries } = createMockClient((text, values) => { + if (text.startsWith('SELECT mic FROM exchange')) { + return { rows: [{ mic: 'XNAS' }] }; + } + if (text.startsWith('INSERT INTO instrument (')) { + return { rows: [{ instrument_id: 1, primary_isin: 'US0378331005' }] }; + } + if (text.startsWith('INSERT INTO instrument_identifier_history')) { + const ids = (values?.[0] as number[]) ?? []; + return { rows: ids.map(() => ({ inserted: 1 })) }; + } + if (text.startsWith('INSERT INTO listing (')) { + return { + rows: [ + { + listing_id: 10, + instrument_id: 1, + mic: 'XNAS', + ticker_root: 'AAPL', + class_suffix: '', + currency: 'USD', + }, + ], + }; + } + if (text.includes('INTO listing_symbol_history')) { + return { rows: [{ inserted_count: 1, updated_count: 0 }] }; + } + if (text.startsWith('INSERT INTO provider_mapping')) { + const sources = (values?.[0] as string[]) ?? []; + const sourceIds = (values?.[1] as string[]) ?? []; + const validFroms = (values?.[2] as string[]) ?? []; + return { + rows: sources.map((source, i) => ({ + source, + source_id: sourceIds[i], + valid_from: validFroms[i], + inserted: true, + })), + }; + } + if (text.includes('DELETE FROM provider_mapping')) { + const deleted = chunkDeleteCounts[deleteChunkIdx++] ?? 0; + return { rows: [{ deleted_count: deleted }] }; + } + return { rows: [] }; + }); + + const result = await persistSecurityMaster( + client, + { + stageA, + stageB, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }, + { chunkSize: 2 } + ); + + const deleteQueries = queries.filter(q => q.text.includes('DELETE FROM provider_mapping')); + expect(deleteQueries).toHaveLength(3); + expect(deleteQueries.map(q => (q.values?.[1] as string[]).length)).toEqual([2, 2, 1]); + expect(result.providerMappingsDeletedStaleFallback).toBe(3); + expect(result.providerMappingsInserted).toBe(5); + expect(result.providerMappingsUpdated).toBe(0); + expect(result.providerMappingsUnchanged).toBe(0); + }); + + test('issues zero DELETE queries when no dated-only provider_mapping pairs exist', async () => { + const stageA = emptyStageA(); + stageA.instruments.push({ + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple Inc.', + members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }], + }); + const key = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const stageB = emptyStageB(); + stageB.listings.push({ + ...key, + ibConid: null, + ibPrimaryExchange: null, + listedFrom: null, + listedTo: null, + }); + stageB.providerMappings.push( + { + source: 'eod', + sourceId: 'AAPL.US', + listingKey: key, + method: 'tier1_isin', + validFrom: null, + validTo: null, + }, + { + source: 'qm', + sourceId: 'AAPL:US', + listingKey: key, + method: 'tier3_ticker_span', + validFrom: DEFAULT_VALID_FROM, + validTo: '2014-12-31', + }, + { + source: 'qm', + sourceId: 'AAPL:US', + listingKey: key, + method: 'tier3_ticker_span', + validFrom: '2015-01-01', + validTo: null, + } + ); + + const { client, queries } = createMockClient(); + const result = await persistSecurityMaster(client, { + stageA, + stageB, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }); + + expect(queries.filter(q => q.text.includes('DELETE FROM provider_mapping'))).toHaveLength(0); + expect(result.providerMappingsDeletedStaleFallback).toBe(0); + expect(result.providerMappingsInserted).toBe(3); + }); + + test('rolls back instead of committing when a step after the stale-fallback DELETE fails', async () => { + const stageA = emptyStageA(); + stageA.instruments.push({ + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple Inc.', + members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }], + }); + const key = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const stageB = emptyStageB(); + stageB.listings.push({ + ...key, + ibConid: null, + ibPrimaryExchange: null, + listedFrom: '2012-05-18', + listedTo: null, + }); + stageB.providerMappings.push({ + source: 'eod', + sourceId: 'AAPL.US', + listingKey: key, + method: 'tier1_isin', + validFrom: '2012-05-18', + validTo: null, + }); + + const base = createMockClient(); + const queries: RecordedQuery[] = []; + const client: SecurityMasterQueryable = { + release: () => undefined, + async query>(text: string, values?: readonly unknown[]) { + if (text.includes('WITH enforced AS')) { + queries.push({ text, values }); + throw new Error('override enforcement failed'); + } + const res = await base.client.query(text, values); + queries.push({ text, values }); + return res; + }, + }; + + await expect( + persistSecurityMaster(client, { + stageA, + stageB, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }) + ).rejects.toThrow('override enforcement failed'); + + const texts = queries.map(q => q.text.trim()); + const deleteIdx = texts.findIndex(t => t.includes('DELETE FROM provider_mapping')); + expect(texts[0]).toBe('BEGIN'); + expect(deleteIdx).toBeGreaterThan(0); + expect(texts.at(-1)).toBe('ROLLBACK'); + expect(texts).not.toContain('COMMIT'); + }); +}); diff --git a/test/unit/security-master-run-cli.test.ts b/test/unit/security-master-run-cli.test.ts new file mode 100644 index 00000000..faba4bee --- /dev/null +++ b/test/unit/security-master-run-cli.test.ts @@ -0,0 +1,1521 @@ +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { assertEnvironmentSafety, stockAppSchema } from '@stock-bot/stock-config'; +import { + computeBarSpans, + type BarSpanAggregateReader, + type GroupedBarSpanRow, +} from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; +import { + assertSecurityMasterPersistSafety, + classifySourceExchanges, + compareAscii, + composeSecurityMasterRun, + createExchangeSourceLookup, + createReadOnlyMongoSourceSymbolReader, + EXCHANGE_SOURCES, + ISO_EXCHANGE_SEEDS, + normalizeRawExchangeDoc, + parseRunSecurityMasterArgs, + readSecurityMasterSources, + RUN_SECURITY_MASTER_USAGE, + runSecurityMaster, + SECURITY_MASTER_OUTPUT_FILES, + SOURCE_EXCHANGE_COLLECTIONS, + type PersistSecurityMasterInput, + type PersistSecurityMasterResult, + type ReadOnlyMongoCollectionClient, + type SecurityMasterPostgresHandle, + type SecurityMasterQueryable, + type SourceExchangeRecord, +} from '../../apps/stock/data-pipeline/src/security-master'; + +const cliSourcePath = fileURLToPath( + new URL( + '../../apps/stock/data-pipeline/src/security-master/run-security-master.ts', + import.meta.url + ) +); + +const tempDirs: string[] = []; + +function createTempDir(prefix = 'sm-run-cli-'): string { + const dir = mkdtempSync(join(tmpdir(), prefix)); + tempDirs.push(dir); + return dir; +} + +afterEach(() => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir) { + rmSync(dir, { recursive: true, force: true }); + } + } +}); + +interface FakeMongoFixture { + readonly collections: Readonly[]>>; + readonly barSpanRowsByCollection?: Readonly>; +} + +function makeAsyncCursor(docs: readonly Record[]) { + let closed = false; + return { + async *[Symbol.asyncIterator](): AsyncIterator> { + for (const doc of docs) { + if (closed) { + break; + } + yield doc; + } + }, + async close(): Promise { + closed = true; + }, + }; +} + +function extractRequestedIdsFromPipeline(pipeline: readonly Record[]): Set | null { + for (const stage of pipeline) { + const match = stage.$match; + if (match && typeof match === 'object') { + for (const value of Object.values(match as Record)) { + if (value && typeof value === 'object' && Array.isArray((value as { $in?: unknown }).$in)) { + return new Set(((value as { $in: unknown[] }).$in).map(String)); + } + } + } + } + return null; +} + +function createStrictReadOnlyFakeMongo( + fixture: FakeMongoFixture, + options: { + readonly readOnly?: boolean; + readonly failCollection?: string; + readonly failAggregate?: boolean; + } = {} +): { + readonly mongoCollectionClient: ReadOnlyMongoCollectionClient; + readonly barSpanReader: BarSpanAggregateReader; + readonly aggregateCalls: Array<{ collectionName: string; pipeline: Record[] }>; + readonly findCalls: string[]; +} { + const readOnly = options.readOnly ?? true; + const aggregateCalls: Array<{ collectionName: string; pipeline: Record[] }> = []; + const findCalls: string[] = []; + + const target = { + isReadOnly(): boolean { + return readOnly; + }, + getCollection(collectionName: string) { + const colTarget = { + find(_filter: Record = {}) { + findCalls.push(collectionName); + if (options.failCollection === collectionName) { + throw new Error(`Simulated Mongo find failure on ${collectionName}`); + } + const docs = fixture.collections[collectionName] ?? []; + return makeAsyncCursor(docs); + }, + }; + + return new Proxy(colTarget, { + get(obj, prop, receiver) { + if (prop === 'find') { + return Reflect.get(obj, prop, receiver); + } + throw new Error(`Forbidden MongoDB collection method called: ${String(prop)}`); + }, + }); + }, + aggregate = Record>( + collectionName: string, + pipeline: Record[] + ): AsyncIterable { + aggregateCalls.push({ collectionName, pipeline }); + if (options.failAggregate) { + throw new Error(`Simulated Mongo aggregate failure on ${collectionName}`); + } + const allRows = fixture.barSpanRowsByCollection?.[collectionName] ?? []; + const requestedIds = extractRequestedIdsFromPipeline(pipeline); + const filtered = + requestedIds === null + ? allRows + : allRows.filter(row => typeof row._id === 'string' && requestedIds.has(row._id)); + + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (const row of filtered) { + yield row as unknown as T; + } + }, + }; + }, + }; + + const proxy = new Proxy(target, { + get(obj, prop, receiver) { + if (prop === 'isReadOnly' || prop === 'getCollection' || prop === 'aggregate') { + return Reflect.get(obj, prop, receiver); + } + throw new Error(`Forbidden MongoDB client method called: ${String(prop)}`); + }, + }); + + return { + mongoCollectionClient: proxy as unknown as ReadOnlyMongoCollectionClient, + barSpanReader: proxy as unknown as BarSpanAggregateReader, + aggregateCalls, + findCalls, + }; +} + +function buildUsCaFixture(): FakeMongoFixture { + return { + collections: { + eodExchanges: [ + { Code: 'US', Name: 'USA Stocks', Country: 'USA', Currency: 'USD', OperatingMIC: 'XNAS' }, + { Code: 'TO', Name: 'Toronto Exchange', Country: 'Canada', Currency: 'CAD', OperatingMIC: 'XTSE' }, + ], + ibExchanges: [ + { exchange: 'NASDAQ', country: 'US', currency: 'USD', mic: 'XNAS' }, + { exchange: 'TSE', country: 'CA', currency: 'CAD', mic: 'XTSE' }, + ], + qmExchanges: [ + { exchange: 'NSD', country: 'US', currency: 'USD' }, + { exchange: 'TSX', country: 'CA', currency: 'CAD' }, + ], + ceoExchanges: [], + eodSymbols: [ + { + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Cusip: '037833100', + Name: 'Apple Inc.', + Type: 'Common Stock', + delisted: false, + }, + { + eodSearchCode: 'SHOP.TO', + Code: 'SHOP', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA82509L1076', + Cusip: '82509L107', + Name: 'Shopify Inc.', + Type: 'Common Stock', + delisted: false, + }, + ], + ibSymbols: [ + { + conid: 265598, + symbol: 'AAPL', + localSymbol: 'AAPL', + primaryExchange: 'NASDAQ', + country: 'US', + currency: 'USD', + isin: 'US0378331005', + cusip: '037833100', + name: 'Apple Inc.', + }, + ], + qmSymbols: [ + { + qmSearchCode: 'AAPL:US', + symbol: 'AAPL', + exchange: 'NSD', + countryCode: 'US', + currency: 'USD', + name: 'Apple Inc.', + active: true, + }, + { + // Unresolved symbol: no matching EOD/IB instrument or listing on XTSE. + qmSearchCode: 'MYSTERY:CA', + symbol: 'MYSTERY', + exchange: 'TSX', + countryCode: 'CA', + currency: 'CAD', + name: 'Mystery Corp', + active: true, + }, + ], + ceoSymbols: [], + eodSymbolChange: [], + }, + barSpanRowsByCollection: { + eodPrices: [ + { _id: 'AAPL.US', firstBarDate: '2015-01-02', lastBarDate: '2026-01-14', barCount: 2770 }, + { _id: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2026-01-14', barCount: 2680 }, + ], + qmPrices: [ + { _id: 'AAPL:US', firstBarDate: '2018-01-02', lastBarDate: '2026-01-14', barCount: 2015 }, + { _id: 'MYSTERY:CA', firstBarDate: '2022-01-03', lastBarDate: '2025-12-31', barCount: 990 }, + ], + }, + }; +} + +function makeFakePersistResult(): PersistSecurityMasterResult { + return { + instrumentsInserted: 2, + instrumentsUpdated: 0, + instrumentsUnchanged: 0, + instrumentsSkipped: 0, + identifierHistoryInserted: 4, + identifierHistoryUnchanged: 0, + listingsInserted: 2, + listingsUpdated: 0, + listingsUnchanged: 0, + listingsSkipped: 0, + listingSymbolHistoryInserted: 2, + listingSymbolHistoryUpdated: 0, + listingSymbolHistoryUnchanged: 0, + providerMappingsInserted: 4, + providerMappingsUpdated: 0, + providerMappingsUnchanged: 0, + providerMappingsSkipped: 0, + providerMappingsDeletedStaleFallback: 0, + overridesApplied: 0, + conflictsInserted: 0, + conflictsUnchanged: 0, + conflictsDeduplicated: 0, + pass6OutcomesApplied: 2, + pass6OutcomesSkipped: 0, + continuitiesInserted: 0, + continuitiesUpdated: 0, + continuitiesUnchanged: 0, + continuitiesSkipped: 0, + skippedByReason: { + instruments: { missing_canonical_name: 0, missing_security_type: 0 }, + listings: { skipped_instrument: 0, missing_instrument: 0, unknown_mic: 0 }, + providerMappings: { missing_listing: 0 }, + pass6Outcomes: { missing_listing: 0 }, + continuities: { + missing_from_listing: 0, + missing_to_listing: 0, + missing_both_listings: 0, + }, + }, + instrumentIdByIsin: new Map(), + listingIdByKey: new Map(), + }; +} + +function assertObjectKeysSortedAscii(value: unknown, path = '$'): void { + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + assertObjectKeysSortedAscii(value[i], `${path}[${i}]`); + } + return; + } + if (value !== null && typeof value === 'object') { + const keys = Object.keys(value as Record); + const sorted = [...keys].sort(compareAscii); + expect(keys, `Keys not ASCII-sorted at ${path}`).toEqual(sorted); + for (const key of keys) { + assertObjectKeysSortedAscii((value as Record)[key], `${path}.${key}`); + } + } +} + +describe('parseRunSecurityMasterArgs', () => { + test('parses required space-separated args with default persist=false', () => { + const parsed = parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './tmp/out']); + expect(parsed).toEqual({ + help: false, + asOfDate: '2026-01-15', + outDir: './tmp/out', + persist: false, + }); + }); + + test('parses = syntax, leap day, and --persist flag', () => { + const parsed = parseRunSecurityMasterArgs([ + '--as-of=2024-02-29', + '--out-dir=/tmp/sm-report', + '--persist', + ]); + expect(parsed).toEqual({ + help: false, + asOfDate: '2024-02-29', + outDir: '/tmp/sm-report', + persist: true, + }); + }); + + test('returns { help: true } for --help without requiring other flags', () => { + expect(parseRunSecurityMasterArgs(['--help'])).toEqual({ help: true }); + expect(RUN_SECURITY_MASTER_USAGE).toContain('--as-of'); + expect(RUN_SECURITY_MASTER_USAGE).toContain('--out-dir'); + expect(RUN_SECURITY_MASTER_USAGE).toContain('--persist'); + }); + + test('rejects missing --as-of or --out-dir', () => { + expect(() => parseRunSecurityMasterArgs(['--out-dir', './out'])).toThrow(/--as-of/); + expect(() => parseRunSecurityMasterArgs(['--as-of', '2026-01-15'])).toThrow(/--out-dir/); + }); + + test('rejects invalid calendar dates, compact dates, and timestamps', () => { + for (const badDate of ['2026-13-40', '20260101', '2023-02-29', '2026-01-15T00:00:00Z']) { + expect(() => + parseRunSecurityMasterArgs(['--as-of', badDate, '--out-dir', './out']) + ).toThrow(/Invalid --as-of date/); + } + }); + + test('rejects unknown flags, positional args, and flags missing values', () => { + expect(() => + parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './out', '--unknown']) + ).toThrow(/Unknown argument: --unknown/); + expect(() => + parseRunSecurityMasterArgs(['--as-of', '2026-01-15', '--out-dir', './out', 'positional']) + ).toThrow(/Unknown argument: positional/); + expect(() => + parseRunSecurityMasterArgs(['--as-of', '--out-dir', '/tmp']) + ).toThrow(/Missing value for --as-of/); + expect(() => + parseRunSecurityMasterArgs(['--as-of=2026-01-15', '--out-dir=']) + ).toThrow(/Missing value for --out-dir/); + expect(() => + parseRunSecurityMasterArgs(['--as-of=', '--out-dir=/tmp']) + ).toThrow(/Missing value for --as-of/); + }); +}); + +describe('runSecurityMaster', () => { + test('happy path writes all four files matching composeSecurityMasterRun byte-for-byte', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = join(createTempDir(), 'nested-report'); + const stdoutChunks: string[] = []; + let mongoClosed = 0; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: text => { + stdoutChunks.push(text); + }, + }, + { + asOfDate: '2026-01-15', + outDir, + } + ); + + // Independently compute expected composeSecurityMasterRun output from the same fixture. + const refMongo = createStrictReadOnlyFakeMongo(fixture); + const refReader = createReadOnlyMongoSourceSymbolReader(refMongo.mongoCollectionClient); + const exchangeRecords: SourceExchangeRecord[] = []; + for (const source of EXCHANGE_SOURCES) { + const cursor = await refReader.find>( + SOURCE_EXCHANGE_COLLECTIONS[source], + {} + ); + for await (const doc of cursor) { + exchangeRecords.push(normalizeRawExchangeDoc(source, doc)); + } + } + const expectedExchanges = classifySourceExchanges(exchangeRecords, { + knownExchanges: ISO_EXCHANGE_SEEDS, + }); + const expectedSources = await readSecurityMasterSources(refReader, { + exchangeLookup: createExchangeSourceLookup(expectedExchanges.mapped), + }); + const expectedBarSpans = await computeBarSpans(refMongo.barSpanReader, { + sources: ['eod', 'qm'], + sourceIdsBySource: { + eod: ['AAPL.US', 'SHOP.TO'], + qm: ['AAPL:US', 'MYSTERY:CA'], + }, + }); + const expectedComposed = composeSecurityMasterRun( + { + sources: expectedSources, + barSpans: expectedBarSpans, + exchanges: expectedExchanges, + }, + { asOfDate: '2026-01-15' } + ); + + const matchReportContent = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.matchReport), + 'utf8' + ); + const conflictsCsvContent = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.conflictsCsv), + 'utf8' + ); + const overrideTemplateContent = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.overrideTemplateSql), + 'utf8' + ); + const runStatsContent = readFileSync( + join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), + 'utf8' + ); + + expect(matchReportContent).toBe(expectedComposed.reportMarkdown); + expect(conflictsCsvContent).toBe(expectedComposed.conflictsCsv); + expect(overrideTemplateContent).toBe(expectedComposed.overrideTemplateSql); + + expect(runStatsContent.endsWith('\n')).toBe(true); + const parsedStats = JSON.parse(runStatsContent) as Record; + assertObjectKeysSortedAscii(parsedStats); + expect(parsedStats.asOfDate).toBe('2026-01-15'); + expect(parsedStats.pass4Wired).toBe(false); + expect(result.composed.pass4).toBeNull(); + expect(result.composed.stageA.instruments.length).toBe(2); + expect(result.composed.stageB.unresolved.some(u => u.sourceId === 'MYSTERY:CA')).toBe(true); + + expect(mongoClosed).toBe(1); + const summaryText = stdoutChunks.join(''); + expect(summaryText).toContain('Instruments: 2'); + expect(summaryText).toContain('Persisted: no (dry-run)'); + expect(summaryText).toContain('match-report.md'); + expect(summaryText).toContain('skipped'); + }); + + test('produces byte-identical files across repeated runs in different output directories', async () => { + const fixture = buildUsCaFixture(); + const outDir1 = createTempDir('sm-replay-1-'); + const outDir2 = createTempDir('sm-replay-2-'); + + const mongo1 = createStrictReadOnlyFakeMongo(fixture); + const mongo2 = createStrictReadOnlyFakeMongo(fixture); + + await runSecurityMaster( + { + mongoCollectionClient: mongo1.mongoCollectionClient, + barSpanReader: mongo1.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: outDir1 } + ); + await runSecurityMaster( + { + mongoCollectionClient: mongo2.mongoCollectionClient, + barSpanReader: mongo2.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: outDir2 } + ); + + for (const filename of Object.values(SECURITY_MASTER_OUTPUT_FILES)) { + const content1 = readFileSync(join(outDir1, filename), 'utf8'); + const content2 = readFileSync(join(outDir2, filename), 'utf8'); + expect(content2, `${filename} differed between runs`).toBe(content1); + } + }); + + test('dry run never invokes PostgreSQL factory or persist function', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir(); + let pgFactoryCalls = 0; + let queryCalls = 0; + let persistCalls = 0; + let mongoClosed = 0; + + const fakeQueryable: SecurityMasterQueryable = { + async query() { + queryCalls += 1; + return { rows: [] }; + }, + }; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + createPostgresClient: () => { + pgFactoryCalls += 1; + return { queryable: fakeQueryable, close: () => {} }; + }, + persistFn: async () => { + persistCalls += 1; + return makeFakePersistResult(); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir, persist: false } + ); + + expect(result.persist).toBe(false); + expect(result.persistResult).toBeNull(); + expect(pgFactoryCalls).toBe(0); + expect(queryCalls).toBe(0); + expect(persistCalls).toBe(0); + expect(mongoClosed).toBe(1); + }); + + test('--persist invokes env-safety guard before PostgreSQL factory and calls persistFn once', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir(); + const callOrder: string[] = []; + const capturedInputs: PersistSecurityMasterInput[] = []; + const stdoutChunks: string[] = []; + + const fakeQueryable: SecurityMasterQueryable = { + async query() { + return { rows: [] }; + }, + }; + let receivedQueryable: SecurityMasterQueryable | null = null; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + callOrder.push('closeMongo'); + }, + assertSafety: () => { + callOrder.push('assertSafety'); + }, + createPostgresClient: (): SecurityMasterPostgresHandle => { + callOrder.push('createPostgresClient'); + return { + queryable: fakeQueryable, + close: () => { + callOrder.push('closePostgres'); + }, + }; + }, + persistFn: async (queryable, input) => { + callOrder.push('persistFn'); + receivedQueryable = queryable; + capturedInputs.push(input); + return makeFakePersistResult(); + }, + writeStdout: text => { + stdoutChunks.push(text); + }, + }, + { asOfDate: '2026-01-15', outDir, persist: true } + ); + + expect(callOrder).toEqual([ + 'assertSafety', + 'createPostgresClient', + 'persistFn', + 'closePostgres', + 'closeMongo', + ]); + expect(capturedInputs).toHaveLength(1); + expect(capturedInputs[0]).toEqual(result.composed.persistInput); + expect(receivedQueryable === fakeQueryable).toBe(true); + expect(result.persistResult).not.toBeNull(); + expect(stdoutChunks.join('')).toContain('Persisted: yes'); + }); + + test('env-safety guard throwing rejects with step name, never opens PostgreSQL, and closes Mongo', async () => { + const fixture = buildUsCaFixture(); + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + const outDir = createTempDir(); + let pgFactoryCalls = 0; + let mongoClosed = 0; + const stdoutChunks: string[] = []; + const safetyErr = new Error('Safety guard: blocked QA PostgreSQL'); + + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => { + throw safetyErr; + }, + createPostgresClient: () => { + pgFactoryCalls += 1; + throw new Error('should not be called'); + }, + writeStdout: text => { + stdoutChunks.push(text); + }, + }, + { asOfDate: '2026-01-15', outDir, persist: true } + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('env-safety'); + expect((caught as Error).cause).toBe(safetyErr); + expect(pgFactoryCalls).toBe(0); + expect(mongoClosed).toBe(1); + expect(stdoutChunks).toHaveLength(0); + }); + + test('assertSecurityMasterPersistSafety rejects QA profile and non-dev PostgreSQL targets before opening PostgreSQL', async () => { + const buildConfig = (overrides: { + environment: 'development' | 'qa'; + host?: string; + port: number; + database: string; + }) => + stockAppSchema.parse({ + name: 'stock-bot', + version: '1.0.0', + environment: overrides.environment, + service: { + name: 'data-pipeline', + port: 2002, + }, + log: { + level: 'info', + }, + database: { + postgres: { + enabled: true, + host: overrides.host ?? 'localhost', + port: overrides.port, + database: overrides.database, + user: 'trading_user', + password: 'dev_password', + }, + mongodb: { + enabled: true, + uri: + overrides.environment === 'qa' + ? 'mongodb://localhost:27017/stock' + : 'mongodb://localhost:27018/stock_dev', + readUri: 'mongodb://studio_stock_bot_read:pass@localhost:27017/stock?authSource=stock', + readOnly: true, + database: overrides.environment === 'qa' ? 'stock' : 'stock_dev', + }, + questdb: { enabled: false }, + dragonfly: { enabled: false }, + }, + providers: {}, + features: {}, + }); + + // 1. QA profile targeting QA PostgreSQL (localhost:5432/trading_bot) must be rejected before PG factory runs + const qaConfig = buildConfig({ + environment: 'qa', + port: 5432, + database: 'trading_bot', + }); + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + let pgFactoryCalls = 0; + let mongoClosed = 0; + const stdoutChunks: string[] = []; + + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => assertSecurityMasterPersistSafety(qaConfig, {}), + createPostgresClient: () => { + pgFactoryCalls += 1; + throw new Error('PostgreSQL factory must not be called for QA profile'); + }, + writeStdout: text => stdoutChunks.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('env-safety'); + expect((caught as Error).message).toContain('NODE_ENV=development'); + expect(pgFactoryCalls).toBe(0); + expect(mongoClosed).toBe(1); + expect(stdoutChunks).toHaveLength(0); + + // 2. Development profile targeting QA PostgreSQL (even with STOCK_BOT_ALLOW_DEV_ON_QA_DB=true) is rejected + const devQaPgConfig = buildConfig({ + environment: 'development', + port: 5432, + database: 'trading_bot', + }); + expect(() => + assertSecurityMasterPersistSafety(devQaPgConfig, { STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true' }) + ).toThrow(/Safety guard: development environment cannot target QA PostgreSQL/); + + // 3. Development profile on port 5433 with non-dev database name is rejected + const devNonDevDbConfig = buildConfig({ + environment: 'development', + port: 5433, + database: 'trading_bot', + }); + expect(() => assertSecurityMasterPersistSafety(devNonDevDbConfig, {})).toThrow( + /cannot target QA PostgreSQL/ + ); + + // 4. Development profile targeting isolated dev PostgreSQL (localhost:5433/trading_bot_dev) passes + const devIsolatedConfig = buildConfig({ + environment: 'development', + port: 5433, + database: 'trading_bot_dev', + }); + expect(() => assertSecurityMasterPersistSafety(devIsolatedConfig, {})).not.toThrow(); + }); + + test('closeMongo failure after successful writes rejects with close-mongo and leaves stdout empty', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const outDir = createTempDir(); + const stdoutChunks: string[] = []; + const closeErr = new Error('Mongo disconnect timed out'); + + let caught: unknown = null; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + throw closeErr; + }, + writeStdout: text => { + stdoutChunks.push(text); + }, + }, + { asOfDate: '2026-01-15', outDir } + ); + } catch (error) { + caught = error; + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toContain('close-mongo'); + expect((caught as Error).cause).toBe(closeErr); + expect(stdoutChunks).toHaveLength(0); + }); + + test('real assertEnvironmentSafety rejects development config targeting QA PostgreSQL 5432/trading_bot', () => { + const devQaPgConfig = stockAppSchema.parse({ + name: 'stock-bot', + version: '1.0.0', + environment: 'development', + service: { + name: 'data-pipeline', + port: 2002, + }, + log: { + level: 'info', + }, + database: { + postgres: { + enabled: true, + host: 'localhost', + port: 5432, + database: 'trading_bot', + user: 'trading_user', + password: 'dev_password', + }, + mongodb: { + enabled: true, + uri: 'mongodb://localhost:27018/stock_dev', + readUri: 'mongodb://studio_stock_bot_read:pass@localhost:27017/stock?authSource=stock', + readOnly: true, + database: 'stock_dev', + }, + questdb: { enabled: false }, + dragonfly: { enabled: false }, + }, + providers: {}, + features: {}, + }); + + expect(() => assertEnvironmentSafety(devQaPgConfig, 'dataPipeline', {})).toThrow( + /Safety guard: development environment cannot target QA PostgreSQL/ + ); + }); + + test('reader, bar-span, file-write, and persist failures wrap step name, suppress summary, and close clients', async () => { + const fixture = buildUsCaFixture(); + + // 1. Reader failure (source symbol collection) + { + const fakeMongo = createStrictReadOnlyFakeMongo(fixture, { failCollection: 'eodSymbols' }); + let mongoClosed = 0; + const stdout: string[] = []; + let caught: unknown; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + } catch (err) { + caught = err; + } + expect((caught as Error).message).toContain('read-sources'); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + } + + // 2. Bar-span failure + { + const fakeMongo = createStrictReadOnlyFakeMongo(fixture, { failAggregate: true }); + let mongoClosed = 0; + const stdout: string[] = []; + let caught: unknown; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + } catch (err) { + caught = err; + } + expect((caught as Error).message).toContain('compute-bar-spans'); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + } + + // 3. File-write failure + secondary closeMongo error does not mask primary error + { + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + let mongoClosed = 0; + const stdout: string[] = []; + const writeErr = new Error('ENOSPC: disk full'); + let caught: unknown; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + throw new Error('secondary disconnect error'); + }, + writeFile: () => { + throw writeErr; + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + } catch (err) { + caught = err; + } + expect((caught as Error).message).toContain('write-files'); + expect((caught as Error).cause).toBe(writeErr); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + } + + // 4. Persist failure closes both PostgreSQL handle and MongoDB client + { + const fakeMongo = createStrictReadOnlyFakeMongo(fixture); + let mongoClosed = 0; + let pgClosed = 0; + const stdout: string[] = []; + const persistErr = new Error('deadlock detected'); + let caught: unknown; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => {}, + createPostgresClient: () => ({ + queryable: { + async query() { + return { rows: [] }; + }, + }, + close: () => { + pgClosed += 1; + }, + }), + persistFn: async () => { + throw persistErr; + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ); + } catch (err) { + caught = err; + } + expect((caught as Error).message).toContain('persist'); + expect((caught as Error).cause).toBe(persistErr); + expect(pgClosed).toBe(1); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + } + }); + + test('rejects non-read-only Mongo client and static source contains zero write/index/drop tokens', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture(), { readOnly: false }); + let mongoClosed = 0; + + let caught: unknown; + try { + await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + } catch (err) { + caught = err; + } + + expect((caught as Error).message).toContain('read-exchanges'); + expect((caught as Error).message).toContain('read-only'); + expect(mongoClosed).toBe(1); + + const sourceText = readFileSync(cliSourcePath, 'utf8'); + const forbiddenPattern = /\b(insert|update|delete|drop|createIndex|bulkWrite)\b/i; + expect(forbiddenPattern.test(sourceText)).toBe(false); + expect(/(insert|update|delete|drop|createIndex|bulkWrite)/i.test(sourceText)).toBe(false); + }); + + test('empty sources succeed, write all four files with zero stats, and skip bar-span aggregates', async () => { + const emptyFixture: FakeMongoFixture = { collections: {} }; + const fakeMongo = createStrictReadOnlyFakeMongo(emptyFixture); + const outDir = createTempDir(); + let mongoClosed = 0; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + + expect(fakeMongo.aggregateCalls).toHaveLength(0); + expect(mongoClosed).toBe(1); + expect(result.composed.stageA.instruments).toHaveLength(0); + expect(result.composed.stageB.listings).toHaveLength(0); + expect(result.composed.report.conflicts).toHaveLength(0); + + for (const filename of Object.values(SECURITY_MASTER_OUTPUT_FILES)) { + const content = readFileSync(join(outDir, filename), 'utf8'); + expect(typeof content).toBe('string'); + } + + const parsedStats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { + barSpans: { totalRowsRead: number; totalSpans: number }; + reportSummary: { instruments: number; listings: number; conflicts: number }; + }; + expect(parsedStats.barSpans.totalRowsRead).toBe(0); + expect(parsedStats.barSpans.totalSpans).toBe(0); + expect(parsedStats.reportSummary.instruments).toBe(0); + expect(parsedStats.reportSummary.listings).toBe(0); + expect(parsedStats.reportSummary.conflicts).toBe(0); + }); +}); + +describe('runSecurityMaster (QA edge cases)', () => { + async function captureRejection(promise: Promise): Promise { + try { + await promise; + } catch (error) { + expect(error).toBeInstanceOf(Error); + return error as Error; + } + throw new Error('expected promise to reject'); + } + + function buildPgConfig(overrides: { + environment?: 'development' | 'qa'; + enabled?: boolean; + port: number; + database: string; + }) { + const environment = overrides.environment ?? 'development'; + return stockAppSchema.parse({ + name: 'stock-bot', + version: '1.0.0', + environment, + service: { name: 'data-pipeline', port: 2002 }, + log: { level: 'info' }, + database: { + postgres: { + enabled: overrides.enabled ?? true, + host: 'localhost', + port: overrides.port, + database: overrides.database, + user: 'trading_user', + password: 'dev_password', + }, + mongodb: { + enabled: true, + uri: 'mongodb://localhost:27018/stock_dev', + readUri: 'mongodb://studio_stock_bot_read:pass@localhost:27017/stock?authSource=stock', + readOnly: true, + database: 'stock_dev', + }, + questdb: { enabled: false }, + dragonfly: { enabled: false }, + }, + providers: {}, + features: {}, + }); + } + + test('failing env-safety guard runs before any MongoDB read', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + let mongoClosed = 0; + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => { + throw new Error('blocked'); + }, + createPostgresClient: () => { + throw new Error('must not be called'); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ) + ); + + expect(error.message).toContain('env-safety'); + expect(fakeMongo.findCalls).toHaveLength(0); + expect(fakeMongo.aggregateCalls).toHaveLength(0); + expect(mongoClosed).toBe(1); + }); + + test('--persist without guard or PostgreSQL factory rejects at env-safety with no reads or writes', async () => { + for (const missing of ['assertSafety', 'createPostgresClient'] as const) { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const writes: string[] = []; + let mongoClosed = 0; + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + ...(missing === 'assertSafety' + ? { + createPostgresClient: () => { + throw new Error('must not be called'); + }, + } + : { assertSafety: () => {} }), + writeFile: filePath => { + writes.push(filePath); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ) + ); + + expect(error.message).toContain('env-safety'); + expect(error.message).toContain(missing); + expect(fakeMongo.findCalls).toHaveLength(0); + expect(writes).toHaveLength(0); + expect(mongoClosed).toBe(1); + } + }); + + test('invalid asOfDate or empty outDir passed programmatically rejects at validate-options before Mongo', async () => { + const cases = [ + { asOfDate: '2023-02-29', outDir: '/tmp/x' }, + { asOfDate: '20260115', outDir: '/tmp/x' }, + { asOfDate: '2026-01-15', outDir: ' ' }, + ]; + for (const options of cases) { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + let mongoClosed = 0; + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: () => {}, + }, + options + ) + ); + expect(error.message).toContain('validate-options'); + expect(fakeMongo.findCalls).toHaveLength(0); + expect(mongoClosed).toBe(1); + } + }); + + test('exchange collection read failure rejects at read-exchanges, writes nothing, closes Mongo', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture(), { + failCollection: 'ibExchanges', + }); + const writes: string[] = []; + const stdout: string[] = []; + let mongoClosed = 0; + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeFile: filePath => { + writes.push(filePath); + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ) + ); + + expect(error.message).toContain('read-exchanges'); + expect((error.cause as Error).message).toContain('ibExchanges'); + expect(writes).toHaveLength(0); + expect(stdout).toHaveLength(0); + expect(mongoClosed).toBe(1); + }); + + test('write failure on a later file never opens PostgreSQL under --persist', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const writes: string[] = []; + let pgFactoryCalls = 0; + let mongoClosed = 0; + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => {}, + createPostgresClient: () => { + pgFactoryCalls += 1; + throw new Error('must not be called'); + }, + writeFile: filePath => { + writes.push(filePath); + if (writes.length === 3) { + throw new Error('EACCES'); + } + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: '/virtual/out', persist: true } + ) + ); + + expect(error.message).toContain('write-files'); + expect(writes).toEqual([ + join('/virtual/out', 'match-report.md'), + join('/virtual/out', 'conflicts.csv'), + join('/virtual/out', 'override-template.sql'), + ]); + expect(pgFactoryCalls).toBe(0); + expect(mongoClosed).toBe(1); + }); + + test('PostgreSQL factory failure rejects at persist after artifacts exist and closes Mongo', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const outDir = createTempDir(); + const stdout: string[] = []; + let mongoClosed = 0; + let persistCalls = 0; + const connectErr = new Error('ECONNREFUSED 127.0.0.1:5433'); + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => {}, + createPostgresClient: async () => { + throw connectErr; + }, + persistFn: async () => { + persistCalls += 1; + return makeFakePersistResult(); + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir, persist: true } + ) + ); + + expect(error.message).toContain('"persist"'); + expect(error.cause).toBe(connectErr); + expect(persistCalls).toBe(0); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + for (const filename of Object.values(SECURITY_MASTER_OUTPUT_FILES)) { + expect(readFileSync(join(outDir, filename), 'utf8').length).toBeGreaterThan(0); + } + }); + + test('PostgreSQL close failure after successful persist rejects and suppresses the summary', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const stdout: string[] = []; + let mongoClosed = 0; + const closeErr = new Error('pool end failed'); + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => {}, + createPostgresClient: () => ({ + queryable: { + async query() { + return { rows: [] }; + }, + }, + close: () => { + throw closeErr; + }, + }), + persistFn: async () => makeFakePersistResult(), + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ) + ); + + expect(error.message).toContain('"persist"'); + expect(error.cause).toBe(closeErr); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + }); + + test('persist failure is not masked by a secondary PostgreSQL close failure', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const persistErr = new Error('unique violation'); + let pgClosed = 0; + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + assertSafety: () => {}, + createPostgresClient: () => ({ + queryable: { + async query() { + return { rows: [] }; + }, + }, + close: () => { + pgClosed += 1; + throw new Error('secondary close error'); + }, + }), + persistFn: async () => { + throw persistErr; + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ) + ); + + expect(error.cause).toBe(persistErr); + expect(pgClosed).toBe(1); + }); + + test('bar spans are targeted to sorted in-scope EOD and QM ids and stats reconcile', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const outDir = createTempDir(); + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + + const requested = new Map( + fakeMongo.aggregateCalls.map(call => [ + call.collectionName, + [...(extractRequestedIdsFromPipeline(call.pipeline) ?? new Set(['']))], + ]) + ); + expect([...requested.keys()].sort()).toEqual(['eodPrices', 'qmPrices']); + expect(requested.get('eodPrices')).toEqual(['AAPL.US', 'SHOP.TO']); + expect(requested.get('qmPrices')).toEqual(['AAPL:US', 'MYSTERY:CA']); + + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { + exchanges: { + countsByCollection: Record; + mapped: number; + unresolved: number; + total: number; + }; + barSpans: { totalSpans: number; totalRowsRead: number }; + reportSummary: { instruments: number; listings: number; conflicts: number }; + }; + expect(stats.exchanges.countsByCollection).toEqual({ ceo: 0, eod: 2, ib: 2, qm: 2 }); + expect(stats.exchanges.total).toBe(stats.exchanges.mapped + stats.exchanges.unresolved); + expect(stats.barSpans.totalSpans).toBe(4); + expect(stats.reportSummary.instruments).toBe(result.composed.stageA.instruments.length); + expect(stats.reportSummary.listings).toBe(result.composed.stageB.listings.length); + expect(stats.reportSummary.conflicts).toBe(result.composed.report.conflicts.length); + expect(result.runStatsJson).toBe( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ); + }); + + test('summary is written exactly once and only after Mongo closes', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const events: string[] = []; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + events.push('closeMongo'); + }, + writeStdout: text => { + events.push(`stdout:${text}`); + }, + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + + expect(events).toEqual(['closeMongo', `stdout:${result.summary}`]); + }); + + test('assertSecurityMasterPersistSafety accepts dev safety DB and rejects disabled or non-dev targets', () => { + expect(() => + assertSecurityMasterPersistSafety( + buildPgConfig({ port: 5433, database: 'stock_bot_safety_qa' }), + {} + ) + ).not.toThrow(); + expect(() => + assertSecurityMasterPersistSafety(buildPgConfig({ port: 5433, database: 'analytics' }), {}) + ).toThrow(/isolated dev PostgreSQL database/); + expect(() => + assertSecurityMasterPersistSafety( + buildPgConfig({ enabled: false, port: 5433, database: 'trading_bot_dev' }), + {} + ) + ).toThrow(/PostgreSQL is disabled/); + expect(() => + assertSecurityMasterPersistSafety( + buildPgConfig({ environment: 'qa', port: 5433, database: 'trading_bot_dev' }), + {} + ) + ).toThrow(/qa environment/); + }); +}); + +describe('run-security-master CLI process', () => { + function runCliProcess(args: readonly string[]) { + const proc = Bun.spawnSync([process.execPath, 'run', cliSourcePath, ...args], { + stdout: 'pipe', + stderr: 'pipe', + env: { PATH: process.env.PATH ?? '', HOME: process.env.HOME ?? '' }, + }); + return { + exitCode: proc.exitCode, + stdout: proc.stdout.toString(), + stderr: proc.stderr.toString(), + }; + } + + test('--help exits 0 and prints usage without connecting to MongoDB', () => { + const result = runCliProcess(['--help']); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain(RUN_SECURITY_MASTER_USAGE); + }); + + test('usage errors exit non-zero with an Error line on stderr and no success summary', () => { + for (const args of [ + ['--as-of', '2026-02-30', '--out-dir', 'x'], + ['--bogus'], + ['--out-dir', 'x'], + ]) { + const result = runCliProcess(args); + expect(result.exitCode).toBe(1); + expect(result.stderr.startsWith('Error: ')).toBe(true); + expect(result.stdout).not.toContain('Security master run complete'); + } + }); +}); diff --git a/test/unit/security-master-run-qa.test.ts b/test/unit/security-master-run-qa.test.ts new file mode 100644 index 00000000..e575e783 --- /dev/null +++ b/test/unit/security-master-run-qa.test.ts @@ -0,0 +1,481 @@ +import { describe, expect, test } from 'bun:test'; +import { + BarSpanIndex, + type BarSpan, + type ComputeBarSpansResult, +} from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; +import { + classifySourceExchanges, + composeSecurityMasterRun, + type ComposeSecurityMasterRunInput, + type ComposeSecurityMasterRunResult, + type FxRateByDateRecord, + type SampleCloseRecord, + type SecurityMasterSourcesResult, + type SecurityType, + type StageASourceRecord, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBTickerSourceInput, +} from '../../apps/stock/data-pipeline/src/security-master'; + +// QA edge cases for composeSecurityMasterRun (T-88): input immutability, repeat-call purity, +// bar-span input-shape equivalence, empty-vs-omitted Pass 4, out-of-window Pass 4 closes, +// multi-seed shuffle determinism, and duplicate source records. In-memory only. + +const AS_OF = '2025-11-28'; + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function shuffle(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rng = makeRng(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const tmp = copy[i] as T; + copy[i] = copy[j] as T; + copy[j] = tmp; + } + return copy; +} + +function emptyCollectionStats( + collection: 'eodSymbols' | 'ibSymbols' | 'qmSymbols' | 'ceoSymbols' | 'eodSymbolChange' +) { + return { + collection, + docsRead: 0, + emitted: 0, + invalidIdentifiersNulled: 0, + skips: { + missingId: 0, + invalidFieldType: 0, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 0, + outOfScopeCountry: 0, + }, + }; +} + +function makeSources(p: { + stageARecords: StageASourceRecord[]; + eodListings: StageBEodListingInput[]; + ibContracts: StageBIbContractInput[]; + tickerSources: StageBTickerSourceInput[]; + securityTypeByIsin: Map; +}): SecurityMasterSourcesResult { + const typeStats = { + totalRecords: 0, + mapped: 0, + missingType: 0, + unknownType: 0, + invalidIsin: 0, + isinsResolved: p.securityTypeByIsin.size, + isinsConflicting: 0, + conflictsTruncated: 0, + }; + return { + stageARecords: p.stageARecords, + stageBInput: { + eodListings: p.eodListings, + ibContracts: p.ibContracts, + tickerSources: p.tickerSources, + symbolChanges: [], + }, + securityTypeRecords: [], + securityTypeByIsin: p.securityTypeByIsin, + securityTypeStats: typeStats, + securityTypeLoaderStats: { ...typeStats }, + unknownSecurityTypes: [], + securityTypeConflicts: [], + stats: { + eodSymbols: emptyCollectionStats('eodSymbols'), + ibSymbols: emptyCollectionStats('ibSymbols'), + qmSymbols: emptyCollectionStats('qmSymbols'), + ceoSymbols: emptyCollectionStats('ceoSymbols'), + eodSymbolChange: emptyCollectionStats('eodSymbolChange'), + }, + }; +} + +interface Fixture { + stageARecords: StageASourceRecord[]; + eodListings: StageBEodListingInput[]; + ibContracts: StageBIbContractInput[]; + tickerSources: StageBTickerSourceInput[]; + securityTypeByIsin: Map; + barSpans: BarSpan[]; + sampleCloses: SampleCloseRecord[]; + fxRates: FxRateByDateRecord[]; +} + +function buildFixture(): Fixture { + const rec = ( + source: 'eod' | 'ib', + sourceId: string, + isin: string, + cusip: string, + country: string, + currency: string, + name: string + ): StageASourceRecord => ({ source, sourceId, isin, cusip, country, currency, name }); + + const stageARecords: StageASourceRecord[] = [ + rec('ib', '265598', 'US0378331005', '037833100', 'US', 'USD', 'Apple Inc.'), + rec('eod', 'AAPL.US', 'US0378331005', '037833100', 'US', 'USD', 'Apple Inc'), + rec('eod', 'FB_OLD.US', 'US30303M1027', '30303M102', 'US', 'USD', 'Meta Platforms Inc'), + rec('eod', 'FB_ETF.US', 'US4642872000', '464287200', 'US', 'USD', 'FB Thematic ETF'), + rec('eod', 'SIVB.US', 'US78486Q1013', '78486Q101', 'US', 'USD', 'SVB Financial Group'), + rec('eod', 'SIVBQ.US', 'US78486Q1013', '78486Q101', 'US', 'USD', 'SVB Financial Group'), + rec('eod', 'SHOP.TO', 'CA82509L1076', '82509L107', 'CA', 'CAD', 'Shopify Inc.'), + rec('eod', 'SHOP.US', 'CA82509L1076', '82509L107', 'CA', 'USD', 'Shopify Inc.'), + rec('ib', '2001', 'CA82509L1076', '82509L107', 'CA', 'CAD', 'Shopify Inc.'), + rec('ib', '2002', 'CA82509L1076', '82509L107', 'CA', 'USD', 'Shopify Inc.'), + ]; + + const eod = (sourceId: string, ticker: string, mic: string, currency: string): StageBEodListingInput => ({ + sourceId, + ticker, + mic, + role: 'primary_venue', + currency, + span: null, + }); + const eodListings: StageBEodListingInput[] = [ + eod('AAPL.US', 'AAPL', 'XNAS', 'USD'), + eod('FB_OLD.US', 'FB', 'XNAS', 'USD'), + eod('FB_ETF.US', 'FB', 'XNAS', 'USD'), + eod('SIVB.US', 'SIVB', 'XNAS', 'USD'), + eod('SIVBQ.US', 'SIVBQ', 'OTCM', 'USD'), + eod('SHOP.TO', 'SHOP', 'XTSE', 'CAD'), + eod('SHOP.US', 'SHOP', 'XNYS', 'USD'), + ]; + + const ibContracts: StageBIbContractInput[] = [ + { sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: '2001', conid: 2001, currency: 'CAD', primaryExchange: 'TSE' }, + { sourceId: '2002', conid: 2002, currency: 'USD', primaryExchange: 'NYSE' }, + ]; + + const tickerSources: StageBTickerSourceInput[] = [ + { source: 'qm', sourceId: 'AAPL:US', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { source: 'qm', sourceId: 'FB_OLD:US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { source: 'qm', sourceId: 'FB_ETF:US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { source: 'qm', sourceId: 'SHOP:CA', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue', currency: 'CAD', span: null }, + { + source: 'ceo', + sourceId: 'ceo:SHOP', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-11-28' }, + }, + ]; + + const span = ( + source: 'eod' | 'qm', + sourceId: string, + firstBarDate: string, + lastBarDate: string, + barCount: number + ): BarSpan => ({ source, sourceId, firstBarDate, lastBarDate, barCount }); + const barSpans: BarSpan[] = [ + span('eod', 'AAPL.US', '2010-01-04', '2025-11-28', 4000), + span('eod', 'FB_OLD.US', '2012-05-18', '2022-06-08', 2530), + span('eod', 'FB_ETF.US', '2025-01-02', '2025-11-28', 230), + span('eod', 'SIVB.US', '2015-01-02', '2023-03-10', 2060), + span('eod', 'SIVBQ.US', '2023-03-28', '2024-11-07', 410), + span('eod', 'SHOP.TO', '2015-05-21', '2025-11-28', 2650), + span('eod', 'SHOP.US', '2015-05-21', '2025-11-28', 2650), + span('qm', 'AAPL:US', '2015-01-02', '2025-11-28', 2700), + span('qm', 'FB_OLD:US', '2014-01-02', '2022-06-08', 2100), + span('qm', 'FB_ETF:US', '2025-02-03', '2025-11-28', 205), + span('qm', 'SHOP:CA', '2018-01-02', '2025-11-28', 1980), + ]; + + const securityTypeByIsin = new Map([ + ['US0378331005', 'common'], + ['US30303M1027', 'common'], + ['US4642872000', 'etf'], + ['US78486Q1013', 'common'], + ['CA82509L1076', 'common'], + ]); + + const dates = ['2025-01-02', '2025-01-03', '2025-01-06', '2025-01-07', '2025-01-08', '2025-01-09']; + const aapl = [185.0, 188.5, 184.2, 191.0, 195.4, 193.1]; + const shop = [140.0, 145.0, 138.0, 148.5, 152.0, 149.0]; + const sampleCloses: SampleCloseRecord[] = []; + const fxRates: FxRateByDateRecord[] = []; + dates.forEach((date, i) => { + fxRates.push({ date, usdCad: 1.38 + i * 0.005 }); + sampleCloses.push({ source: 'eod', sourceId: 'AAPL.US', date, close: aapl[i]! }); + sampleCloses.push({ source: 'qm', sourceId: 'AAPL:US', date, close: aapl[i]! * 1.001 }); + sampleCloses.push({ source: 'eod', sourceId: 'SHOP.TO', date, close: shop[i]! }); + sampleCloses.push({ source: 'qm', sourceId: 'SHOP:CA', date, close: shop[i]! * 1.5 }); + }); + + return { + stageARecords, + eodListings, + ibContracts, + tickerSources, + securityTypeByIsin, + barSpans, + sampleCloses, + fxRates, + }; +} + +const EXCHANGES = classifySourceExchanges([ + { source: 'eod', sourceCode: 'NASDAQ', name: 'NASDAQ', country: 'US', operatingMic: 'XNAS' }, + { source: 'eod', sourceCode: 'NYSE', name: 'NYSE', country: 'US', operatingMic: 'XNYS' }, + { source: 'eod', sourceCode: 'TO', name: 'TSX', country: 'CA', operatingMic: 'XTSE' }, + { source: 'eod', sourceCode: 'OTC', name: 'OTC', country: 'US', operatingMic: 'OTCM' }, +]); + +function toInput(f: Fixture, withPass4: boolean): ComposeSecurityMasterRunInput { + return { + sources: makeSources(f), + barSpans: f.barSpans, + exchanges: EXCHANGES, + ...(withPass4 ? { sampleCloses: f.sampleCloses, fxRates: f.fxRates } : {}), + }; +} + +function deepFreeze(value: T): T { + if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) { + if (!(value instanceof Map) && !(value instanceof BarSpanIndex)) { + Object.freeze(value); + } + for (const v of Object.values(value as Record)) { + deepFreeze(v); + } + } + return value; +} + +function expectSameOutputs( + a: ComposeSecurityMasterRunResult, + b: ComposeSecurityMasterRunResult +): void { + expect(b.reportMarkdown).toBe(a.reportMarkdown); + expect(b.conflictsCsv).toBe(a.conflictsCsv); + expect(b.overrideTemplateSql).toBe(a.overrideTemplateSql); + expect(b.persistInput).toEqual(a.persistInput); + expect(Array.from(b.persistInput.securityTypeByIsin.entries())).toEqual( + Array.from(a.persistInput.securityTypeByIsin.entries()) + ); +} + +describe('composeSecurityMasterRun QA edge cases', () => { + test('does not mutate any input (deep-frozen arrays/records, Map unchanged) and does not alias securityTypeByIsin', () => { + const f = buildFixture(); + const input = toInput(f, true); + const before = JSON.stringify({ + a: f.stageARecords, + e: f.eodListings, + i: f.ibContracts, + t: f.tickerSources, + b: f.barSpans, + s: f.sampleCloses, + x: f.fxRates, + m: Array.from(f.securityTypeByIsin.entries()), + }); + deepFreeze(input); + + const result = composeSecurityMasterRun(input, { asOfDate: AS_OF }); + + const after = JSON.stringify({ + a: f.stageARecords, + e: f.eodListings, + i: f.ibContracts, + t: f.tickerSources, + b: f.barSpans, + s: f.sampleCloses, + x: f.fxRates, + m: Array.from(f.securityTypeByIsin.entries()), + }); + expect(after).toBe(before); + // Spans were attached to clones, not to the caller's listings. + expect(f.eodListings.every(l => l.span === null)).toBe(true); + expect(result.persistInput.securityTypeByIsin).not.toBe(f.securityTypeByIsin); + expect(result.stats.barSpans.attachedEodListings).toBe(7); + }); + + test('repeated calls on the same input are deep-equal (no hidden state between runs)', () => { + const f = buildFixture(); + const first = composeSecurityMasterRun(toInput(f, true), { asOfDate: AS_OF }); + const second = composeSecurityMasterRun(toInput(f, true), { asOfDate: AS_OF }); + expectSameOutputs(first, second); + expect(second.stats).toEqual(first.stats); + }); + + test('BarSpan[], BarSpanIndex and ComputeBarSpansResult carrying the same spans compose identical reports and persist input', () => { + const f = buildFixture(); + const index = new BarSpanIndex(); + for (const s of f.barSpans) { + index.merge(s); + } + const computed: ComputeBarSpansResult = { + index, + bySource: {}, + skipped: { invalidId: 0, invalidDate: 0, invalidCount: 0, total: 0 }, + totalRowsRead: f.barSpans.length, + totalSpans: index.size, + }; + + const fromArray = composeSecurityMasterRun(toInput(f, true), { asOfDate: AS_OF }); + const fromIndex = composeSecurityMasterRun( + { ...toInput(f, true), barSpans: index }, + { asOfDate: AS_OF } + ); + const fromComputed = composeSecurityMasterRun( + { ...toInput(f, true), barSpans: computed }, + { asOfDate: AS_OF } + ); + + expectSameOutputs(fromArray, fromIndex); + expectSameOutputs(fromArray, fromComputed); + for (const r of [fromArray, fromIndex, fromComputed]) { + expect(r.stats.barSpans.recordsIn).toBe(11); + expect(r.stats.barSpans.resolved).toBe(11); + expect(r.stats.barSpans.skipped).toBe(0); + expect(r.stats.barSpans.indexedSpans).toBe(11); + } + }); + + test('an empty sampleCloses array is treated exactly like omitted sampleCloses (Pass 4 skipped, never passed)', () => { + const f = buildFixture(); + const omitted = composeSecurityMasterRun(toInput(f, false), { asOfDate: AS_OF }); + const empty = composeSecurityMasterRun( + { ...toInput(f, false), sampleCloses: [], fxRates: f.fxRates }, + { asOfDate: AS_OF } + ); + + expectSameOutputs(omitted, empty); + expect(empty.pass4).toBeNull(); + expect(empty.persistInput.pass4).toBeUndefined(); + expect('pass4' in empty.persistInput).toBe(false); + expect(empty.stats.pass4.status).toBe('skipped'); + expect(empty.stats.pass4.resolved).toBe(0); + expect(empty.stats.pass4.conflicts).toBe(0); + expect(empty.reportMarkdown).toContain('- Status: skipped (no sample closes supplied)'); + expect(empty.conflictsCsv).not.toContain('price_ratio_mismatch'); + }); + + test('sample closes only for series with no provider mapping execute Pass 4 with zero confirmations and zero conflicts', () => { + const f = buildFixture(); + const dates = ['2025-01-02', '2025-01-03', '2025-01-06', '2025-01-07', '2025-01-08', '2025-01-09']; + const closes: SampleCloseRecord[] = []; + dates.forEach((date, i) => { + closes.push({ source: 'eod', sourceId: 'UNMAPPED.US', date, close: 100 + i }); + closes.push({ source: 'qm', sourceId: 'UNMAPPED:US', date, close: (100 + i) * 3 }); + }); + + const result = composeSecurityMasterRun( + { ...toInput(f, false), sampleCloses: closes, fxRates: f.fxRates }, + { asOfDate: AS_OF } + ); + + // Executed (closes were supplied) but nothing may pass or be disputed without usable data. + expect(result.stats.pass4.status).toBe('executed'); + expect(result.pass4).not.toBeNull(); + expect(result.pass4!.stats.pairsIn).toBe(result.pass4CandidatePairs.length); + expect(result.pass4CandidatePairs.length).toBeGreaterThan(0); + expect(result.pass4!.results.every(r => r.verdict !== 'confirmed')).toBe(true); + expect(result.pass4!.conflicts).toEqual([]); + expect(result.stats.pass4.resolved).toBe(0); + expect(result.stats.conflicts.pass4).toBe(0); + const s = result.stats.pass4; + expect(s.recordsIn).toBe(s.resolved + s.unresolved + s.skipped); + expect(result.persistInput.pass4).toBe(result.pass4!); + expect(result.reportMarkdown).not.toContain('Status: skipped'); + }); + + test('determinism holds across several independent shuffle seeds, including exchange classification input order', () => { + const f = buildFixture(); + const baseline = composeSecurityMasterRun(toInput(f, true), { asOfDate: AS_OF }); + const exchangeRows = [ + { source: 'eod' as const, sourceCode: 'NASDAQ', name: 'NASDAQ', country: 'US', operatingMic: 'XNAS' }, + { source: 'eod' as const, sourceCode: 'NYSE', name: 'NYSE', country: 'US', operatingMic: 'XNYS' }, + { source: 'eod' as const, sourceCode: 'TO', name: 'TSX', country: 'CA', operatingMic: 'XTSE' }, + { source: 'eod' as const, sourceCode: 'OTC', name: 'OTC', country: 'US', operatingMic: 'OTCM' }, + ]; + + for (const seed of [1, 2, 3, 1234, 987654]) { + const shuffled: Fixture = { + stageARecords: shuffle(f.stageARecords, seed), + eodListings: shuffle(f.eodListings, seed + 1), + ibContracts: shuffle(f.ibContracts, seed + 2), + tickerSources: shuffle(f.tickerSources, seed + 3), + securityTypeByIsin: new Map(shuffle(Array.from(f.securityTypeByIsin.entries()), seed + 4)), + barSpans: shuffle(f.barSpans, seed + 5), + sampleCloses: shuffle(f.sampleCloses, seed + 6), + fxRates: shuffle(f.fxRates, seed + 7), + }; + const run = composeSecurityMasterRun( + { + ...toInput(shuffled, true), + exchanges: classifySourceExchanges(shuffle(exchangeRows, seed + 8)), + }, + { asOfDate: AS_OF } + ); + expectSameOutputs(baseline, run); + expect(run.stats).toEqual(baseline.stats); + } + }); + + test('a duplicated Stage A source record is quarantined (duplicate_source_id) and carried into report, CSV and persist input without throwing or breaking other listings', () => { + const f = buildFixture(); + const fbOld = f.stageARecords.find(r => r.sourceId === 'FB_OLD.US')!; + const dup: Fixture = { ...f, stageARecords: [...f.stageARecords, { ...fbOld }] }; + + const result = composeSecurityMasterRun(toInput(dup, true), { asOfDate: AS_OF }); + + for (const step of [ + result.stats.barSpans, + result.stats.stageA, + result.stats.stageB, + result.stats.pass6, + result.stats.pass4, + ]) { + expect(step.recordsIn).toBe(step.resolved + step.unresolved + step.skipped); + } + expect(result.stats.stageA.recordsIn).toBe(11); + const c = result.stats.conflicts; + expect(c.total).toBe(c.stageA + c.stageB + c.pass4 + c.pass6); + expect(result.report.conflicts.length).toBe(c.total); + + const dupConflicts = result.stageA.conflicts.filter( + x => x.sourceId === 'FB_OLD.US' && x.conflictKind === 'duplicate_source_id' + ); + expect(dupConflicts.length).toBeGreaterThan(0); + expect(result.persistInput.stageA.conflicts).toEqual(result.stageA.conflicts); + expect(result.conflictsCsv).toContain('duplicate_source_id'); + expect(result.conflictsCsv).toContain('FB_OLD.US'); + + // The quarantined issuer gets no listing; the FB ETF, SIVB chain and Pass 4 are unaffected. + const fbListings = result.persistInput.stageB.listings.filter(l => l.tickerRoot === 'FB'); + expect(fbListings.map(l => l.primaryIsin)).toEqual(['US4642872000']); + const sivbTransfers = result.pass6.continuities.filter( + x => x.fromListingKey.tickerRoot === 'SIVB' && x.toListingKey.tickerRoot === 'SIVBQ' + ); + expect(sivbTransfers.length).toBe(1); + expect(result.pass4!.conflicts.some(x => x.conflictKind === 'price_ratio_mismatch')).toBe(true); + // A record lost to quarantine must not be reported as 100% resolved. + const eodRow = result.report.resolutionBySource.find(r => r.source === 'eod')!; + expect(eodRow.eligibleResolvedPct).not.toBeNull(); + expect(eodRow.eligibleResolvedPct!).toBeLessThan(1); + }); +}); diff --git a/test/unit/security-master-run.test.ts b/test/unit/security-master-run.test.ts new file mode 100644 index 00000000..ff6ebfd0 --- /dev/null +++ b/test/unit/security-master-run.test.ts @@ -0,0 +1,1580 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { + BarSpanIndex, + type BarSpan, + type ComputeBarSpansResult, +} from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; +import { cusipToIsin } from '../../apps/stock/data-pipeline/src/normalization/identifiers'; +import { + attachBarSpansToStageBInput, + classifySourceExchanges, + composeSecurityMasterRun, + CONTINUITY_KIND_OTC_DELIST_TRANSFER, + derivePass4CandidatePairs, + deriveSourceCountries, + filterSampleClosesByMappingBounds, + formatListingNaturalKey, + type ComposeSecurityMasterRunInput, + type FxRateByDateRecord, + type SampleCloseRecord, + type SecurityMasterSourcesResult, + type SecurityMasterStageBSourceInput, + type SecurityType, + type StageASourceRecord, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBSymbolChangeInput, + type StageBTickerSourceInput, +} from '../../apps/stock/data-pipeline/src/security-master'; + +const runSourcePath = fileURLToPath( + new URL('../../apps/stock/data-pipeline/src/security-master/run.ts', import.meta.url) +); + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function shuffleWithSeed(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rng = makeRng(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const a = copy[i]; + const b = copy[j]; + if (a !== undefined && b !== undefined) { + copy[i] = b; + copy[j] = a; + } + } + return copy; +} + +function makeEmptyCollectionStats( + collection: 'eodSymbols' | 'ibSymbols' | 'qmSymbols' | 'ceoSymbols' | 'eodSymbolChange' +) { + return { + collection, + docsRead: 0, + emitted: 0, + invalidIdentifiersNulled: 0, + skips: { + missingId: 0, + invalidFieldType: 0, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 0, + outOfScopeCountry: 0, + }, + }; +} + +function makeSourcesResult(params: { + stageARecords: StageASourceRecord[]; + eodListings: StageBEodListingInput[]; + ibContracts: StageBIbContractInput[]; + tickerSources: StageBTickerSourceInput[]; + symbolChanges?: StageBSymbolChangeInput[]; + securityTypeByIsin: Map; +}): SecurityMasterSourcesResult { + return { + stageARecords: params.stageARecords, + stageBInput: { + eodListings: params.eodListings, + ibContracts: params.ibContracts, + tickerSources: params.tickerSources, + symbolChanges: params.symbolChanges ?? [], + }, + securityTypeRecords: [], + securityTypeByIsin: params.securityTypeByIsin, + securityTypeStats: { + totalRecords: 0, + mapped: 0, + missingType: 0, + unknownType: 0, + invalidIsin: 0, + isinsResolved: params.securityTypeByIsin.size, + isinsConflicting: 0, + conflictsTruncated: 0, + }, + securityTypeLoaderStats: { + totalRecords: 0, + mapped: 0, + missingType: 0, + unknownType: 0, + invalidIsin: 0, + isinsResolved: params.securityTypeByIsin.size, + isinsConflicting: 0, + conflictsTruncated: 0, + }, + unknownSecurityTypes: [], + securityTypeConflicts: [], + stats: { + eodSymbols: makeEmptyCollectionStats('eodSymbols'), + ibSymbols: makeEmptyCollectionStats('ibSymbols'), + qmSymbols: makeEmptyCollectionStats('qmSymbols'), + ceoSymbols: makeEmptyCollectionStats('ceoSymbols'), + eodSymbolChange: makeEmptyCollectionStats('eodSymbolChange'), + }, + }; +} + +/** + * Canonical M1 exit-criterion fixture: + * - AAPL (`US0378331005`): EOD + IB + QM on XNAS (USD) + * - FB common (`US30303M1027`, 2012-2022) vs FB ETF (`US4642872000`, 2025) on XNAS (USD) + * - SIVB (`US78486Q1013`) XNAS (2015..2023-03-10) -> SIVBQ OTCM (2023-03-28..2024-11-07) + * - SHOP (`CA82509L1076`) interlisted XTSE (CAD) + XNYS (USD) with IB contracts in CAD & USD + */ +function buildCanonicalFixture(): { + input: ComposeSecurityMasterRunInput; + sampleCloses: SampleCloseRecord[]; + fxRates: FxRateByDateRecord[]; +} { + const stageARecords: StageASourceRecord[] = [ + { + source: 'ib', + sourceId: '265598', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + { + source: 'eod', + sourceId: 'AAPL.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc', + }, + { + source: 'eod', + sourceId: 'FB_OLD.US', + isin: 'US30303M1027', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: 'Meta Platforms Inc', + }, + { + source: 'eod', + sourceId: 'FB_ETF.US', + isin: 'US4642872000', + cusip: '464287200', + country: 'US', + currency: 'USD', + name: 'FB Thematic ETF', + }, + { + source: 'eod', + sourceId: 'SIVB.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SIVBQ.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SHOP.TO', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'CAD', + name: 'Shopify Inc.', + }, + { + source: 'eod', + sourceId: 'SHOP.US', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'USD', + name: 'Shopify Inc.', + }, + { + source: 'ib', + sourceId: '2001', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'CAD', + name: 'Shopify Inc.', + }, + { + source: 'ib', + sourceId: '2002', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'USD', + name: 'Shopify Inc.', + }, + ]; + + // Spans start as null on EOD/QM to verify attachBarSpansToStageBInput wires them from barSpans. + const eodListings: StageBEodListingInput[] = [ + { + sourceId: 'AAPL.US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'FB_OLD.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'FB_ETF.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'SIVB.US', + ticker: 'SIVB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'SIVBQ.US', + ticker: 'SIVBQ', + mic: 'OTCM', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'SHOP.TO', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: null, + }, + { + sourceId: 'SHOP.US', + ticker: 'SHOP', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + ]; + + const ibContracts: StageBIbContractInput[] = [ + { sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: '2001', conid: 2001, currency: 'CAD', primaryExchange: 'TSE' }, + { sourceId: '2002', conid: 2002, currency: 'USD', primaryExchange: 'NYSE' }, + ]; + + const tickerSources: StageBTickerSourceInput[] = [ + { + source: 'qm', + sourceId: 'AAPL:US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + source: 'qm', + sourceId: 'FB_OLD:US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + source: 'qm', + sourceId: 'FB_ETF:US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + source: 'qm', + sourceId: 'SHOP:CA', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: null, + }, + { + source: 'ceo', + sourceId: 'ceo:SHOP', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-11-28' }, + }, + ]; + + const barSpans: BarSpan[] = [ + { source: 'eod', sourceId: 'AAPL.US', firstBarDate: '2010-01-04', lastBarDate: '2025-11-28', barCount: 4000 }, + { source: 'eod', sourceId: 'FB_OLD.US', firstBarDate: '2012-05-18', lastBarDate: '2022-06-08', barCount: 2530 }, + { source: 'eod', sourceId: 'FB_ETF.US', firstBarDate: '2025-01-02', lastBarDate: '2025-11-28', barCount: 230 }, + { source: 'eod', sourceId: 'SIVB.US', firstBarDate: '2015-01-02', lastBarDate: '2023-03-10', barCount: 2060 }, + { source: 'eod', sourceId: 'SIVBQ.US', firstBarDate: '2023-03-28', lastBarDate: '2024-11-07', barCount: 410 }, + { source: 'eod', sourceId: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 }, + { source: 'eod', sourceId: 'SHOP.US', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 }, + { source: 'qm', sourceId: 'AAPL:US', firstBarDate: '2015-01-02', lastBarDate: '2025-11-28', barCount: 2700 }, + { source: 'qm', sourceId: 'FB_OLD:US', firstBarDate: '2014-01-02', lastBarDate: '2022-06-08', barCount: 2100 }, + { source: 'qm', sourceId: 'FB_ETF:US', firstBarDate: '2025-02-03', lastBarDate: '2025-11-28', barCount: 205 }, + { source: 'qm', sourceId: 'SHOP:CA', firstBarDate: '2018-01-02', lastBarDate: '2025-11-28', barCount: 1980 }, + ]; + + const securityTypeByIsin = new Map([ + ['US0378331005', 'common'], + ['US30303M1027', 'common'], + ['US4642872000', 'etf'], + ['US78486Q1013', 'common'], + ['CA82509L1076', 'common'], + ]); + + const exchanges = classifySourceExchanges([ + { source: 'eod', sourceCode: 'NASDAQ', name: 'NASDAQ', country: 'US', operatingMic: 'XNAS' }, + { source: 'eod', sourceCode: 'NYSE', name: 'NYSE', country: 'US', operatingMic: 'XNYS' }, + { source: 'eod', sourceCode: 'TO', name: 'TSX', country: 'CA', operatingMic: 'XTSE' }, + { source: 'eod', sourceCode: 'OTC', name: 'OTC', country: 'US', operatingMic: 'OTCM' }, + ]); + + const dates = [ + '2025-01-02', + '2025-01-03', + '2025-01-06', + '2025-01-07', + '2025-01-08', + '2025-01-09', + ]; + const aaplPrices = [185.0, 188.5, 184.2, 191.0, 195.4, 193.1]; + const shopCadPrices = [140.0, 145.0, 138.0, 148.5, 152.0, 149.0]; + + const sampleCloses: SampleCloseRecord[] = []; + const fxRates: FxRateByDateRecord[] = []; + for (let i = 0; i < dates.length; i++) { + const date = dates[i]!; + const aapl = aaplPrices[i]!; + const shop = shopCadPrices[i]!; + fxRates.push({ date, usdCad: 1.38 + i * 0.005 }); + // AAPL: eod vs qm matching closes -> confirmed + sampleCloses.push({ source: 'eod', sourceId: 'AAPL.US', date, close: aapl }); + sampleCloses.push({ source: 'qm', sourceId: 'AAPL:US', date, close: aapl * 1.001 }); + // SHOP.TO: eod vs qm deliberately 1.5x ratio mismatch -> price_ratio_mismatch + sampleCloses.push({ source: 'eod', sourceId: 'SHOP.TO', date, close: shop }); + sampleCloses.push({ source: 'qm', sourceId: 'SHOP:CA', date, close: shop * 1.5 }); + // ceo:SHOP also mismatches eod SHOP.TO (2.0x) to exercise two mismatches sharing a left endpoint + sampleCloses.push({ source: 'ceo', sourceId: 'ceo:SHOP', date, close: shop * 2.0 }); + } + + const input: ComposeSecurityMasterRunInput = { + sources: makeSourcesResult({ + stageARecords, + eodListings, + ibContracts, + tickerSources, + securityTypeByIsin, + }), + barSpans, + exchanges, + }; + + return { input, sampleCloses, fxRates }; +} + +describe('security-master run composer purity & exports', () => { + test('contains zero I/O imports and zero wall-clock calls', () => { + const src = readFileSync(runSourcePath, 'utf8'); + expect(src).not.toMatch(/\bfrom\s+['"](node:)?(fs|net|http|https|pg|mongodb)['"]/); + expect(src).not.toMatch(/\bfrom\s+['"]@stock-bot\/(mongodb|postgres)['"]/); + expect(src).not.toMatch(/\bDate\.now\b/); + expect(src).not.toMatch(/\bnew\s+Date\b/); + expect(src).not.toMatch(/\bperformance\.now\b/); + + expect(typeof composeSecurityMasterRun).toBe('function'); + expect(typeof attachBarSpansToStageBInput).toBe('function'); + expect(typeof derivePass4CandidatePairs).toBe('function'); + expect(typeof deriveSourceCountries).toBe('function'); + }); +}); + +describe('security-master run composer adapter helpers', () => { + test('attachBarSpansToStageBInput supports BarSpan[], BarSpanIndex, ComputeBarSpansResult, merges duplicates, preserves CEO spans, and skips malformed entries', () => { + const baseStageB: SecurityMasterStageBSourceInput = { + eodListings: [ + { sourceId: 'A.US', ticker: 'A', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { + sourceId: 'B.US', + ticker: 'B', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2020-12-31' }, + }, + ], + ibContracts: [{ sourceId: '101', conid: 101, currency: 'USD', primaryExchange: 'NASDAQ' }], + tickerSources: [ + { source: 'qm', sourceId: 'A:US', ticker: 'A', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { + source: 'ceo', + sourceId: 'ceo:A', + ticker: 'A', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2021-01-04', lastBarDate: '2024-12-31' }, + }, + ], + symbolChanges: [], + }; + + const barSpansArray: BarSpan[] = [ + { source: 'eod', sourceId: 'A.US', firstBarDate: '2018-01-02', lastBarDate: '2022-12-30', barCount: 1000 }, + { source: 'eod', sourceId: 'A.US', firstBarDate: '2016-01-04', lastBarDate: '2024-12-31', barCount: 500 }, + { source: 'qm', sourceId: 'A:US', firstBarDate: '2019-01-02', lastBarDate: '2024-12-31', barCount: 1500 }, + // Malformed entry (inverted dates) + { source: 'eod', sourceId: 'BAD.US', firstBarDate: '2025-01-02', lastBarDate: '2024-01-02', barCount: 10 }, + ]; + + const fromArray = attachBarSpansToStageBInput(baseStageB, barSpansArray); + expect(fromArray.stats.recordsIn).toBe(4); + expect(fromArray.stats.resolved).toBe(3); + expect(fromArray.stats.skipped).toBe(1); + expect(fromArray.stats.attachedEodListings).toBe(1); + expect(fromArray.stats.attachedQmTickerSources).toBe(1); + // Merged min/max span for A.US + expect(fromArray.stageBInput.eodListings[0]?.span).toEqual({ + firstBarDate: '2016-01-04', + lastBarDate: '2024-12-31', + }); + // Existing span on B.US preserved when absent from barSpans + expect(fromArray.stageBInput.eodListings[1]?.span).toEqual({ + firstBarDate: '2020-01-02', + lastBarDate: '2020-12-31', + }); + // QM span attached, CEO span preserved + expect(fromArray.stageBInput.tickerSources[0]?.span).toEqual({ + firstBarDate: '2019-01-02', + lastBarDate: '2024-12-31', + }); + expect(fromArray.stageBInput.tickerSources[1]?.span).toEqual({ + firstBarDate: '2021-01-04', + lastBarDate: '2024-12-31', + }); + // Original input not mutated + expect(baseStageB.eodListings[0]?.span).toBeNull(); + + // BarSpanIndex and ComputeBarSpansResult inputs produce identical spans + const index = new BarSpanIndex(); + index.merge(barSpansArray[0]!); + index.merge(barSpansArray[1]!); + index.merge(barSpansArray[2]!); + + const fromIndex = attachBarSpansToStageBInput(baseStageB, index); + expect(fromIndex.stageBInput).toEqual(fromArray.stageBInput); + + const computeResult: ComputeBarSpansResult = { + index, + bySource: {}, + skipped: { invalidId: 0, invalidDate: 0, invalidCount: 0, total: 0 }, + totalRowsRead: 3, + totalSpans: index.size, + }; + const fromComputeResult = attachBarSpansToStageBInput(baseStageB, computeResult); + expect(fromComputeResult.stageBInput).toEqual(fromArray.stageBInput); + }); + + test('derivePass4CandidatePairs emits deduplicated ASCII-sorted cross-source pairs per listing', () => { + const key = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const mappings = [ + { source: 'qm' as const, sourceId: 'AAPL:US', listingKey: key, method: 'tier3_ticker_span' as const, validFrom: null, validTo: null }, + { source: 'eod' as const, sourceId: 'AAPL.US', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null }, + { source: 'eod' as const, sourceId: 'AAPL_DUP.US', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null }, + { source: 'ib' as const, sourceId: '265598', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null }, + ]; + + const pairsA = derivePass4CandidatePairs(mappings); + const pairsB = derivePass4CandidatePairs([...mappings].reverse()); + expect(pairsA).toEqual(pairsB); + // Same-source pair (eod, eod) must never be emitted + for (const pair of pairsA) { + expect(pair.left.source).not.toBe(pair.right.source); + } + // 2 eod * 1 ib + 2 eod * 1 qm + 1 ib * 1 qm = 5 cross-source pairs + expect(pairsA.length).toBe(5); + }); + + test('deriveSourceCountries resolves MIC countries with Stage A fallback deterministically', () => { + const stageARecords: StageASourceRecord[] = [ + { source: 'ib', sourceId: '265598', isin: 'US0378331005', country: 'US' }, + { source: 'eod', sourceId: 'SHOP.TO', isin: 'CA82509L1076', country: 'CA' }, + ]; + const stageBInput = { + eodListings: [ + { sourceId: 'SHOP.TO', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue' as const, currency: 'CAD', span: null }, + ], + tickerSources: [ + { source: 'qm' as const, sourceId: 'SHOP:CA', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue' as const, currency: 'CAD', span: null }, + ], + }; + const countries = deriveSourceCountries(stageARecords, stageBInput, { providerMappings: [] }); + expect(countries.get('ib:265598')).toBe('US'); + expect(countries.get('eod:SHOP.TO')).toBe('CA'); + expect(countries.get('qm:SHOP:CA')).toBe('CA'); + }); +}); + +describe('composeSecurityMasterRun', () => { + test('resolves FB common vs FB ETF to two distinct instruments and listings, chains SIVB -> SIVBQ, and attaches IB + interlisted SHOP', () => { + const { input } = buildCanonicalFixture(); + const result = composeSecurityMasterRun(input, { asOfDate: '2025-11-28' }); + + // FB common (US30303M1027) vs FB ETF (US4642872000) + const fbListings = result.stageB.listings.filter(l => l.tickerRoot === 'FB'); + expect(fbListings.length).toBe(2); + const fbKeys = fbListings.map(l => formatListingNaturalKey(l)); + expect(new Set(fbKeys).size).toBe(2); + expect(new Set(fbListings.map(l => l.primaryIsin))).toEqual( + new Set(['US30303M1027', 'US4642872000']) + ); + expect(result.persistInput.stageA.instruments.filter(i => i.primaryIsin === 'US30303M1027' || i.primaryIsin === 'US4642872000').length).toBe(2); + expect(result.persistInput.securityTypeByIsin.get('US30303M1027')).toBe('common'); + expect(result.persistInput.securityTypeByIsin.get('US4642872000')).toBe('etf'); + + // QM FB_OLD:US -> US30303M1027, QM FB_ETF:US -> US4642872000 + const qmFbOld = result.stageB.providerMappings.find(m => m.source === 'qm' && m.sourceId === 'FB_OLD:US'); + const qmFbEtf = result.stageB.providerMappings.find(m => m.source === 'qm' && m.sourceId === 'FB_ETF:US'); + expect(qmFbOld?.listingKey.primaryIsin).toBe('US30303M1027'); + expect(qmFbEtf?.listingKey.primaryIsin).toBe('US4642872000'); + + // SIVB -> SIVBQ OTC continuity + expect(result.pass6.continuities.length).toBe(1); + const continuity = result.pass6.continuities[0]!; + expect(continuity.fromListingKey.tickerRoot).toBe('SIVB'); + expect(continuity.fromListingKey.mic).toBe('XNAS'); + expect(continuity.toListingKey.tickerRoot).toBe('SIVBQ'); + expect(continuity.toListingKey.mic).toBe('OTCM'); + expect(continuity.kind).toBe(CONTINUITY_KIND_OTC_DELIST_TRANSFER); + expect(result.persistInput.pass6?.continuities).toEqual(result.pass6.continuities); + expect(result.report.delistingChains?.continuitiesCreated).toBe(1); + expect(result.reportMarkdown).toContain('- Continuities Created: 1'); + + // Interlisted SHOP (CA82509L1076) -> 1 instrument, 2 listings (CAD + USD), IB attached at (instrument, currency) + const shopInstruments = result.stageA.instruments.filter(i => i.primaryIsin === 'CA82509L1076'); + expect(shopInstruments.length).toBe(1); + const shopListings = result.stageB.listings.filter(l => l.primaryIsin === 'CA82509L1076'); + expect(shopListings.length).toBe(2); + const shopCad = shopListings.find(l => l.currency === 'CAD'); + const shopUsd = shopListings.find(l => l.currency === 'USD'); + expect(shopCad?.mic).toBe('XTSE'); + expect(shopCad?.ibConid).toBe(2001); + expect(shopUsd?.mic).toBe('XNYS'); + expect(shopUsd?.ibConid).toBe(2002); + + // IB AAPL attached at (US0378331005, USD) + const aaplListing = result.stageB.listings.find(l => l.primaryIsin === 'US0378331005'); + expect(aaplListing?.ibConid).toBe(265598); + }); + + test('Pass 4 supplied confirms matching pairs and emits price_ratio_mismatch into report, CSV, SQL, and persistInput; omitted marks Pass 4 skipped', () => { + const { input, sampleCloses, fxRates } = buildCanonicalFixture(); + + // 1. Omitted sampleCloses -> Pass 4 skipped (never reported as passed) + const skippedRun = composeSecurityMasterRun(input, { asOfDate: '2025-11-28' }); + expect(skippedRun.pass4).toBeNull(); + expect(skippedRun.persistInput.pass4).toBeUndefined(); + expect(skippedRun.stats.pass4.status).toBe('skipped'); + expect(skippedRun.stats.pass4.resolved).toBe(0); + expect(skippedRun.stats.pass4.skipped).toBe(skippedRun.pass4CandidatePairs.length); + expect(skippedRun.report.priceCrossCheck).toBeNull(); + expect(skippedRun.report.conflicts.filter(c => c.pass === 'pass4').length).toBe(0); + expect(skippedRun.reportMarkdown).toContain('- Status: skipped (no sample closes supplied)'); + + // 2. Supplied sampleCloses + fxRates -> AAPL confirmed, SHOP mismatches emitted everywhere + const suppliedRun = composeSecurityMasterRun( + { ...input, sampleCloses, fxRates }, + { asOfDate: '2025-11-28' } + ); + expect(suppliedRun.pass4).not.toBeNull(); + expect(suppliedRun.persistInput.pass4).toBe(suppliedRun.pass4); + expect(suppliedRun.stats.pass4.status).toBe('executed'); + expect(suppliedRun.reportMarkdown).not.toContain('Status: skipped'); + + const aaplRow = suppliedRun.pass4!.results.find( + r => r.left.sourceId === 'AAPL.US' && r.right.sourceId === 'AAPL:US' + ); + expect(aaplRow?.verdict).toBe('confirmed'); + + const pass4Conflicts = suppliedRun.pass4!.conflicts; + expect(pass4Conflicts.length).toBeGreaterThanOrEqual(2); + expect(pass4Conflicts.every(c => c.conflictKind === 'price_ratio_mismatch')).toBe(true); + expect(suppliedRun.report.conflicts.filter(c => c.pass === 'pass4').length).toBe( + pass4Conflicts.length + ); + expect(suppliedRun.conflictsCsv).toContain('price_ratio_mismatch'); + expect(suppliedRun.overrideTemplateSql).toContain('price_ratio_mismatch'); + expect(suppliedRun.persistInput.pass4?.conflicts).toEqual(pass4Conflicts); + }); + + test('produces byte-identical Markdown, CSV, override SQL, and deep-equal persistInput under shuffled inputs', () => { + const { input, sampleCloses, fxRates } = buildCanonicalFixture(); + const baseline = composeSecurityMasterRun( + { ...input, sampleCloses, fxRates }, + { asOfDate: '2025-11-28' } + ); + + const shuffledSecTypes = new Map( + shuffleWithSeed(Array.from(input.sources.securityTypeByIsin.entries()), 77) + ); + const shuffledInput: ComposeSecurityMasterRunInput = { + sources: makeSourcesResult({ + stageARecords: shuffleWithSeed(input.sources.stageARecords, 11), + eodListings: shuffleWithSeed(input.sources.stageBInput.eodListings, 22), + ibContracts: shuffleWithSeed(input.sources.stageBInput.ibContracts, 33), + tickerSources: shuffleWithSeed(input.sources.stageBInput.tickerSources, 44), + symbolChanges: shuffleWithSeed(input.sources.stageBInput.symbolChanges, 55), + securityTypeByIsin: shuffledSecTypes, + }), + barSpans: shuffleWithSeed(input.barSpans as readonly BarSpan[], 66), + exchanges: input.exchanges, + sampleCloses: shuffleWithSeed(sampleCloses, 88), + fxRates: shuffleWithSeed(fxRates, 99), + }; + + const shuffled = composeSecurityMasterRun(shuffledInput, { asOfDate: '2025-11-28' }); + + expect(shuffled.reportMarkdown).toBe(baseline.reportMarkdown); + expect(shuffled.conflictsCsv).toBe(baseline.conflictsCsv); + expect(shuffled.overrideTemplateSql).toBe(baseline.overrideTemplateSql); + expect(shuffled.persistInput).toEqual(baseline.persistInput); + expect(Array.from(shuffled.persistInput.securityTypeByIsin.entries())).toEqual( + Array.from(baseline.persistInput.securityTypeByIsin.entries()) + ); + expect(shuffled.stats).toEqual(baseline.stats); + }); + + test('reconciles per-step stats and conflict totals while counting malformed/sparse records without throwing', () => { + const { input, sampleCloses, fxRates } = buildCanonicalFixture(); + + // Add a Stage A conflict (isin_cusip_mismatch) so conflicts come from multiple passes + const stageARecords: StageASourceRecord[] = [ + ...input.sources.stageARecords, + { + source: 'eod', + sourceId: 'CONFLICT_A.US', + isin: 'US0378331005', + cusip: '594918104', + country: 'US', + currency: 'USD', + name: 'Conflict Co', + }, + // Malformed Stage A records + null as unknown as StageASourceRecord, + { source: 'bogus' as 'eod', sourceId: 'X.US' }, + { source: 'eod', sourceId: '' }, + ]; + // Sparse slot + stageARecords.length += 1; + + const eodListings: StageBEodListingInput[] = [ + ...input.sources.stageBInput.eodListings, + null as unknown as StageBEodListingInput, + { sourceId: 'BAD_ROLE.US', ticker: 'BR', mic: 'XNAS', role: 'invalid_role' as 'primary_venue', currency: 'USD', span: null }, + ]; + const ibContracts: StageBIbContractInput[] = [ + ...input.sources.stageBInput.ibContracts, + { sourceId: '', conid: 999, currency: 'USD', primaryExchange: 'NASDAQ' }, + ]; + const tickerSources: StageBTickerSourceInput[] = [ + ...input.sources.stageBInput.tickerSources, + { source: 'unknown' as 'qm', sourceId: 'U:US', ticker: 'U', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + ]; + const symbolChanges: StageBSymbolChangeInput[] = [ + { eodSourceId: '', oldTicker: 'OLD', effectiveDate: '2022-01-01' }, + { eodSourceId: 'AAPL.US', oldTicker: 'AAPL_OLD', effectiveDate: 'not-a-date' }, + { eodSourceId: 'AAPL.US', oldTicker: 'AAPL_OLD', effectiveDate: '2022-01-01', validFrom: '2023-01-01' }, + ]; + const barSpans: BarSpan[] = [ + ...(input.barSpans as readonly BarSpan[]), + null as unknown as BarSpan, + { source: 'eod', sourceId: 'NEG.US', firstBarDate: '2020-01-02', lastBarDate: '2020-12-31', barCount: -5 }, + ]; + const badCloses: SampleCloseRecord[] = [ + ...sampleCloses, + { source: 'eod', sourceId: 'AAPL.US', date: 'bad-date', close: 100 }, + { source: 'eod', sourceId: 'AAPL.US', date: '2025-01-02', close: -1 }, + ]; + const badFx: FxRateByDateRecord[] = [ + ...fxRates, + { date: '2025-01-02', usdCad: 0 }, + ]; + + const result = composeSecurityMasterRun( + { + sources: makeSourcesResult({ + stageARecords, + eodListings, + ibContracts, + tickerSources, + symbolChanges, + securityTypeByIsin: input.sources.securityTypeByIsin, + }), + barSpans, + exchanges: input.exchanges, + sampleCloses: badCloses, + fxRates: badFx, + }, + { asOfDate: '2025-11-28' } + ); + + // Every step reconciles: recordsIn === resolved + unresolved + skipped + const { stats } = result; + expect(stats.barSpans.recordsIn).toBe( + stats.barSpans.resolved + stats.barSpans.unresolved + stats.barSpans.skipped + ); + expect(stats.stageA.recordsIn).toBe( + stats.stageA.resolved + stats.stageA.unresolved + stats.stageA.skipped + ); + expect(stats.stageB.recordsIn).toBe( + stats.stageB.resolved + stats.stageB.unresolved + stats.stageB.skipped + ); + expect(stats.pass6.recordsIn).toBe( + stats.pass6.resolved + stats.pass6.unresolved + stats.pass6.skipped + ); + expect(stats.pass4.recordsIn).toBe( + stats.pass4.resolved + stats.pass4.unresolved + stats.pass4.skipped + ); + + // Malformed counts surfaced accurately + expect(stats.malformedInputs.stageARecords).toBe(4); // null + bogus source + empty sourceId + sparse slot + expect(stats.malformedInputs.eodListings).toBe(2); + expect(stats.malformedInputs.ibContracts).toBe(1); + expect(stats.malformedInputs.tickerSources).toBe(1); + expect(stats.malformedInputs.symbolChanges).toBe(3); + expect(stats.malformedInputs.barSpans).toBe(2); + expect(stats.malformedInputs.sampleCloses).toBe(2); + expect(stats.malformedInputs.fxRates).toBe(1); + expect(stats.malformedInputs.total).toBe(16); + + // Conflict totals reconcile with report.conflicts.length + expect(stats.conflicts.stageA).toBe(1); + expect(stats.conflicts.pass4).toBeGreaterThanOrEqual(2); + expect(stats.conflicts.total).toBe( + stats.conflicts.stageA + + stats.conflicts.stageB + + stats.conflicts.pass4 + + stats.conflicts.pass6 + ); + expect(result.report.conflicts.length).toBe(stats.conflicts.total); + }); + + test('fails the 95% equity-resolution gate when Stage A rejects >5% of eligible EOD records despite 100% Stage B coverage', () => { + const stageARecords: StageASourceRecord[] = []; + const eodListings: StageBEodListingInput[] = []; + const barSpans: BarSpan[] = []; + const securityTypeByIsin = new Map(); + + // 90 valid in-scope EOD equities that all pass Stage A and match in Stage B (100% Stage B) + for (let i = 0; i < 90; i++) { + const base8 = `B${String(i).padStart(7, '0')}`; + let sum = 0; + for (let pos = 0; pos < 8; pos++) { + const ch = base8.charCodeAt(pos); + let v = ch >= 65 ? ch - 55 : ch - 48; + if (pos % 2 === 1) { + v *= 2; + } + sum += Math.floor(v / 10) + (v % 10); + } + const cusip = `${base8}${(10 - (sum % 10)) % 10}`; + const isin = cusipToIsin(cusip, 'US')!; + const ticker = `E${String(i).padStart(3, '0')}`; + const sourceId = `${ticker}.US`; + stageARecords.push({ + source: 'eod', + sourceId, + isin, + cusip, + country: 'US', + currency: 'USD', + name: `Equity ${i}`, + }); + eodListings.push({ + sourceId, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }); + barSpans.push({ + source: 'eod', + sourceId, + firstBarDate: '2020-01-02', + lastBarDate: '2025-11-28', + barCount: 1500, + }); + securityTypeByIsin.set(isin, 'common'); + } + + // 10 in-scope EOD equities lacking usable identifiers (rejected by Stage A, never reach Stage B) + for (let i = 0; i < 10; i++) { + const ticker = `N${String(i).padStart(3, '0')}`; + const sourceId = `${ticker}.US`; + stageARecords.push({ + source: 'eod', + sourceId, + isin: null, + cusip: null, + country: 'US', + currency: 'USD', + name: `NoId Equity ${i}`, + }); + eodListings.push({ + sourceId, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }); + } + + // 5 excluded_fund EOD records also lacking identifiers (must be excludedByDesign, not penalizing eligibleTotal) + for (let i = 0; i < 5; i++) { + const ticker = `F${String(i).padStart(3, '0')}`; + const sourceId = `${ticker}.US`; + stageARecords.push({ + source: 'eod', + sourceId, + isin: null, + cusip: null, + country: 'US', + currency: 'USD', + name: `Mutual Fund ${i}`, + }); + eodListings.push({ + sourceId, + ticker, + mic: 'XNAS', + role: 'excluded_fund', + currency: 'USD', + span: null, + }); + } + + const sources = makeSourcesResult({ + stageARecords, + eodListings, + ibContracts: [], + tickerSources: [], + securityTypeByIsin, + }); + + const result = composeSecurityMasterRun({ sources, barSpans }, { asOfDate: '2025-11-28' }); + + // Stage B itself saw 90/90 matched (100%), but end-to-end eligible coverage is 90/100 (90%) + expect(result.stageB.stats.bySource.eod.total).toBe(90); + expect(result.stageB.stats.bySource.eod.matched).toBe(90); + + const eodRow = result.report.resolutionBySource.find(r => r.source === 'eod'); + expect(eodRow).toBeDefined(); + expect(eodRow?.total).toBe(105); + expect(eodRow?.matched).toBe(90); + expect(eodRow?.unresolved).toBe(15); + expect(eodRow?.conflict).toBe(0); + expect(eodRow?.excludedByDesign).toBe(5); + expect(eodRow?.eligibleTotal).toBe(100); + expect(eodRow?.eligibleResolvedPct).toBeCloseTo(0.9, 10); + expect(result.report.meetsExitThresholds.equitiesResolved95).toBe(false); + expect(result.reportMarkdown).toContain('| Equities Resolved (Eligible) | FAIL | >= 95.00% |'); + + const usRow = result.report.resolutionByCountry.find(r => r.country === 'US'); + expect(usRow?.eligibleTotal).toBe(100); + expect(usRow?.matched).toBe(90); + expect(usRow?.eligibleResolvedPct).toBeCloseTo(0.9, 10); + + // Duplicate sourceId in both stageARecords (2 rows) and eodListings (2 rows) must not be counted 3 times + const dupSources = makeSourcesResult({ + stageARecords: [ + { + source: 'eod', + sourceId: 'DUP.US', + isin: 'US0378331005', + country: 'US', + currency: 'USD', + name: 'Dup A', + }, + { + source: 'eod', + sourceId: 'DUP.US', + isin: 'US0378331005', + country: 'US', + currency: 'USD', + name: 'Dup B', + }, + ], + eodListings: [ + { + sourceId: 'DUP.US', + ticker: 'DUP', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'DUP.US', + ticker: 'DUP', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + ], + ibContracts: [], + tickerSources: [], + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }); + const dupResult = composeSecurityMasterRun({ sources: dupSources }, { asOfDate: '2025-11-28' }); + const dupEodRow = dupResult.report.resolutionBySource.find(r => r.source === 'eod'); + expect(dupEodRow?.total).toBe(2); + expect(dupEodRow?.conflict).toBe(2); + expect(dupResult.report.meetsExitThresholds.equitiesResolved95).toBe(false); + }); + + test('applies venue eligibility exclusions to Stage A conflicts in source and country coverage while keeping the conflict', () => { + const stageARecords: StageASourceRecord[] = []; + const eodListings: StageBEodListingInput[] = []; + const barSpans: BarSpan[] = []; + const securityTypeByIsin = new Map(); + + // 95 resolved eligible EOD equities + for (let i = 0; i < 95; i++) { + const base8 = `C${String(i).padStart(7, '0')}`; + let sum = 0; + for (let pos = 0; pos < 8; pos++) { + const ch = base8.charCodeAt(pos); + let v = ch >= 65 ? ch - 55 : ch - 48; + if (pos % 2 === 1) { + v *= 2; + } + sum += Math.floor(v / 10) + (v % 10); + } + const cusip = `${base8}${(10 - (sum % 10)) % 10}`; + const isin = cusipToIsin(cusip, 'US')!; + const ticker = `G${String(i).padStart(3, '0')}`; + const sourceId = `${ticker}.US`; + stageARecords.push({ + source: 'eod', + sourceId, + isin, + cusip, + country: 'US', + currency: 'USD', + name: `Good Equity ${i}`, + }); + eodListings.push({ + sourceId, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }); + barSpans.push({ + source: 'eod', + sourceId, + firstBarDate: '2020-01-02', + lastBarDate: '2025-11-28', + barCount: 1500, + }); + securityTypeByIsin.set(isin, 'common'); + } + + // 5 unresolved eligible EOD equities -> exactly 95 / 100 = 95.00% + for (let i = 0; i < 5; i++) { + const ticker = `U${String(i).padStart(3, '0')}`; + const sourceId = `${ticker}.US`; + stageARecords.push({ + source: 'eod', + sourceId, + isin: null, + cusip: null, + country: 'US', + currency: 'USD', + name: `Unresolved Equity ${i}`, + }); + eodListings.push({ + sourceId, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }); + } + + // 1 additional EOD record from a US composite venue with disagreeing valid ISIN & CUSIP + stageARecords.push({ + source: 'eod', + sourceId: 'COMP.US', + isin: 'US0378331005', + cusip: '594918104', + country: 'US', + currency: 'USD', + name: 'Composite Conflict Corp', + }); + eodListings.push({ + sourceId: 'COMP.US', + ticker: 'COMP', + mic: null, + role: 'composite', + currency: 'USD', + span: null, + }); + + const sources = makeSourcesResult({ + stageARecords, + eodListings, + ibContracts: [], + tickerSources: [], + securityTypeByIsin, + }); + + const result = composeSecurityMasterRun({ sources, barSpans }, { asOfDate: '2025-11-28' }); + + // Conflict is preserved in Stage A, report, CSV, and persist input + expect(result.stageA.conflicts.length).toBe(1); + expect(result.stageA.conflicts[0]?.sourceId).toBe('COMP.US'); + expect(result.report.conflicts.length).toBe(1); + expect(result.report.conflicts[0]?.sourceId).toBe('COMP.US'); + expect(result.persistInput.stageA.conflicts.length).toBe(1); + expect(result.conflictsCsv).toContain('COMP.US'); + + // Excluded composite conflict does not inflate eligibleTotal beyond 100 + const eodRow = result.report.resolutionBySource.find(r => r.source === 'eod'); + expect(eodRow?.total).toBe(101); + expect(eodRow?.matched).toBe(95); + expect(eodRow?.unresolved).toBe(5); + expect(eodRow?.conflict).toBe(1); + expect(eodRow?.excludedByDesign).toBe(1); + expect(eodRow?.eligibleTotal).toBe(100); + expect(eodRow?.eligibleResolvedPct).toBeCloseTo(0.95, 10); + + const usRow = result.report.resolutionByCountry.find(r => r.country === 'US'); + expect(usRow?.total).toBe(101); + expect(usRow?.matched).toBe(95); + expect(usRow?.unresolved).toBe(5); + expect(usRow?.conflict).toBe(1); + expect(usRow?.excludedByDesign).toBe(1); + expect(usRow?.eligibleTotal).toBe(100); + expect(usRow?.eligibleResolvedPct).toBeCloseTo(0.95, 10); + + expect(result.report.meetsExitThresholds.equitiesResolved95).toBe(true); + expect(result.reportMarkdown).toContain('| Equities Resolved (Eligible) | PASS | >= 95.00% |'); + }); + + test('restricts Pass 4 sample closes to Stage B mapping validity windows on reused tickers', () => { + const sources = makeSourcesResult({ + stageARecords: [ + { + source: 'eod', + sourceId: 'META.US', + isin: 'US30303M1027', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: 'Meta Platforms Inc.', + }, + ], + eodListings: [ + { + sourceId: 'META.US', + ticker: 'META', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + ], + ibContracts: [], + tickerSources: [ + { + source: 'qm', + sourceId: 'FB:US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + ], + symbolChanges: [ + { + eodSourceId: 'META.US', + oldTicker: 'FB', + effectiveDate: '2022-06-09', + }, + ], + securityTypeByIsin: new Map([['US30303M1027', 'common']]), + }); + + const barSpans: BarSpan[] = [ + { + source: 'eod', + sourceId: 'META.US', + firstBarDate: '2012-05-18', + lastBarDate: '2025-11-28', + barCount: 3400, + }, + { + source: 'qm', + sourceId: 'FB:US', + firstBarDate: '2012-05-18', + lastBarDate: '2025-11-28', + barCount: 3400, + }, + ]; + + // 2 matching closes before rename (too few for minCommonDates=5) + 5 mismatched post-rename closes + const postRenameMismatchedCloses: SampleCloseRecord[] = [ + { source: 'eod', sourceId: 'META.US', date: '2025-03-03', close: 650.0 }, + { source: 'qm', sourceId: 'FB:US', date: '2025-03-03', close: 25.0 }, + { source: 'eod', sourceId: 'META.US', date: '2025-03-04', close: 655.0 }, + { source: 'qm', sourceId: 'FB:US', date: '2025-03-04', close: 25.5 }, + { source: 'eod', sourceId: 'META.US', date: '2025-03-05', close: 660.0 }, + { source: 'qm', sourceId: 'FB:US', date: '2025-03-05', close: 24.8 }, + { source: 'eod', sourceId: 'META.US', date: '2025-03-06', close: 645.0 }, + { source: 'qm', sourceId: 'FB:US', date: '2025-03-06', close: 25.1 }, + { source: 'eod', sourceId: 'META.US', date: '2025-03-07', close: 670.0 }, + { source: 'qm', sourceId: 'FB:US', date: '2025-03-07', close: 26.0 }, + ]; + + const twoPreRenameCloses: SampleCloseRecord[] = [ + { source: 'eod', sourceId: 'META.US', date: '2022-05-02', close: 211.13 }, + { source: 'qm', sourceId: 'FB:US', date: '2022-05-02', close: 211.15 }, + { source: 'eod', sourceId: 'META.US', date: '2022-05-03', close: 212.03 }, + { source: 'qm', sourceId: 'FB:US', date: '2022-05-03', close: 212.0 }, + ]; + + const insufficientResult = composeSecurityMasterRun( + { + sources, + barSpans, + sampleCloses: [...twoPreRenameCloses, ...postRenameMismatchedCloses], + }, + { asOfDate: '2025-11-28' } + ); + + const qmMapping = insufficientResult.stageB.providerMappings.find( + m => m.source === 'qm' && m.sourceId === 'FB:US' + ); + expect(qmMapping?.validTo).toBe('2022-06-08'); + expect(insufficientResult.pass4).not.toBeNull(); + expect(insufficientResult.pass4?.results.length).toBe(1); + expect(insufficientResult.pass4?.results[0]?.verdict).toBe('insufficient_data'); + expect(insufficientResult.pass4?.results[0]?.usableDates).toBe(2); + expect(insufficientResult.pass4?.conflicts.length).toBe(0); + + // 5 matching closes inside the valid window + 5 mismatched post-rename closes -> confirmed, 0 conflicts + const fivePreRenameCloses: SampleCloseRecord[] = [ + ...twoPreRenameCloses, + { source: 'eod', sourceId: 'META.US', date: '2022-05-04', close: 223.41 }, + { source: 'qm', sourceId: 'FB:US', date: '2022-05-04', close: 223.4 }, + { source: 'eod', sourceId: 'META.US', date: '2022-05-05', close: 208.28 }, + { source: 'qm', sourceId: 'FB:US', date: '2022-05-05', close: 208.3 }, + { source: 'eod', sourceId: 'META.US', date: '2022-05-06', close: 203.77 }, + { source: 'qm', sourceId: 'FB:US', date: '2022-05-06', close: 203.75 }, + ]; + + const confirmedResult = composeSecurityMasterRun( + { + sources, + barSpans, + sampleCloses: [...fivePreRenameCloses, ...postRenameMismatchedCloses], + }, + { asOfDate: '2025-11-28' } + ); + + expect(confirmedResult.pass4?.results[0]?.verdict).toBe('confirmed'); + expect(confirmedResult.pass4?.results[0]?.usableDates).toBe(5); + expect(confirmedResult.pass4?.conflicts.length).toBe(0); + + // Direct helper check: malformed closes pass through so crossCheckPrices counts droppedInvalidCloses + const filtered = filterSampleClosesByMappingBounds(insufficientResult.stageB.providerMappings, [ + { source: 'qm', sourceId: 'FB:US', date: '2022-06-08', close: 195.0 }, + { source: 'qm', sourceId: 'FB:US', date: '2022-06-09', close: 25.0 }, + { source: 'qm', sourceId: 'FB:US', date: 'bad-date', close: 10.0 }, + ]); + expect(filtered.map(c => c.date)).toEqual(['2022-06-08', 'bad-date']); + }); + + test('rejects zero-bar spans as malformed and prevents a zero-bar OTC span from establishing continuity', () => { + const sources = makeSourcesResult({ + stageARecords: [ + { + source: 'eod', + sourceId: 'SIVB.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SIVBQ.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group OTC', + }, + ], + eodListings: [ + { + sourceId: 'SIVB.US', + ticker: 'SIVB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'SIVBQ.US', + ticker: 'SIVBQ', + mic: 'OTCM', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + ], + ibContracts: [], + tickerSources: [], + securityTypeByIsin: new Map([['US78486Q1013', 'common']]), + }); + + const barSpans: BarSpan[] = [ + { + source: 'eod', + sourceId: 'SIVB.US', + firstBarDate: '2015-01-02', + lastBarDate: '2023-03-10', + barCount: 2050, + }, + { + source: 'eod', + sourceId: 'SIVBQ.US', + firstBarDate: '2023-03-28', + lastBarDate: '2024-11-07', + barCount: 0, + }, + ]; + + const result = composeSecurityMasterRun({ sources, barSpans }, { asOfDate: '2025-11-28' }); + + expect(result.stats.barSpans.recordsIn).toBe(2); + expect(result.stats.barSpans.resolved).toBe(1); + expect(result.stats.barSpans.unresolved).toBe(0); + expect(result.stats.barSpans.skipped).toBe(1); + expect(result.stats.barSpans.indexedSpans).toBe(1); + expect(result.stats.malformedInputs.barSpans).toBe(1); + + const sivbqListing = result.stageB.listings.find(l => l.tickerRoot === 'SIVBQ'); + expect(sivbqListing?.listedFrom).toBeNull(); + expect(sivbqListing?.listedTo).toBeNull(); + expect(result.pass6.continuities.length).toBe(0); + }); + + test('carries through totalRowsRead and skipped.total from ComputeBarSpansResult and separates accepted rows from distinct indexed spans', () => { + const index = new BarSpanIndex(); + for (let i = 0; i < 99; i++) { + index.merge({ + source: 'eod', + sourceId: `SYM${i}.US`, + firstBarDate: '2020-01-02', + lastBarDate: '2025-11-28', + barCount: 1000, + }); + } + // Merge one duplicate row into an existing span: 100 accepted rows -> 99 distinct indexed spans + index.merge({ + source: 'eod', + sourceId: 'SYM0.US', + firstBarDate: '2019-01-02', + lastBarDate: '2025-11-28', + barCount: 250, + }); + + const readerResult: ComputeBarSpansResult = { + index, + bySource: { + eod: { + source: 'eod', + collection: 'eodPrices', + batchesRun: 1, + rowsRead: 101, + spansIndexed: 99, + skipped: { invalidId: 0, invalidDate: 1, invalidCount: 0, total: 1 }, + }, + }, + skipped: { invalidId: 0, invalidDate: 1, invalidCount: 0, total: 1 }, + totalRowsRead: 101, + totalSpans: 99, + }; + + const attached = attachBarSpansToStageBInput( + { + eodListings: [ + { + sourceId: 'SYM0.US', + ticker: 'SYM0', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + ], + ibContracts: [], + tickerSources: [], + symbolChanges: [], + }, + readerResult + ); + + expect(attached.stats.recordsIn).toBe(101); + expect(attached.stats.resolved).toBe(100); + expect(attached.stats.unresolved).toBe(0); + expect(attached.stats.skipped).toBe(1); + expect(attached.stats.indexedSpans).toBe(99); + expect(attached.stats.recordsIn).toBe( + attached.stats.resolved + attached.stats.unresolved + attached.stats.skipped + ); + expect(attached.malformed.barSpans).toBe(1); + expect(attached.stageBInput.eodListings[0]?.span).toEqual({ + firstBarDate: '2019-01-02', + lastBarDate: '2025-11-28', + }); + + const sources = makeSourcesResult({ + stageARecords: [ + { + source: 'eod', + sourceId: 'SYM0.US', + isin: 'US0378331005', + country: 'US', + currency: 'USD', + name: 'Sym Zero', + }, + ], + eodListings: [ + { + sourceId: 'SYM0.US', + ticker: 'SYM0', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + ], + ibContracts: [], + tickerSources: [], + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }); + + const composed = composeSecurityMasterRun( + { sources, barSpans: readerResult }, + { asOfDate: '2025-11-28' } + ); + expect(composed.stats.barSpans.recordsIn).toBe(101); + expect(composed.stats.barSpans.resolved).toBe(100); + expect(composed.stats.barSpans.skipped).toBe(1); + expect(composed.stats.barSpans.indexedSpans).toBe(99); + expect(composed.stats.malformedInputs.barSpans).toBe(1); + }); + + test('composes a fixed-seed 100,000-record synthetic workload end to end above the sandbox throughput floor', () => { + // 50,000 EOD + 25,000 IB + 25,000 QM = 100,000 source records + const numInstruments = 50_000; + const numIb = 25_000; + const numQm = 25_000; + const totalSourceRecords = numInstruments + numIb + numQm; + + const stageARecords: StageASourceRecord[] = new Array(numInstruments + numIb); + const eodListings: StageBEodListingInput[] = new Array(numInstruments); + const ibContracts: StageBIbContractInput[] = new Array(numIb); + const tickerSources: StageBTickerSourceInput[] = new Array(numQm); + const barSpans: BarSpan[] = new Array(numInstruments + numQm); + const securityTypeByIsin = new Map(); + + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + let stageAIdx = 0; + let spanIdx = 0; + + for (let i = 0; i < numInstruments; i++) { + // Deterministic valid US ISIN via cusipToIsin (9-char CUSIP: 6-digit issuer + 2-char issue + check) + // Construct a valid 9-char CUSIP using cusipToIsin after computing CUSIP check digit, or direct ISIN: + const base8 = `A${String(i).padStart(7, '0')}`; + // Compute CUSIP check digit (Luhn mod 10 over A=10..Z=35) + let sum = 0; + for (let pos = 0; pos < 8; pos++) { + const ch = base8.charCodeAt(pos); + let v = ch >= 65 ? ch - 55 : ch - 48; + if (pos % 2 === 1) { + v *= 2; + } + sum += Math.floor(v / 10) + (v % 10); + } + const checkDigit = (10 - (sum % 10)) % 10; + const cusip = `${base8}${checkDigit}`; + const isin = cusipToIsin(cusip, 'US')!; + + // Unique 4-letter ticker from i + const c0 = alphabet[Math.floor(i / (26 * 26 * 26)) % 26]!; + const c1 = alphabet[Math.floor(i / (26 * 26)) % 26]!; + const c2 = alphabet[Math.floor(i / 26) % 26]!; + const c3 = alphabet[i % 26]!; + const ticker = `${c0}${c1}${c2}${c3}`; + const eodId = `${ticker}.US`; + + stageARecords[stageAIdx++] = { + source: 'eod', + sourceId: eodId, + isin, + cusip, + country: 'US', + currency: 'USD', + name: `Bench Corp ${i}`, + }; + eodListings[i] = { + sourceId: eodId, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }; + barSpans[spanIdx++] = { + source: 'eod', + sourceId: eodId, + firstBarDate: '2018-01-02', + lastBarDate: '2025-11-28', + barCount: 1980, + }; + securityTypeByIsin.set(isin, 'common'); + + if (i < numIb) { + const ibId = String(1_000_000 + i); + stageARecords[stageAIdx++] = { + source: 'ib', + sourceId: ibId, + isin, + cusip, + country: 'US', + currency: 'USD', + name: `Bench Corp ${i}`, + }; + ibContracts[i] = { + sourceId: ibId, + conid: 1_000_000 + i, + currency: 'USD', + primaryExchange: 'NASDAQ', + }; + } + + if (i < numQm) { + const qmId = `${ticker}:US`; + tickerSources[i] = { + source: 'qm', + sourceId: qmId, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }; + barSpans[spanIdx++] = { + source: 'qm', + sourceId: qmId, + firstBarDate: '2020-01-02', + lastBarDate: '2025-11-28', + barCount: 1480, + }; + } + } + + const sources = makeSourcesResult({ + stageARecords, + eodListings, + ibContracts, + tickerSources, + securityTypeByIsin, + }); + + const startMs = performance.now(); + const result = composeSecurityMasterRun( + { sources, barSpans }, + { asOfDate: '2025-11-28' } + ); + const elapsedMs = performance.now() - startMs; + const recordsPerSec = totalSourceRecords / (elapsedMs / 1000); + + expect(totalSourceRecords).toBe(100_000); + expect(result.stageA.instruments.length).toBe(numInstruments); + expect(result.stageB.listings.length).toBe(numInstruments); + expect(result.stageB.providerMappings.length).toBe(totalSourceRecords); + expect(result.stats.stageA.recordsIn).toBe( + result.stats.stageA.resolved + result.stats.stageA.unresolved + result.stats.stageA.skipped + ); + expect(result.stats.stageB.recordsIn).toBe( + result.stats.stageB.resolved + result.stats.stageB.unresolved + result.stats.stageB.skipped + ); + expect(result.stats.pass4.status).toBe('skipped'); + // Assert conservative sandbox throughput floor (>= 10,000 records/s) + expect(recordsPerSec).toBeGreaterThanOrEqual(10_000); + }); +}); diff --git a/test/unit/security-master-security-type.test.ts b/test/unit/security-master-security-type.test.ts new file mode 100644 index 00000000..710531f9 --- /dev/null +++ b/test/unit/security-master-security-type.test.ts @@ -0,0 +1,507 @@ +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { + buildSecurityTypeByIsin, + buildSecurityTypeByIsinForStageA, + classifyEodSecurityType, + compareAscii, + DEFAULT_MAX_SECURITY_TYPE_CONFLICTS, + EOD_SECURITY_TYPE_MAP, + SECURITY_TYPES, + type SecurityType, + type SecurityTypeClassificationStats, + type SecurityTypeInputRecord, + type StageAInstrumentCandidate, +} from '../../apps/stock/data-pipeline/src/security-master'; + +function mulberry32(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) / 4294967296; + }; +} + +function shuffleWithSeed(items: readonly T[], seed: number): T[] { + const copy = items.slice(); + const rand = mulberry32(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rand() * (i + 1)); + const tmp = copy[i]!; + copy[i] = copy[j]!; + copy[j] = tmp; + } + return copy; +} + +function assertStatsReconcile( + stats: SecurityTypeClassificationStats, + mappedSize: number, + conflictsLength: number, + unknownTotal: number +): void { + expect(stats.recordsIn).toBe( + stats.classified + stats.missingIsin + stats.missingType + stats.unknownType + ); + expect(stats.isinsMapped).toBe(mappedSize); + expect(stats.isinsMapped + stats.isinsConflicting).toBe(stats.distinctClassifiedIsins); + expect(stats.isinsConflicting).toBe(conflictsLength + stats.conflictsTruncated); + expect(unknownTotal).toBe(stats.unknownType); +} + +describe('security-master security-type classifier', () => { + test('zero-I/O static proof: security-type.ts has no DB, fs, or network imports', () => { + const sourcePath = resolve( + import.meta.dir, + '../../apps/stock/data-pipeline/src/security-master/security-type.ts' + ); + const sourceText = readFileSync(sourcePath, 'utf8'); + expect(sourceText).not.toMatch( + /from\s+['"](?:node:fs|node:net|node:http|node:https|mongodb|pg|@stock-bot\/mongodb|@stock-bot\/postgres)['"]/ + ); + }); + + test('classifyEodSecurityType maps every EOD_SECURITY_TYPE_MAP entry and case/whitespace variants into SECURITY_TYPES', () => { + expect(Object.isFrozen(EOD_SECURITY_TYPE_MAP)).toBe(true); + expect(DEFAULT_MAX_SECURITY_TYPE_CONFLICTS).toBe(200); + + const validSecurityTypes = new Set(SECURITY_TYPES); + const observedOutputs = new Set(); + + for (const [rawKey, expectedType] of Object.entries(EOD_SECURITY_TYPE_MAP)) { + expect(validSecurityTypes.has(expectedType)).toBe(true); + observedOutputs.add(expectedType); + + // Exact, lowercase, mixed-case, leading/trailing spaces, and collapsed internal whitespace. + expect(classifyEodSecurityType(rawKey)).toBe(expectedType); + expect(classifyEodSecurityType(rawKey.toLowerCase())).toBe(expectedType); + expect(classifyEodSecurityType(` ${rawKey.toLowerCase()} `)).toBe(expectedType); + expect(classifyEodSecurityType(`\t${rawKey.replace(/ /g, ' \t\n ')}\n`)).toBe( + expectedType + ); + } + + // All 8 canonical SecurityType values are reachable from EOD_SECURITY_TYPE_MAP. + expect([...observedOutputs].sort(compareAscii)).toEqual([...SECURITY_TYPES].sort(compareAscii)); + + // Spot-check realistic provider spellings. + expect(classifyEodSecurityType('Common Stock')).toBe('common'); + expect(classifyEodSecurityType('Preferred Stock')).toBe('preferred'); + expect(classifyEodSecurityType('ETF')).toBe('etf'); + expect(classifyEodSecurityType('Unit')).toBe('unit'); + expect(classifyEodSecurityType('Units')).toBe('unit'); + expect(classifyEodSecurityType('Warrant')).toBe('warrant'); + expect(classifyEodSecurityType('Warrants')).toBe('warrant'); + expect(classifyEodSecurityType('Right')).toBe('right'); + expect(classifyEodSecurityType('Rights')).toBe('right'); + expect(classifyEodSecurityType('CDR')).toBe('cdr'); + expect(classifyEodSecurityType('Currency')).toBe('fx'); + expect(classifyEodSecurityType('Forex')).toBe('fx'); + expect(classifyEodSecurityType('FX')).toBe('fx'); + }); + + test('classifyEodSecurityType returns null for non-equity values, blanks, unknowns, non-strings, and prototype keys', () => { + const nullInputs: unknown[] = [ + // Documented non-equity EODHD values (must never be guessed) + 'FUND', + 'Mutual Fund', + 'Bond', + 'Notes', + 'INDEX', + 'Index', + 'ETC', + 'Closed-End Fund', + 'Trust', + // Blanks and whitespace + '', + ' ', + ' \t\n\r ', + // Unknown values + 'Cryptocurrency', + 'ADR', + 'Depositary Receipt', + // Non-strings + null, + undefined, + 0, + 42, + true, + false, + {}, + ['Common Stock'], + Symbol('ETF'), + // Prototype keys (must never match Object.prototype properties) + 'toString', + 'constructor', + '__proto__', + 'valueOf', + 'hasOwnProperty', + 'TOSTRING', + 'CONSTRUCTOR', + ]; + + for (const input of nullInputs) { + expect(classifyEodSecurityType(input)).toBeNull(); + } + }); + + test('buildSecurityTypeByIsin omits conflicts, collapses duplicates, handles mixed missing/unknown on same ISIN, and sorts unknowns', () => { + const records: SecurityTypeInputRecord[] = [ + // Identical duplicates collapse into one mapped ISIN + { isin: 'US0378331005', rawType: 'Common Stock', sourceId: 'AAPL.US' }, + { isin: 'US0378331005', rawType: ' common stock ', sourceId: 'AAPL.NEO' }, + // Classified + missingType + unknownType on same ISIN -> still maps cleanly without conflict + { isin: 'CA82509L1076', rawType: 'Common Stock', sourceId: 'SHOP.TO' }, + { isin: 'CA82509L1076', rawType: null, sourceId: 'SHOP.US' }, + { isin: 'CA82509L1076', rawType: 'Unknown Variant', sourceId: 'SHOP.NEO' }, + // Conflicting types on one ISIN -> omitted from map, emitted in conflicts + { isin: 'US1111111111', rawType: 'ETF', sourceId: 'CONF.US' }, + { isin: 'US1111111111', rawType: 'Common Stock', sourceId: 'CONF.TO' }, + { isin: 'US1111111111', rawType: 'Preferred Stock', sourceId: 'CONF.V' }, + // Second conflict to verify ASCII ordering and capping + { isin: 'CA2222222222', rawType: 'Unit', sourceId: 'UNIT.TO' }, + { isin: 'CA2222222222', rawType: 'Warrant', sourceId: 'UNIT.V' }, + // Missing ISIN (counts as missingIsin even if rawType is also missing or unknown) + { isin: null, rawType: 'Common Stock', sourceId: 'NOISIN1.US' }, + { isin: ' ', rawType: undefined, sourceId: 'NOISIN2.US' }, + // Missing/non-string/blank type on valid ISIN + { isin: 'US3333333333', rawType: undefined, sourceId: 'NOTYPE1.US' }, + { isin: 'US3333333333', rawType: 123, sourceId: 'NOTYPE2.US' }, + { isin: 'US3333333333', rawType: ' \t ', sourceId: 'NOTYPE3.US' }, + // Unknown raw types with ties to verify count desc then ASCII tie-breaking + { isin: 'US4444444444', rawType: 'FUND', sourceId: 'F1.US' }, + { isin: 'US4444444445', rawType: ' FUND ', sourceId: 'F2.US' }, + { isin: 'US4444444446', rawType: 'FUND', sourceId: 'F3.US' }, + { isin: 'US5555555555', rawType: 'Mutual Fund', sourceId: 'MF1.US' }, + { isin: 'US5555555556', rawType: 'Mutual Fund', sourceId: 'MF2.US' }, + { isin: 'US6666666666', rawType: 'Bond', sourceId: 'B1.US' }, + { isin: 'US6666666667', rawType: 'Bond', sourceId: 'B2.US' }, + { isin: 'US7777777777', rawType: 'INDEX', sourceId: 'IDX1.US' }, + ]; + + const result = buildSecurityTypeByIsin(records); + + // Mapped ISINs in ASCII order, excluding conflicting ISINs + expect([...result.securityTypeByIsin.entries()]).toEqual([ + ['CA82509L1076', 'common'], + ['US0378331005', 'common'], + ]); + + // Conflicts in ASCII order by ISIN, with sorted types and sourceIds + expect(result.conflicts).toEqual([ + { + isin: 'CA2222222222', + types: ['unit', 'warrant'], + sourceIds: ['UNIT.TO', 'UNIT.V'], + recordCount: 2, + }, + { + isin: 'US1111111111', + types: ['common', 'etf', 'preferred'], + sourceIds: ['CONF.TO', 'CONF.US', 'CONF.V'], + recordCount: 3, + }, + ]); + + // Unknown raw types sorted by count desc, then ASCII (Bond before Mutual Fund at count 2) + expect(result.unknownRawTypes).toEqual([ + { rawType: 'FUND', count: 3 }, + { rawType: 'Bond', count: 2 }, + { rawType: 'Mutual Fund', count: 2 }, + { rawType: 'INDEX', count: 1 }, + { rawType: 'Unknown Variant', count: 1 }, + ]); + + const unknownSum = result.unknownRawTypes.reduce((acc, row) => acc + row.count, 0); + assertStatsReconcile( + result.stats, + result.securityTypeByIsin.size, + result.conflicts.length, + unknownSum + ); + expect(result.stats).toEqual({ + recordsIn: 23, + classified: 8, + missingIsin: 2, + missingType: 4, + unknownType: 9, + distinctClassifiedIsins: 4, + isinsMapped: 2, + isinsConflicting: 2, + conflictsTruncated: 0, + }); + + // Capping conflicts preserves total count and reports conflictsTruncated + const capped = buildSecurityTypeByIsin(records, { maxConflicts: 1 }); + expect(capped.conflicts.map(c => c.isin)).toEqual(['CA2222222222']); + expect(capped.stats.isinsConflicting).toBe(2); + expect(capped.stats.conflictsTruncated).toBe(1); + assertStatsReconcile( + capped.stats, + capped.securityTypeByIsin.size, + capped.conflicts.length, + unknownSum + ); + + const zeroCapped = buildSecurityTypeByIsin(records, { maxConflicts: 0 }); + expect(zeroCapped.conflicts).toEqual([]); + expect(zeroCapped.stats.isinsConflicting).toBe(2); + expect(zeroCapped.stats.conflictsTruncated).toBe(2); + + // Invalid maxConflicts rejected + expect(() => buildSecurityTypeByIsin(records, { maxConflicts: -1 })).toThrow(RangeError); + expect(() => buildSecurityTypeByIsin(records, { maxConflicts: 1.5 })).toThrow(RangeError); + expect(() => buildSecurityTypeByIsin(records, { maxConflicts: Number.NaN })).toThrow( + RangeError + ); + }); + + test('determinism: output is identical across input permutations', () => { + const records: SecurityTypeInputRecord[] = [ + { isin: 'US98954M1018', rawType: 'Common Stock', sourceId: 'Z.US' }, + { isin: 'US0378331005', rawType: 'Common Stock', sourceId: 'AAPL.US' }, + { isin: 'CA7800871021', rawType: 'Preferred Stock', sourceId: 'RY-PA.TO' }, + { isin: 'CA82509L1076', rawType: 'ETF', sourceId: 'SHOP.TO' }, + { isin: 'CA82509L1076', rawType: 'Common Stock', sourceId: 'SHOP.US' }, + { isin: 'CA82509L1076', rawType: 'Unit', sourceId: 'SHOP.NEO' }, + { isin: 'US1234567890', rawType: 'CDR', sourceId: 'CDR1.NEO' }, + { isin: 'US1234567890', rawType: 'CDR', sourceId: 'CDR2.NEO' }, + { isin: 'US0000000001', rawType: 'FUND', sourceId: 'F1.US' }, + { isin: 'US0000000002', rawType: 'Bond', sourceId: 'B1.US' }, + { isin: 'US0000000003', rawType: 'FUND', sourceId: 'F2.US' }, + { isin: null, rawType: 'Warrant', sourceId: 'W1.TO' }, + { isin: 'US0000000004', rawType: null, sourceId: 'M1.US' }, + ]; + + const serialize = (res: ReturnType) => + JSON.stringify({ + entries: [...res.securityTypeByIsin.entries()], + stats: res.stats, + unknownRawTypes: res.unknownRawTypes, + conflicts: res.conflicts, + }); + + const baseline = serialize(buildSecurityTypeByIsin(records)); + + for (const seed of [7, 42, 1337, 20261128, 999999]) { + const shuffled = shuffleWithSeed(records, seed); + expect(serialize(buildSecurityTypeByIsin(shuffled))).toBe(baseline); + } + }); + + test('buildSecurityTypeByIsinForStageA includes only Stage A-accepted EOD members and prevents quarantined rows from supplying or vetoing types', () => { + const records: SecurityTypeInputRecord[] = [ + // Accepted EOD member for US0378331005 + { isin: 'US0378331005', rawType: 'Common Stock', sourceId: 'AAPL.US' }, + // Quarantined EOD row (not in instruments) sharing US0378331005 with conflicting Type + { isin: 'US0378331005', rawType: 'ETF', sourceId: 'AAPL_STALE.US' }, + // Quarantined EOD row that is the only row for US30303M1027 + { isin: 'US30303M1027', rawType: 'ETF', sourceId: 'META_BAD.US' }, + // Accepted EOD member whose raw record had null isin (Stage A primaryIsin is authoritative) + { isin: null, rawType: 'Unit', sourceId: 'SCU-UN.TO' }, + ]; + + const instruments: StageAInstrumentCandidate[] = [ + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple Inc.', + members: [ + { source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: '265598', currency: 'USD', method: 'tier1_isin' }, + ], + }, + { + primaryIsin: 'CA8131371066', + primaryCusip: '813137106', + issuerCountry: 'CA', + canonicalName: 'Second Cup Income Fund', + members: [{ source: 'eod', sourceId: 'SCU-UN.TO', currency: 'CAD', method: 'tier2_cusip' }], + }, + // IB-only instrument (no EOD members) + { + primaryIsin: 'CA7800871021', + primaryCusip: '780087102', + issuerCountry: 'CA', + canonicalName: 'Royal Bank of Canada', + members: [{ source: 'ib', sourceId: '100001', currency: 'CAD', method: 'tier1_isin' }], + }, + ]; + + const result = buildSecurityTypeByIsinForStageA(records, instruments); + expect([...result.securityTypeByIsin.entries()]).toEqual([ + ['CA8131371066', 'unit'], + ['US0378331005', 'common'], + ]); + expect(result.conflicts).toEqual([]); + expect(result.unknownRawTypes).toEqual([]); + assertStatsReconcile( + result.stats, + result.securityTypeByIsin.size, + result.conflicts.length, + 0 + ); + expect(result.stats).toEqual({ + recordsIn: 2, + classified: 2, + missingIsin: 0, + missingType: 0, + unknownType: 0, + distinctClassifiedIsins: 2, + isinsMapped: 2, + isinsConflicting: 0, + conflictsTruncated: 0, + }); + }); + + test('local benchmark: >= 300,000 synthetic EOD records classify at >= 100,000 records/s with zero DB connections', () => { + const RECORD_COUNT = 300_000; + const rand = mulberry32(20261128); + const vocabulary: readonly unknown[] = [ + 'Common Stock', + 'Preferred Stock', + 'ETF', + 'Unit', + 'Warrant', + 'Right', + 'CDR', + 'Currency', + 'FUND', + 'Mutual Fund', + 'Bond', + null, + ]; + + // Pre-build 300k deterministic records (100k distinct ISINs, ~3 records/ISIN, small conflict rate). + const records: SecurityTypeInputRecord[] = new Array(RECORD_COUNT); + for (let i = 0; i < RECORD_COUNT; i++) { + const bucket = i % 100_000; + const missingIsin = i % 50 === 0; + const isin = missingIsin ? null : `US${String(bucket).padStart(10, '0')}`; + // Every 5,000th bucket (offset +1 so it is not also a missingIsin bucket) introduces a conflict. + let rawType: unknown; + if (!missingIsin && bucket % 5_000 === 1 && i >= 100_000) { + rawType = 'ETF'; + } else if (i % 20 === 0) { + rawType = vocabulary[8 + Math.floor(rand() * 4)]; + } else { + rawType = vocabulary[bucket % 8]; + } + records[i] = { + isin, + rawType, + sourceId: `SYM${i}.US`, + }; + } + + const started = performance.now(); + const result = buildSecurityTypeByIsin(records); + const elapsedMs = performance.now() - started; + const recordsPerSec = Math.round(RECORD_COUNT / (elapsedMs / 1000)); + + process.stdout.write( + `[security-type benchmark] ${RECORD_COUNT.toLocaleString('en-US')} records in ${elapsedMs.toFixed(1)} ms (${recordsPerSec.toLocaleString('en-US')} records/s, mapped=${result.stats.isinsMapped}, conflicts=${result.stats.isinsConflicting})\n` + ); + + const unknownSum = result.unknownRawTypes.reduce((acc, row) => acc + row.count, 0); + assertStatsReconcile( + result.stats, + result.securityTypeByIsin.size, + result.conflicts.length, + unknownSum + ); + expect(result.stats.recordsIn).toBe(RECORD_COUNT); + expect(result.stats.isinsMapped).toBeGreaterThan(80_000); + expect(result.stats.isinsConflicting).toBeGreaterThan(0); + expect(recordsPerSec).toBeGreaterThanOrEqual(100_000); + }); +}); + +describe('security-master security-type classifier QA edges', () => { + test('a conflict that later returns to the first type stays conflicting (A, B, A) in every order', () => { + const records: SecurityTypeInputRecord[] = [ + { isin: 'US0378331005', rawType: 'Common Stock', sourceId: 'A1' }, + { isin: 'US0378331005', rawType: 'ETF', sourceId: 'A2' }, + { isin: 'US0378331005', rawType: 'Common Stock', sourceId: 'A3' }, + ]; + for (const seed of [1, 2, 3, 4, 5, 6]) { + const result = buildSecurityTypeByIsin(shuffleWithSeed(records, seed)); + expect(result.securityTypeByIsin.size).toBe(0); + expect(result.conflicts).toEqual([ + { isin: 'US0378331005', types: ['common', 'etf'], sourceIds: ['A1', 'A2', 'A3'], recordCount: 3 }, + ]); + } + }); + + test('ISIN keys are trimmed so padded and unpadded ISINs collapse into one entry', () => { + const result = buildSecurityTypeByIsin([ + { isin: ' US0378331005 ', rawType: 'Common Stock', sourceId: 'A1' }, + { isin: 'US0378331005', rawType: 'ETF', sourceId: 'A2' }, + { isin: 'CA82509L1076\t', rawType: 'Unit', sourceId: 'B1' }, + ]); + expect([...result.securityTypeByIsin.entries()]).toEqual([['CA82509L1076', 'unit']]); + expect(result.conflicts.map(c => c.isin)).toEqual(['US0378331005']); + expect(result.conflicts[0]?.recordCount).toBe(2); + }); + + test('conflict detail counts only classified records (unknown/missing types on the ISIN are excluded)', () => { + const result = buildSecurityTypeByIsin([ + { isin: 'US0378331005', rawType: 'Common Stock', sourceId: 'A1' }, + { isin: 'US0378331005', rawType: 'Warrant', sourceId: 'A2' }, + { isin: 'US0378331005', rawType: 'FUND', sourceId: 'A3' }, + { isin: 'US0378331005', rawType: null, sourceId: 'A4' }, + ]); + expect(result.conflicts).toEqual([ + { isin: 'US0378331005', types: ['common', 'warrant'], sourceIds: ['A1', 'A2'], recordCount: 2 }, + ]); + expect(result.stats.classified).toBe(2); + }); + + test('empty input yields empty outputs with zeroed stats; Infinity maxConflicts rejects', () => { + const result = buildSecurityTypeByIsin([]); + expect(result.securityTypeByIsin.size).toBe(0); + expect(result.unknownRawTypes).toEqual([]); + expect(result.conflicts).toEqual([]); + expect(Object.values(result.stats).every(v => v === 0)).toBe(true); + expect(() => buildSecurityTypeByIsin([], { maxConflicts: Number.POSITIVE_INFINITY })).toThrow( + RangeError + ); + }); + + test('unknown raw types group by whitespace-collapsed exact case (case variants are reported separately)', () => { + const result = buildSecurityTypeByIsin([ + { isin: 'US0000000001', rawType: 'Mutual Fund', sourceId: 'A' }, + { isin: 'US0000000002', rawType: ' Mutual Fund', sourceId: 'B' }, + { isin: 'US0000000003', rawType: 'mutual fund', sourceId: 'C' }, + ]); + expect(result.unknownRawTypes).toEqual([ + { rawType: 'Mutual Fund', count: 2 }, + { rawType: 'mutual fund', count: 1 }, + ]); + }); + + test('ForStageA: EOD members of an instrument with a different raw ISIN are keyed by primaryIsin, and IB members never supply a type', () => { + const instruments: StageAInstrumentCandidate[] = [ + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple Inc.', + members: [ + { source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier2_cusip' }, + { source: 'ib', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ]; + const result = buildSecurityTypeByIsinForStageA( + [{ isin: 'XX-raw-ignored', rawType: 'Preferred Stock', sourceId: 'AAPL.US' }], + instruments + ); + expect([...result.securityTypeByIsin.entries()]).toEqual([['US0378331005', 'preferred']]); + expect(buildSecurityTypeByIsinForStageA([], instruments).securityTypeByIsin.size).toBe(0); + }); +}); diff --git a/test/unit/security-master-source-symbol-readers-qa.test.ts b/test/unit/security-master-source-symbol-readers-qa.test.ts new file mode 100644 index 00000000..105ba67c --- /dev/null +++ b/test/unit/security-master-source-symbol-readers-qa.test.ts @@ -0,0 +1,438 @@ +import { describe, expect, test } from 'bun:test'; +import { parseTickerDetailed } from '../../apps/stock/data-pipeline/src/normalization/ticker'; +import { + adaptCeoSymbolDoc, + adaptEodSymbolChangeDoc, + adaptEodSymbolDoc, + adaptIbSymbolDoc, + adaptQmSymbolDoc, + createExchangeSourceLookup, + createReadOnlyMongoSourceSymbolReader, + ISO_EXCHANGE_SEEDS, + readEodSymbols, + readIbSymbols, + readSecurityMasterSources, + SOURCE_SYMBOL_COLLECTIONS, + type ReadOnlyMongoCollectionClient, + type ReadOnlySourceSymbolReader, + type SourceCollectionReadStats, + type SourceSymbolFindOptions, +} from '../../apps/stock/data-pipeline/src/security-master'; + +// QA supplement for T-86: edge cases not covered by security-master-source-symbol-readers.test.ts. +// In-memory fakes only — no MongoDB or PostgreSQL connection is opened. + +const lookup = createExchangeSourceLookup(); +const micCurrencyMap = new Map(ISO_EXCHANGE_SEEDS.map(row => [row.mic, row.currency])); +const usCa: ReadonlySet = new Set(['US', 'CA']); + +function assertConservation(stats: SourceCollectionReadStats): void { + const skipped = Object.values(stats.skips).reduce((sum, n) => sum + n, 0); + expect(stats.docsRead).toBe(stats.emitted + skipped); +} + +function arrayReader( + collections: Readonly[]>> +): ReadOnlySourceSymbolReader & { calls: string[] } { + const calls: string[] = []; + return { + calls, + isReadOnly: () => true, + find>(name: string): AsyncIterable { + calls.push(name); + const docs = collections[name] ?? []; + return { + async *[Symbol.asyncIterator]() { + for (const doc of docs) { + yield doc as T; + } + }, + }; + }, + }; +} + +const MIXED_COUNTRY_EOD = [ + { + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + Exchange: 'NASDAQ', + Country: 'USA', + Isin: 'US0378331005', + }, + { eodSearchCode: 'RY.TO', Code: 'RY', Exchange: 'TO', Country: 'Canada', Isin: 'CA7800871021' }, + { + eodSearchCode: 'SAP.XETRA', + Code: 'SAP', + Exchange: 'XETRA', + Country: 'Germany', + Isin: 'DE0007164600', + }, +]; + +describe('source-symbol-readers QA supplement', () => { + test('country option: [] emits nothing, null disables filtering, aliases like "usa" normalize', async () => { + const collections = { [SOURCE_SYMBOL_COLLECTIONS.eod]: MIXED_COUNTRY_EOD }; + const germanLookup = createExchangeSourceLookup([ + { + source: 'eod', + sourceCode: 'XETRA', + role: 'primary_venue', + mic: 'XETR', + countryIso: 'DE', + method: 'explicit_rule', + reviewedBy: 'qa', + }, + ]); + + const empty = await readEodSymbols(arrayReader(collections), { + exchangeLookup: germanLookup, + countries: [], + }); + expect(empty.stageARecords).toHaveLength(0); + expect(empty.stats.skips.outOfScopeCountry).toBe(3); + assertConservation(empty.stats); + + const all = await readEodSymbols(arrayReader(collections), { + exchangeLookup: germanLookup, + countries: null, + }); + expect(all.stageARecords.map(r => r.sourceId)).toEqual(['AAPL.US', 'RY.TO', 'SAP.XETRA']); + expect(all.stageARecords.find(r => r.sourceId === 'SAP.XETRA')?.country).toBe('DE'); + assertConservation(all.stats); + + const aliased = await readEodSymbols(arrayReader(collections), { + exchangeLookup: germanLookup, + countries: ['usa'], + }); + expect(aliased.stageARecords.map(r => r.sourceId)).toEqual(['AAPL.US']); + expect(aliased.stats.skips.outOfScopeCountry).toBe(2); + assertConservation(aliased.stats); + }); + + test('EOD: lowercase ISIN is uppercased, missing currency falls back to listing MIC currency, invalid-ISIN-only gives null issuer country', () => { + const ctx = { exchangeLookup: lookup, allowedCountries: usCa, micCurrencyMap }; + + const lower = adaptEodSymbolDoc( + { + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + Exchange: 'NASDAQ', + Country: 'USA', + Isin: 'us0378331005', + }, + ctx + ); + expect(lower.ok).toBe(true); + if (lower.ok) { + expect(lower.stageARecord.isin).toBe('US0378331005'); + expect(lower.stageARecord.country).toBe('US'); + expect(lower.eodListing.currency).toBe('USD'); + expect(lower.eodListing.mic).toBe('XNAS'); + expect(lower.invalidIdentifiersNulled).toBe(0); + } + + // CA listing, bad ISIN check digit, no CUSIP -> issuer country unknown (never listing Country). + const bad = adaptEodSymbolDoc( + { + eodSearchCode: 'XX.TO', + Code: 'XX', + Exchange: 'TO', + Country: 'Canada', + Isin: 'CA52886N1024', + }, + ctx + ); + expect(bad.ok).toBe(true); + if (bad.ok) { + expect(bad.stageARecord.isin).toBeNull(); + expect(bad.stageARecord.country).toBeNull(); + expect(bad.eodListing.currency).toBe('CAD'); + expect(bad.invalidIdentifiersNulled).toBe(1); + } + }); + + test('IB: issuer country from ISIN beats listing country; CUSIP-only uses doc country; nothing valid gives null', () => { + const ctx = { exchangeLookup: lookup, allowedCountries: usCa }; + + // Irish-domiciled ADR listed in the US. + const ie = adaptIbSymbolDoc( + { + conid: 101, + symbol: 'ACN', + country: 'US', + currency: 'USD', + isin: 'IE00B4BNMY34', + exchangeId: 'NYSE', + }, + ctx + ); + expect(ie.ok && ie.stageARecord.country).toBe('IE'); + expect(ie.ok && ie.ibContract.primaryExchange).toBe('NYSE'); + + const cusipOnly = adaptIbSymbolDoc( + { + conid: 102, + symbol: 'AAPL', + country: 'US', + currency: 'USD', + cusip: '037833100', + exchangeId: 'AEQLIT', + }, + ctx + ); + expect(cusipOnly.ok && cusipOnly.stageARecord.country).toBe('US'); + expect(cusipOnly.ok && cusipOnly.ibContract.primaryExchange).toBeNull(); + + const nothing = adaptIbSymbolDoc( + { + conid: 103, + symbol: 'ZZZ', + country: 'CA', + currency: 'CAD', + isin: 'CATSETEST001', + cusip: '123456780', + }, + ctx + ); + expect(nothing.ok).toBe(true); + if (nothing.ok) { + expect(nothing.stageARecord.country).toBeNull(); + expect(nothing.stageARecord.isin).toBeNull(); + expect(nothing.invalidIdentifiersNulled).toBe(2); + } + + // Fractional conid and boolean conid are classified, not thrown. + expect(adaptIbSymbolDoc({ conid: 1.5, country: 'US' }, ctx)).toEqual({ + ok: false, + skipReason: 'invalidIdentifier', + }); + expect(adaptIbSymbolDoc({ conid: true, country: 'US' }, ctx)).toEqual({ + ok: false, + skipReason: 'invalidFieldType', + }); + expect(adaptIbSymbolDoc({ conid: 5, country: 'US', isin: 42 }, ctx)).toEqual({ + ok: false, + skipReason: 'invalidFieldType', + }); + }); + + test('CEO tickers round-trip through the Stage B parser without double-stripping .TO/.V', () => { + const ctx = { exchangeLookup: lookup, allowedCountries: usCa, micCurrencyMap }; + const cases: Array<[string, string, string, string]> = [ + // symbol, exchange, expected root, expected class suffix + ['BIP.UN.TO', 'TSX', 'BIP', 'UN'], + ['ABC.V', 'CDX', 'ABC', ''], + ['ABC.A.V', 'CDX', 'ABC', 'A'], + ['XYZ.TO.TO', 'TSX', 'XYZ', 'TO'], + ['RCI.B', 'TSX', 'RCI', 'B'], + ]; + for (const [symbol, exchange, root, suffix] of cases) { + const res = adaptCeoSymbolDoc({ ceoId: `ceo-${symbol}`, symbol, exchange }, ctx); + expect(res.ok).toBe(true); + if (!res.ok) { + continue; + } + const reparsed = parseTickerDetailed(res.tickerSource.ticker, 'ceo'); + expect(reparsed).toEqual({ ok: true, tickerRoot: root, classSuffix: suffix }); + expect(res.tickerSource.currency).toBe('CAD'); + } + const aql = adaptCeoSymbolDoc({ ceoId: 'n1', symbol: 'NEO1', exchange: 'aql' }, ctx); + expect(aql.ok && aql.tickerSource.mic).toBe('NEOE'); + }); + + test('CEO span: ceoSpans wins over lastSeen; lastSeen Date gives a single-day span; non-date lastSeen is invalidFieldType', () => { + const base = { exchangeLookup: lookup, allowedCountries: usCa, micCurrencyMap }; + const fromMap = adaptCeoSymbolDoc( + { ceoId: 'c1', symbol: 'RY.TO', exchange: 'TSX', lastSeen: '2024-05-01' }, + { + ...base, + ceoSpans: new Map([['c1', { firstBarDate: '2010-01-04', lastBarDate: '2024-04-30' }]]), + } + ); + expect(fromMap.ok && fromMap.tickerSource.span).toEqual({ + firstBarDate: '2010-01-04', + lastBarDate: '2024-04-30', + }); + + const fromDate = adaptCeoSymbolDoc( + { ceoId: 'c2', symbol: 'RY.TO', exchange: 'TSX', lastSeen: new Date('2024-05-01T12:00:00Z') }, + base + ); + expect(fromDate.ok && fromDate.tickerSource.span).toEqual({ + firstBarDate: '2024-05-01', + lastBarDate: '2024-05-01', + }); + + expect( + adaptCeoSymbolDoc({ ceoId: 'c3', symbol: 'RY', exchange: 'TSX', lastSeen: 12345 }, base) + ).toEqual({ + ok: false, + skipReason: 'invalidFieldType', + }); + }); + + test('QM: composite CCQ venue keeps null MIC and CAD fallback; ATS EDGX keeps routing role', () => { + const ctx = { exchangeLookup: lookup, allowedCountries: usCa, micCurrencyMap }; + const ccq = adaptQmSymbolDoc( + { qmSearchCode: 'RY:CCQ', symbol: 'RY', exchange: 'CCQ TSX' }, + ctx + ); + expect(ccq.ok && ccq.tickerSource).toMatchObject({ + mic: null, + role: 'composite', + currency: 'CAD', + }); + const edgx = adaptQmSymbolDoc( + { qmSearchCode: 'AACT.U:EGX', symbol: 'AACT.U', exchange: 'EDGX', countryCode: 'US' }, + ctx + ); + expect(edgx.ok && edgx.tickerSource).toMatchObject({ + mic: null, + role: 'ats_routing', + currency: 'USD', + }); + }); + + test('eodSymbolChange: Date effective, Country alias, validFrom ordering and NMFQS exclusion', () => { + const ctx = { exchangeLookup: lookup, allowedCountries: usCa }; + const ok = adaptEodSymbolChangeDoc( + { + oldSymbol: 'FB', + newSymbol: 'META', + exchange: 'US', + Country: 'USA', + effective: new Date('2022-06-09T00:00:00Z'), + validFrom: '2012-05-18', + }, + ctx + ); + expect(ok).toEqual({ + ok: true, + symbolChange: { + eodSourceId: 'META.US', + oldTicker: 'FB', + effectiveDate: '2022-06-09', + validFrom: '2012-05-18', + }, + }); + + const caChange = adaptEodSymbolChangeDoc( + { oldSymbol: 'OLD', newSymbol: 'NEW', exchange: 'TO', date: '2021-01-04' }, + ctx + ); + expect(caChange.ok && caChange.symbolChange.eodSourceId).toBe('NEW.TO'); + + expect( + adaptEodSymbolChangeDoc( + { + oldSymbol: 'FB', + newSymbol: 'META', + exchange: 'US', + effective: '2022-06-09', + validFrom: '2022-06-09', + }, + ctx + ) + ).toEqual({ ok: false, skipReason: 'invalidIdentifier' }); + expect( + adaptEodSymbolChangeDoc( + { oldSymbol: 'A', newSymbol: 'B', exchange: 'US', effective: 'not-a-date' }, + ctx + ) + ).toEqual({ + ok: false, + skipReason: 'invalidIdentifier', + }); + expect( + adaptEodSymbolChangeDoc( + { oldSymbol: 'A', newSymbol: 'B', exchange: 'NMFQS', Country: 'US', date: '2020-01-02' }, + ctx + ) + ).toEqual({ + ok: false, + skipReason: 'excludedMutualFund', + }); + expect( + adaptEodSymbolChangeDoc( + { oldSymbol: 'A', newSymbol: 'B', exchange: 'US', effective: 20220609 }, + ctx + ) + ).toEqual({ + ok: false, + skipReason: 'invalidFieldType', + }); + }); + + test('non-object cursor documents are counted as invalidFieldType, not thrown', async () => { + const reader = arrayReader({ + [SOURCE_SYMBOL_COLLECTIONS.ib]: [ + null as unknown as Record, + ['x'] as unknown as Record, + { conid: 7, country: 'US', currency: 'USD' }, + ], + }); + const res = await readIbSymbols(reader, { exchangeLookup: lookup }); + expect(res.stats.docsRead).toBe(3); + expect(res.stats.emitted).toBe(1); + expect(res.stats.skips.invalidFieldType).toBe(2); + assertConservation(res.stats); + }); + + test('readers reject buffered (array / sync iterable) find results with the collection name', async () => { + const buffered: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: (() => + Promise.resolve([ + { eodSearchCode: 'A.US' }, + ])) as unknown as ReadOnlySourceSymbolReader['find'], + }; + await expect(readEodSymbols(buffered, { exchangeLookup: lookup })).rejects.toThrow( + 'eodSymbols' + ); + }); + + test('aggregate entry point refuses a writable reader before issuing any find', async () => { + const reader = arrayReader({}); + const writable = { ...reader, isReadOnly: () => false }; + await expect(readSecurityMasterSources(writable, { exchangeLookup: lookup })).rejects.toThrow( + 'read-only' + ); + expect(reader.calls).toHaveLength(0); + }); + + test('Mongo cursor adapter closes the cursor on mid-stream error and when the client turns writable', async () => { + let closed = 0; + let readOnly = true; + const findCalls: Array<{ name: string; options: SourceSymbolFindOptions | undefined }> = []; + const client: ReadOnlyMongoCollectionClient = { + isReadOnly: () => readOnly, + getCollection: name => ({ + find: (_filter, options) => { + findCalls.push({ name, options }); + return { + async *[Symbol.asyncIterator]() { + yield { eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA' }; + throw new Error('cursor killed'); + }, + close: async () => { + closed += 1; + }, + }; + }, + }), + }; + const reader = createReadOnlyMongoSourceSymbolReader(client); + await expect( + readEodSymbols(reader, { exchangeLookup: lookup, batchSize: 500 }) + ).rejects.toThrow(/eodSymbols.*cursor killed|cursor killed.*eodSymbols/); + expect(closed).toBe(1); + expect(findCalls[0]?.options?.batchSize).toBe(500); + expect(findCalls[0]?.options?.projection?._id).toBe(0); + + readOnly = false; + await expect(readEodSymbols(reader, { exchangeLookup: lookup })).rejects.toThrow('read-only'); + expect(findCalls).toHaveLength(1); + expect(() => createReadOnlyMongoSourceSymbolReader(client)).toThrow('read-only'); + }); +}); diff --git a/test/unit/security-master-source-symbol-readers.test.ts b/test/unit/security-master-source-symbol-readers.test.ts new file mode 100644 index 00000000..a578e728 --- /dev/null +++ b/test/unit/security-master-source-symbol-readers.test.ts @@ -0,0 +1,2006 @@ +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import type { MongoDBClient } from '@stock-bot/mongodb'; +import { BarSpanIndex } from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; +import { cusipToIsin } from '../../apps/stock/data-pipeline/src/normalization/identifiers'; +import { parseTickerDetailed } from '../../apps/stock/data-pipeline/src/normalization/ticker'; +import { + buildSecurityTypeByIsin, + buildSecurityTypeByIsinForStageA, + CEO_SYMBOLS_PROJECTION, + classifySourceExchanges, + compareAscii, + createExchangeSourceLookup, + createReadOnlyMongoSourceSymbolReader, + DEFAULT_SOURCE_COUNTRIES, + EOD_SYMBOL_CHANGE_PROJECTION, + EOD_SYMBOLS_PROJECTION, + EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS, + IB_SYMBOLS_PROJECTION, + ISO_EXCHANGE_SEEDS, + matchInstrumentsStageA, + matchListingsStageB, + normalizeCountryIso2, + normalizeRawExchangeDoc, + QM_SYMBOLS_PROJECTION, + readCeoSymbols, + readEodSymbolChanges, + readEodSymbols, + readIbSymbols, + readQmSymbols, + readSecurityMasterSources, + REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS, + SOURCE_SYMBOL_COLLECTIONS, + type ExchangeSourceMapRow, + type MongoDBClientSourceSymbolReaderCheck, + type ReadOnlyMongoCollectionClient, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type SourceCollectionReadStats, + type SourceSymbolFindOptions, +} from '../../apps/stock/data-pipeline/src/security-master'; + +// Compile-time read-only contract proofs (erased at runtime, verified by `bun run typecheck`). +type AssertExact = [A] extends [B] ? ([B] extends [A] ? true : never) : never; +const _exactReaderKeysCheck: AssertExact = + true; +const _exactCollectionClientKeysCheck: AssertExact< + keyof ReadOnlyMongoCollectionClient, + 'isReadOnly' | 'getCollection' +> = true; +const _mongoClientAssignableCheck: MongoDBClientSourceSymbolReaderCheck = true; +type AssertMongoCollectionAssignable = MongoDBClient extends ReadOnlyMongoCollectionClient + ? true + : never; +const _mongoClientStructuralCheck: AssertMongoCollectionAssignable = true; +// Raw MongoDBClient.find() calls cursor.toArray() (Promise), so it must NOT be +// directly assignable to ReadOnlySourceSymbolReader (which requires incremental AsyncIterable). +type AssertRawMongoFindNotDirectlyAssignable = MongoDBClient extends ReadOnlySourceSymbolReader + ? never + : true; +const _rawMongoFindNotBufferedCheck: AssertRawMongoFindNotDirectlyAssignable = true; + +interface RecordedFindCall { + collectionName: string; + filter: Record | undefined; + options: SourceSymbolFindOptions | undefined; +} + +interface FakeReaderOptions { + readOnly?: boolean; + applyFilterAndProjection?: boolean; + failOnCollection?: { + collection: string; + afterDocs?: number; + errorMessage?: string; + }; +} + +function matchesMongoFilter( + doc: Record, + filter: Record | undefined +): boolean { + if (filter === undefined) { + return true; + } + const entries = Object.entries(filter); + for (let i = 0; i < entries.length; i++) { + const [key, expected] = entries[i]!; + if (key === '$or') { + if (!Array.isArray(expected) || expected.length === 0) { + throw new Error('$or must be a nonempty array'); + } + const matchedAny = expected.some(clause => + matchesMongoFilter(doc, clause as Record) + ); + if (!matchedAny) { + return false; + } + continue; + } + const actual = doc[key]; + if (expected !== null && typeof expected === 'object' && !Array.isArray(expected)) { + const operators = expected as Record; + if ('$in' in operators) { + const list = operators.$in; + if (!Array.isArray(list)) { + return false; + } + if (!list.includes(actual)) { + return false; + } + continue; + } + } + if (actual !== expected) { + return false; + } + } + return true; +} + +function applyMongoProjection( + doc: Record, + projection: Record | undefined +): Record { + if (projection === undefined) { + return { ...doc }; + } + const includedKeys = Object.entries(projection) + .filter(([, flag]) => flag === 1) + .map(([key]) => key); + const out: Record = {}; + for (let i = 0; i < includedKeys.length; i++) { + const key = includedKeys[i]!; + if (key in doc) { + out[key] = doc[key]; + } + } + if (projection._id !== 0 && '_id' in doc) { + out._id = doc._id; + } + return out; +} + +class FakeSourceSymbolReader implements ReadOnlySourceSymbolReader { + public readonly calls: RecordedFindCall[] = []; + private readonly collections: Readonly[]>>; + private readonly readOnly: boolean; + private readonly applyFilterAndProjection: boolean; + private readonly failOnCollection?: FakeReaderOptions['failOnCollection']; + + constructor( + collections: Readonly[]>>, + options: FakeReaderOptions = {} + ) { + this.collections = collections; + this.readOnly = options.readOnly ?? true; + this.applyFilterAndProjection = options.applyFilterAndProjection ?? false; + this.failOnCollection = options.failOnCollection; + } + + isReadOnly(): boolean { + return this.readOnly; + } + + async find = Record>( + collectionName: string, + filter?: Record, + options?: SourceSymbolFindOptions + ): Promise> { + this.calls.push({ collectionName, filter, options }); + + if ( + this.failOnCollection !== undefined && + this.failOnCollection.collection === collectionName && + this.failOnCollection.afterDocs === undefined + ) { + throw new Error(this.failOnCollection.errorMessage ?? 'connection reset by peer'); + } + + const docs = this.collections[collectionName] ?? []; + const failConfig = + this.failOnCollection !== undefined && this.failOnCollection.collection === collectionName + ? this.failOnCollection + : undefined; + const applyQuery = this.applyFilterAndProjection; + const projection = options?.projection; + + return { + async *[Symbol.asyncIterator](): AsyncIterator { + let yielded = 0; + for (const doc of docs) { + if (applyQuery && !matchesMongoFilter(doc, filter)) { + continue; + } + if (failConfig?.afterDocs !== undefined && yielded >= failConfig.afterDocs) { + throw new Error(failConfig.errorMessage ?? 'mid-stream cursor error'); + } + yielded += 1; + yield (applyQuery ? applyMongoProjection(doc, projection) : doc) as T; + } + }, + }; + } +} + +/** + * Builds the Pass 1 exchange lookup strictly through the repo's Pass 1 path + * (`normalizeRawExchangeDoc` -> `classifySourceExchanges` -> `createExchangeSourceLookup`), + * matching live QA MongoDB where `eodExchanges` holds composite `US` + CA venues and + * `qmExchanges` / `ibExchanges` carry zero OperatingMICs. + */ +function createPass1ExchangeLookup(extraRows: readonly ExchangeSourceMapRow[] = []) { + const rawPass1Records = [ + // eodExchanges (US is composite; CA exchanges carry OperatingMIC) + normalizeRawExchangeDoc('eod', { Code: 'US', Name: 'USA Stocks', CountryISO2: 'US', OperatingMIC: 'XNAS, XNYS' }), + normalizeRawExchangeDoc('eod', { Code: 'TO', Name: 'Toronto Exchange', CountryISO2: 'CA', OperatingMIC: 'XTSE' }), + normalizeRawExchangeDoc('eod', { Code: 'V', Name: 'TSX Venture', CountryISO2: 'CA', OperatingMIC: 'XTSX' }), + normalizeRawExchangeDoc('eod', { Code: 'CN', Name: 'CSE', CountryISO2: 'CA', OperatingMIC: 'XCNQ' }), + normalizeRawExchangeDoc('eod', { Code: 'NEO', Name: 'Cboe Canada', CountryISO2: 'CA', OperatingMIC: 'NEOE' }), + // qmExchanges (0% OperatingMIC in QA MongoDB per phase1-investigation.md) + normalizeRawExchangeDoc('qm', { exchange: 'NSQ', exchangeName: 'NASDAQ', countryCode: 'US' }), + normalizeRawExchangeDoc('qm', { exchange: 'NYE', exchangeName: 'NYSE', countryCode: 'US' }), + normalizeRawExchangeDoc('qm', { exchange: 'EDGX', exchangeName: 'Cboe EDGX', countryCode: 'US' }), + normalizeRawExchangeDoc('qm', { exchange: 'TSE', exchangeName: 'TSX', countryCode: 'CA' }), + normalizeRawExchangeDoc('qm', { exchange: 'CNX', exchangeName: 'CSE', countryCode: 'CA' }), + normalizeRawExchangeDoc('qm', { exchange: 'CC', exchangeName: 'CSE Legacy', countryCode: 'CA' }), + // ibExchanges (0% OperatingMIC in QA MongoDB) + normalizeRawExchangeDoc('ib', { id: 'AEQLIT', name: 'Aequitas NEO', country_code: 'CA' }), + normalizeRawExchangeDoc('ib', { id: 'OTCLNKECN', name: 'OTC Link ECN', country_code: 'US' }), + normalizeRawExchangeDoc('ib', { id: 'EDGX', name: 'Cboe EDGX', country_code: 'US' }), + normalizeRawExchangeDoc('ib', { id: 'NYSE', name: 'NYSE', country_code: 'US' }), + // ceoExchanges + normalizeRawExchangeDoc('ceo', { exchange: 'TSX', countryCode: 'CA' }), + normalizeRawExchangeDoc('ceo', { exchange: 'CDX', countryCode: 'CA' }), + normalizeRawExchangeDoc('ceo', { exchange: 'CNQ', countryCode: 'CA' }), + normalizeRawExchangeDoc('ceo', { exchange: 'AQL', countryCode: 'CA' }), + ]; + + const pass1 = classifySourceExchanges(rawPass1Records); + return createExchangeSourceLookup([...pass1.mapped, ...extraRows]); +} + +function sumSkips(stats: SourceCollectionReadStats): number { + return ( + stats.skips.missingId + + stats.skips.invalidFieldType + + stats.skips.invalidIdentifier + + stats.skips.excludedMutualFund + + stats.skips.unmappedExchange + + stats.skips.outOfScopeCountry + ); +} + +function assertStatsConservation(stats: SourceCollectionReadStats): void { + expect(stats.docsRead).toBe(stats.emitted + sumSkips(stats)); +} + +function mulberry32(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) / 4294967296; + }; +} + +function shuffleWithSeed(items: readonly T[], seed: number): T[] { + const copy = items.slice(); + const rand = mulberry32(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rand() * (i + 1)); + const tmp = copy[i]!; + copy[i] = copy[j]!; + copy[j] = tmp; + } + return copy; +} + +describe('security-master source-symbol-readers', () => { + test('read-only proof: interface surface, zero runtime DB/I/O imports, guard, and find-only projections', async () => { + expect(_exactReaderKeysCheck).toBe(true); + expect(_exactCollectionClientKeysCheck).toBe(true); + expect(_mongoClientAssignableCheck).toBe(true); + expect(_mongoClientStructuralCheck).toBe(true); + expect(_rawMongoFindNotBufferedCheck).toBe(true); + + // Static check: source-symbol-readers.ts must not contain runtime DB, fs, or network imports. + const sourcePath = resolve( + import.meta.dir, + '../../apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts' + ); + const sourceText = readFileSync(sourcePath, 'utf8'); + expect(sourceText).toContain("import type { MongoDBClient } from '@stock-bot/mongodb'"); + expect(sourceText).not.toMatch(/^\s*import\s+(?!type\b).*@stock-bot\/mongodb/m); + expect(sourceText).not.toMatch(/from\s+['"](?:node:fs|node:net|node:http|mongodb|pg)['"]/); + + const exchangeLookup = createPass1ExchangeLookup(); + + // Writable reader must fail before issuing any find() call. + const writableReader = new FakeSourceSymbolReader({}, { readOnly: false }); + await expect(readSecurityMasterSources(writableReader, { exchangeLookup })).rejects.toThrow( + /read-only/i + ); + await expect(readEodSymbols(writableReader, { exchangeLookup })).rejects.toThrow(/read-only/i); + await expect(readIbSymbols(writableReader, { exchangeLookup })).rejects.toThrow(/read-only/i); + await expect(readQmSymbols(writableReader, { exchangeLookup })).rejects.toThrow(/read-only/i); + await expect(readCeoSymbols(writableReader, { exchangeLookup })).rejects.toThrow(/read-only/i); + await expect(readEodSymbolChanges(writableReader, { exchangeLookup })).rejects.toThrow( + /read-only/i + ); + expect(writableReader.calls.length).toBe(0); + + // Buffered array result must be rejected at runtime (enforcing incremental streaming). + const bufferingReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: async () => [] as unknown as AsyncIterable, + }; + await expect(readEodSymbols(bufferingReader, { exchangeLookup })).rejects.toThrow(/eodSymbols/); + + // Read-only reader must record strictly find() calls with _id: 0 projections and pushdown filters. + const readOnlyReader = new FakeSourceSymbolReader({}, { readOnly: true }); + await readSecurityMasterSources(readOnlyReader, { exchangeLookup, batchSize: 2000 }); + + expect(readOnlyReader.calls.map(c => c.collectionName)).toEqual([ + SOURCE_SYMBOL_COLLECTIONS.eod, + SOURCE_SYMBOL_COLLECTIONS.ib, + SOURCE_SYMBOL_COLLECTIONS.qm, + SOURCE_SYMBOL_COLLECTIONS.ceo, + SOURCE_SYMBOL_COLLECTIONS.eodSymbolChange, + ]); + + for (const call of readOnlyReader.calls) { + expect(call.options?.projection?._id).toBe(0); + expect(call.options?.batchSize).toBe(2000); + } + + // Verify projections omit bloated blobs and include documented `effective` date field. + expect(QM_SYMBOLS_PROJECTION._id).toBe(0); + expect('profile' in QM_SYMBOLS_PROJECTION).toBe(false); + expect('symbolInfo' in QM_SYMBOLS_PROJECTION).toBe(false); + expect(EOD_SYMBOLS_PROJECTION._id).toBe(0); + expect(EOD_SYMBOLS_PROJECTION.Type).toBe(1); + expect(EOD_SYMBOLS_PROJECTION.type).toBe(1); + expect(IB_SYMBOLS_PROJECTION._id).toBe(0); + expect(CEO_SYMBOLS_PROJECTION._id).toBe(0); + expect(EOD_SYMBOL_CHANGE_PROJECTION._id).toBe(0); + expect(EOD_SYMBOL_CHANGE_PROJECTION.effective).toBe(1); + + // Verify default US + CA country pushdown filters include spellings and venue fallbacks. + expect(DEFAULT_SOURCE_COUNTRIES).toEqual(['US', 'CA']); + expect(readOnlyReader.calls[0]?.filter).toHaveProperty('$or'); + expect(readOnlyReader.calls[1]?.filter).toHaveProperty('$or'); + expect(readOnlyReader.calls[2]?.filter).toHaveProperty('$or'); + expect(readOnlyReader.calls[3]?.filter).toHaveProperty('$or'); + expect(readOnlyReader.calls[4]?.filter).toHaveProperty('$or'); + + // When countries: null, filters must be empty {}. + const unfilteredReader = new FakeSourceSymbolReader({}, { readOnly: true }); + await readSecurityMasterSources(unfilteredReader, { exchangeLookup, countries: null }); + for (const call of unfilteredReader.calls) { + expect(call.filter).toEqual({}); + } + }); + + test('cursor-backed MongoDB adapter streams incrementally via getCollection().find() without toArray() and closes cursors', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + + // Writable client rejected immediately before any getCollection() call. + let writableGetCollectionCalled = false; + const writableClient: ReadOnlyMongoCollectionClient = { + isReadOnly: () => false, + getCollection: () => { + writableGetCollectionCalled = true; + throw new Error('should not be called'); + }, + }; + expect(() => createReadOnlyMongoSourceSymbolReader(writableClient)).toThrow(/read-only/i); + expect(writableGetCollectionCalled).toBe(false); + + // In-memory cursor fixture proving incremental iteration, zero toArray() buffering, and cursor.close(). + const events: string[] = []; + const closedCollections: string[] = []; + const recordedOptions: Array<{ + collection: string; + filter: Record; + options: SourceSymbolFindOptions | undefined; + }> = []; + + const fixtures: Record[]> = { + eodSymbols: [ + { + _id: 'raw-1', + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + eodExchange: 'US', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Name: 'Apple Inc.', + }, + { + _id: 'raw-2', + eodSearchCode: 'RY.TO', + Code: 'RY', + eodExchange: 'TO', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA7800871021', + Name: 'Royal Bank of Canada', + }, + ], + ibSymbols: [], + qmSymbols: [ + { _id: 'qm-1', qmSearchCode: 'VOY:CNX', symbol: 'VOY', exchange: 'CNX', countryCode: 'CA', active: true, profile: { huge: 'blob' } }, + { _id: 'qm-2', qmSearchCode: 'VOY:CC', symbol: 'VOY', exchange: 'CC', countryCode: 'CA', active: false, symbolInfo: { huge: 'blob' } }, + ], + ceoSymbols: [], + eodSymbolChange: [], + }; + + const cursorClient: ReadOnlyMongoCollectionClient = { + isReadOnly: () => true, + getCollection(name: string) { + return { + find(filter: Record, options?: SourceSymbolFindOptions) { + recordedOptions.push({ collection: name, filter, options }); + const docs = fixtures[name] ?? []; + const cursor: ReadOnlySourceSymbolCursor> & { + toArray: () => never; + } = { + toArray() { + throw new Error('toArray() must never be called on streaming cursor path'); + }, + async *[Symbol.asyncIterator]() { + for (let i = 0; i < docs.length; i++) { + const doc = docs[i]!; + if (!matchesMongoFilter(doc, filter)) { + continue; + } + events.push(`yield:${name}:${i}`); + yield applyMongoProjection(doc, options?.projection); + } + }, + async close() { + closedCollections.push(name); + }, + }; + return cursor; + }, + }; + }, + }; + + const reader = createReadOnlyMongoSourceSymbolReader(cursorClient); + const result = await readSecurityMasterSources(reader, { exchangeLookup, batchSize: 500 }); + + expect(result.stats.eodSymbols.emitted).toBe(2); + expect(result.stats.qmSymbols.emitted).toBe(2); + expect(closedCollections).toEqual([ + 'eodSymbols', + 'ibSymbols', + 'qmSymbols', + 'ceoSymbols', + 'eodSymbolChange', + ]); + expect(events).toEqual([ + 'yield:eodSymbols:0', + 'yield:eodSymbols:1', + 'yield:qmSymbols:0', + 'yield:qmSymbols:1', + ]); + for (const rec of recordedOptions) { + expect(rec.options?.projection?._id).toBe(0); + expect(rec.options?.batchSize).toBe(500); + } + + // Cursor must still be closed when an error occurs mid-stream. + let errorCursorClosed = false; + const failingCursorClient: ReadOnlyMongoCollectionClient = { + isReadOnly: () => true, + getCollection() { + return { + find() { + return { + async *[Symbol.asyncIterator]() { + yield { eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA' }; + throw new Error('network interrupted'); + }, + async close() { + errorCursorClosed = true; + }, + }; + }, + }; + }, + }; + const failingReader = createReadOnlyMongoSourceSymbolReader(failingCursorClient); + await expect(readEodSymbols(failingReader, { exchangeLookup })).rejects.toThrow(/eodSymbols/); + expect(errorCursorClosed).toBe(true); + }); + + test('Pass 1 lookup coverage: reviewed US+CA venue rules are valid and Pass 1 path resolves NASDAQ, NYSE, both VOY records, and QM EDGX (AACT.U:EGX)', async () => { + // Structural integrity of REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: + // sorted by (source, sourceCode), zero collisions with explicit baseline, + // primary_venue rows reference ISO_EXCHANGE_SEEDS with matching countryIso, + // and ats_routing/composite rows carry mic: null with US/CA countryIso. + const seedByMic = new Map(ISO_EXCHANGE_SEEDS.map(row => [row.mic, row])); + const explicitKeys = new Set( + EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS.map(row => `${row.source}:${row.sourceCode}`) + ); + for (let i = 0; i < REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS.length; i++) { + const row = REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS[i]!; + expect(explicitKeys.has(`${row.source}:${row.sourceCode}`)).toBe(false); + if (i > 0) { + const prev = REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS[i - 1]!; + const cmp = + compareAscii(prev.source, row.source) || compareAscii(prev.sourceCode, row.sourceCode); + expect(cmp).toBeLessThan(0); + } + if (row.role === 'primary_venue') { + expect(row.mic).not.toBeNull(); + const seed = seedByMic.get(row.mic!); + expect(seed).toBeDefined(); + expect(row.countryIso).toBe(seed?.countryIso); + } else { + expect(row.mic).toBeNull(); + expect(['US', 'CA']).toContain(row.countryIso); + } + expect(row.reviewedBy).toBe('reviewed_us_ca_venues'); + } + + // Build lookup strictly through the repo's Pass 1 path (no hand-built rows). + const exchangeLookup = createPass1ExchangeLookup(); + expect(exchangeLookup.get('eod', 'NASDAQ')?.mic).toBe('XNAS'); + expect(exchangeLookup.get('eod', 'NYSE')?.mic).toBe('XNYS'); + expect(exchangeLookup.get('qm', 'CNX')?.mic).toBe('XCNQ'); + expect(exchangeLookup.get('qm', 'CC')?.mic).toBe('XCNQ'); + expect(exchangeLookup.get('qm', 'EDGX')).toMatchObject({ + role: 'ats_routing', + mic: null, + countryIso: 'US', + }); + expect(exchangeLookup.get('ib', 'EDGX')).toMatchObject({ + role: 'ats_routing', + mic: null, + countryIso: 'US', + }); + expect(exchangeLookup.get('qm', 'NYSE American')).toMatchObject({ + role: 'primary_venue', + mic: 'XASE', + countryIso: 'US', + }); + expect(exchangeLookup.get('qm', 'CCQ TSX')).toMatchObject({ + role: 'composite', + mic: null, + countryIso: 'CA', + }); + expect(exchangeLookup.get('qm', 'CCQ TSXV')).toMatchObject({ + role: 'composite', + mic: null, + countryIso: 'CA', + }); + + const barSpans = new BarSpanIndex(); + barSpans.merge({ source: 'eod', sourceId: 'AAPL.US', firstBarDate: '2010-01-04', lastBarDate: '2025-06-30', barCount: 3900 }); + barSpans.merge({ source: 'eod', sourceId: 'VOY.CN', firstBarDate: '2020-01-03', lastBarDate: '2025-01-03', barCount: 1250 }); + barSpans.merge({ source: 'qm', sourceId: 'AAPL:US', firstBarDate: '2010-01-04', lastBarDate: '2025-06-30', barCount: 3900 }); + barSpans.merge({ source: 'qm', sourceId: 'VOY:CNX', firstBarDate: '2022-01-03', lastBarDate: '2025-01-03', barCount: 750 }); + barSpans.merge({ source: 'qm', sourceId: 'VOY:CC', firstBarDate: '2020-01-03', lastBarDate: '2021-12-31', barCount: 500 }); + barSpans.merge({ source: 'qm', sourceId: 'AACT.U:EGX', firstBarDate: '2023-05-01', lastBarDate: '2025-06-30', barCount: 540 }); + + const reader = new FakeSourceSymbolReader( + { + eodSymbols: [ + { + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + eodExchange: 'US', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Name: 'Apple Inc.', + }, + { + eodSearchCode: 'VOY.CN', + Code: 'VOY', + eodExchange: 'CN', + Exchange: 'CN', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA92919V1085', + Name: 'Voyager Digital Ltd.', + }, + ], + ibSymbols: [ + // Captured phase1-investigation.md:261 shape: SLB with exchangeId='EDGX' (ATS venue) + { + conid: 880001, + symbol: 'SLB', + localSymbol: 'SLB', + exchangeId: 'EDGX', + isin: 'AN8068571086', + cusip: '806857108', + country: 'US', + currency: 'USD', + }, + ], + qmSymbols: [ + { qmSearchCode: 'AAPL:US', symbol: 'AAPL', exchange: 'NSQ', countryCode: 'US', active: true }, + { qmSearchCode: 'VOY:CNX', symbol: 'VOY', exchange: 'CNX', countryCode: 'CA', active: true }, + { qmSearchCode: 'VOY:CC', symbol: 'VOY', exchange: 'CC', countryCode: 'CA', active: false }, + // Captured phase1-investigation.md:272 shape: AACT.U:EGX with exchange='EDGX', countryCode='US' + { qmSearchCode: 'AACT.U:EGX', symbol: 'AACT.U', exchange: 'EDGX', countryCode: 'US', active: true }, + ], + ceoSymbols: [], + eodSymbolChange: [], + }, + { readOnly: true, applyFilterAndProjection: true } + ); + + const sources = await readSecurityMasterSources(reader, { exchangeLookup, barSpans }); + expect(sources.stats.eodSymbols.emitted).toBe(2); + expect(sources.stats.qmSymbols.emitted).toBe(4); + expect(sources.stats.qmSymbols.skips.unmappedExchange).toBe(0); + assertStatsConservation(sources.stats.qmSymbols); + + // IB EDGX ATS must not become primaryExchange. + expect(sources.stageBInput.ibContracts).toEqual([ + { sourceId: '880001', conid: 880001, currency: 'USD', primaryExchange: null }, + ]); + + // AACT.U:EGX reaches Stage B classified as ats_routing (not dropped as unmappedExchange). + const aactQm = sources.stageBInput.tickerSources.find( + t => t.source === 'qm' && t.sourceId === 'AACT.U:EGX' + ); + expect(aactQm).toMatchObject({ + source: 'qm', + sourceId: 'AACT.U:EGX', + ticker: 'AACT.U', + mic: null, + role: 'ats_routing', + currency: 'USD', + }); + + const stageA = matchInstrumentsStageA(sources.stageARecords); + const stageB = matchListingsStageB({ instruments: stageA.instruments, ...sources.stageBInput }); + expect(stageB.conflicts).toEqual([]); + expect( + stageB.unresolved.find(u => u.source === 'qm' && u.sourceId === 'AACT.U:EGX') + ).toMatchObject({ + source: 'qm', + sourceId: 'AACT.U:EGX', + reason: 'ats_routing_venue', + }); + + const qmMappedIds = stageB.providerMappings + .filter(m => m.source === 'qm') + .map(m => m.sourceId) + .sort(compareAscii); + expect(qmMappedIds).toEqual(['AAPL:US', 'VOY:CC', 'VOY:CNX']); + }); + + test('happy path: US, CA domestic, CA interlisted (SHOP), and provider-shaped eodSymbolChange (`effective`) resolve unchanged through Stage A and Stage B', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + const barSpans = new BarSpanIndex(); + barSpans.merge({ source: 'eod', sourceId: 'AAPL.US', firstBarDate: '2000-01-03', lastBarDate: '2025-06-30', barCount: 6400 }); + barSpans.merge({ source: 'eod', sourceId: 'RY.TO', firstBarDate: '2000-01-03', lastBarDate: '2025-06-30', barCount: 6400 }); + barSpans.merge({ source: 'eod', sourceId: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2025-06-30', barCount: 2540 }); + barSpans.merge({ source: 'eod', sourceId: 'SHOP.US', firstBarDate: '2015-05-21', lastBarDate: '2025-06-30', barCount: 2540 }); + barSpans.merge({ source: 'eod', sourceId: 'META.US', firstBarDate: '2012-05-18', lastBarDate: '2025-06-30', barCount: 3300 }); + barSpans.merge({ source: 'qm', sourceId: 'AAPL:US', firstBarDate: '2010-01-04', lastBarDate: '2025-06-30', barCount: 3900 }); + barSpans.merge({ source: 'qm', sourceId: 'RY:CA', firstBarDate: '2010-01-04', lastBarDate: '2025-06-30', barCount: 3900 }); + barSpans.merge({ source: 'qm', sourceId: 'SHOP:CA', firstBarDate: '2015-05-21', lastBarDate: '2025-06-30', barCount: 2540 }); + barSpans.merge({ source: 'qm', sourceId: 'SHOP:US', firstBarDate: '2015-05-21', lastBarDate: '2025-06-30', barCount: 2540 }); + // Pre-effective FB (Facebook, ends 2022-06-08 < effective 2022-06-09) -> MUST resolve to META + barSpans.merge({ source: 'qm', sourceId: 'FB:US', firstBarDate: '2015-01-02', lastBarDate: '2022-06-08', barCount: 1870 }); + // Post-effective FB (2025 ETF reusing ticker FB after 2022-06-09) -> MUST NOT resolve to META + barSpans.merge({ source: 'qm', sourceId: 'FB_ETF:US', firstBarDate: '2025-01-02', lastBarDate: '2025-06-30', barCount: 120 }); + + const reader = new FakeSourceSymbolReader( + { + eodSymbols: [ + { + _id: 'eod-1', + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + eodExchange: 'US', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Cusip: '037833100', + Name: 'Apple Inc.', + }, + { + _id: 'eod-2', + eodSearchCode: 'RY.TO', + Code: 'RY', + eodExchange: 'TO', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA7800871021', + Cusip: '780087102', + Name: 'Royal Bank of Canada', + }, + { + _id: 'eod-3', + eodSearchCode: 'SHOP.TO', + Code: 'SHOP', + eodExchange: 'TO', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA82509L1076', + Cusip: '82509L107', + Name: 'Shopify Inc.', + }, + // CA interlisted share on NYSE: listing Country='USA' differs from issuer country 'CA'. + { + _id: 'eod-4', + eodSearchCode: 'SHOP.US', + Code: 'SHOP', + eodExchange: 'US', + Exchange: 'NYSE', + Country: 'USA', + Currency: 'USD', + Isin: 'CA82509L1076', + Cusip: '82509L107', + Name: 'Shopify Inc.', + }, + { + _id: 'eod-5', + eodSearchCode: 'META.US', + Code: 'META', + eodExchange: 'US', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US30303M1027', + Cusip: '30303M102', + Name: 'Meta Platforms Inc.', + }, + ], + ibSymbols: [ + { + _id: 'ib-1', + conid: 265598, + symbol: 'AAPL', + exchangeId: 'ARCAEDGE', + country: 'US', + currency: 'USD', + isin: 'US0378331005', + cusip: '037833100', + description: 'APPLE INC', + }, + { + _id: 'ib-2', + conid: 4001, + symbol: 'RY', + exchangeId: 'AEQLIT', + country: 'CA', + currency: 'CAD', + isin: 'CA7800871021', + cusip: '780087102', + description: 'ROYAL BANK OF CANADA', + }, + { + _id: 'ib-3', + conid: 199100, + symbol: 'SHOP', + exchangeId: 'AEQLIT', + country: 'CA', + currency: 'CAD', + isin: 'CA82509L1076', + cusip: '82509L107', + description: 'SHOPIFY INC - CLASS A', + }, + { + _id: 'ib-4', + conid: 199101, + symbol: 'SHOP', + exchangeId: 'OTCLNKECN', + country: 'US', + currency: 'USD', + isin: 'CA82509L1076', + cusip: '82509L107', + description: 'SHOPIFY INC - CLASS A', + }, + ], + qmSymbols: [ + { _id: 'qm-1', qmSearchCode: 'AAPL:US', symbol: 'AAPL', exchange: 'NSQ', countryCode: 'US', active: true, profile: { omitted: true } }, + { _id: 'qm-2', qmSearchCode: 'RY:CA', symbol: 'RY', exchange: 'TSE', countryCode: 'CA', active: true }, + { _id: 'qm-3', qmSearchCode: 'SHOP:CA', symbol: 'SHOP', exchange: 'TSE', countryCode: 'CA', active: true }, + { _id: 'qm-4', qmSearchCode: 'SHOP:US', symbol: 'SHOP', exchange: 'NYE', countryCode: 'US', active: true }, + { _id: 'qm-5', qmSearchCode: 'FB:US', symbol: 'FB', exchange: 'NSQ', countryCode: 'US', active: false }, + { _id: 'qm-6', qmSearchCode: 'FB_ETF:US', symbol: 'FB', exchange: 'NSQ', countryCode: 'US', active: true }, + ], + ceoSymbols: [ + { _id: 'ceo-1', ceoId: 'RY', symbol: 'RY.TO', exchange: 'TSX', name: 'Royal Bank', lastSeen: '2025-03-15' }, + { _id: 'ceo-2', ceoId: 'SHOP', symbol: 'SHOP.TO', exchange: 'TSX', name: 'Shopify', lastSeen: '2025-03-15' }, + ], + // Provider-shaped eodSymbolChange doc matching REVIEW.md:71 (`exchange: 'US'`, `effective` date field). + eodSymbolChange: [ + { + _id: 'sc-1', + oldSymbol: 'FB', + newSymbol: 'META', + exchange: 'US', + effective: '2022-06-09', + }, + ], + }, + { readOnly: true, applyFilterAndProjection: true } + ); + + const sources = await readSecurityMasterSources(reader, { exchangeLookup, barSpans }); + + assertStatsConservation(sources.stats.eodSymbols); + assertStatsConservation(sources.stats.ibSymbols); + assertStatsConservation(sources.stats.qmSymbols); + assertStatsConservation(sources.stats.ceoSymbols); + assertStatsConservation(sources.stats.eodSymbolChange); + expect(sources.stats.eodSymbolChange.emitted).toBe(1); + expect(sources.stageBInput.symbolChanges).toEqual([ + { + eodSourceId: 'META.US', + oldTicker: 'FB', + effectiveDate: '2022-06-09', + }, + ]); + + // T-55: SHOP.US Stage A record carries issuer country 'CA', not listing country 'US'. + const shopUsStageA = sources.stageARecords.find( + r => r.source === 'eod' && r.sourceId === 'SHOP.US' + ); + expect(shopUsStageA?.country).toBe('CA'); + + // Feed output unchanged into Stage A and Stage B. + const stageA = matchInstrumentsStageA(sources.stageARecords); + expect(stageA.conflicts).toEqual([]); + expect(stageA.unresolved).toEqual([]); + expect(stageA.instruments.length).toBe(4); // AAPL, RY, SHOP, META + + const shopInstrument = stageA.instruments.find(i => i.primaryIsin === 'CA82509L1076'); + expect(shopInstrument?.issuerCountry).toBe('CA'); + expect(shopInstrument?.members.length).toBe(4); // EOD SHOP.TO, EOD SHOP.US, IB 199100, IB 199101 + + const stageB = matchListingsStageB({ + instruments: stageA.instruments, + ...sources.stageBInput, + }); + expect(stageB.conflicts).toEqual([]); + expect(stageB.listings.length).toBe(5); // AAPL XNAS, RY XTSE, SHOP XTSE CAD, SHOP XNYS USD, META XNAS + + // Interlisted SHOP listings get distinct CAD and USD IB conids. + const shopCadListing = stageB.listings.find( + l => l.primaryIsin === 'CA82509L1076' && l.mic === 'XTSE' && l.currency === 'CAD' + ); + const shopUsdListing = stageB.listings.find( + l => l.primaryIsin === 'CA82509L1076' && l.mic === 'XNYS' && l.currency === 'USD' + ); + expect(shopCadListing?.ibConid).toBe(199100); + expect(shopCadListing?.ibPrimaryExchange).toBeNull(); // AEQLIT ATS never used as primaryExchange + expect(shopUsdListing?.ibConid).toBe(199101); + expect(shopUsdListing?.ibPrimaryExchange).toBeNull(); // OTCLNKECN ATS never used as primaryExchange + + // Historical pre-effective FB:US resolved to META listing via `effective: '2022-06-09'`. + const fbMapping = stageB.providerMappings.find( + m => m.source === 'qm' && m.sourceId === 'FB:US' + ); + expect(fbMapping?.listingKey.primaryIsin).toBe('US30303M1027'); + expect(fbMapping?.listingKey.tickerRoot).toBe('META'); + + // Post-effective FB_ETF:US (2025) must NOT resolve to META — stays unresolved. + expect(stageB.providerMappings.some(m => m.source === 'qm' && m.sourceId === 'FB_ETF:US')).toBe( + false + ); + expect(stageB.unresolved.map(u => `${u.source}:${u.sourceId}`)).toEqual(['qm:FB_ETF:US']); + + // CEO mappings resolved to XTSE listings. + const ceoShopMapping = stageB.providerMappings.find( + m => m.source === 'ceo' && m.sourceId === 'SHOP' + ); + expect(ceoShopMapping?.listingKey.mic).toBe('XTSE'); + expect(ceoShopMapping?.listingKey.tickerRoot).toBe('SHOP'); + }); + + test('query pushdown with filter+projection fake: non-US/CA countries (DE/Germany) and venue fallbacks retain eligible documents', async () => { + const germanLookup = createPass1ExchangeLookup([ + { source: 'eod', sourceCode: 'F', role: 'primary_venue', mic: 'XFRA', countryIso: 'DE', method: 'operating_mic' }, + { source: 'eod', sourceCode: 'XETRA', role: 'primary_venue', mic: 'XETR', countryIso: 'DE', method: 'operating_mic' }, + { source: 'qm', sourceCode: 'FRA', role: 'primary_venue', mic: 'XFRA', countryIso: 'DE', method: 'explicit_rule' }, + ]); + + const reader = new FakeSourceSymbolReader( + { + eodSymbols: [ + // Documented EOD record SVQ.F with full country name 'Germany' + { + _id: 'de-1', + eodSearchCode: 'SVQ.F', + Code: 'SVQ', + Exchange: 'F', + Country: 'Germany', + Currency: 'EUR', + Isin: 'DE0007164600', + Name: 'SAP SE', + }, + // Missing Country/countryCode -> falls back to mapped German venue 'F' + { + _id: 'de-2', + eodSearchCode: 'ADS.F', + Code: 'ADS', + Exchange: 'F', + Currency: 'EUR', + Isin: 'DE000A1EWWW0', + Name: 'Adidas AG', + }, + // Uses countryCode: 'DE' instead of Country + { + _id: 'de-3', + eodSearchCode: 'SIE.XETRA', + Code: 'SIE', + Exchange: 'XETRA', + countryCode: 'DE', + Currency: 'EUR', + Name: 'Siemens AG', + }, + // Out-of-scope US record filtered out by MongoDB query pushdown + { + _id: 'us-1', + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Name: 'Apple Inc.', + }, + ], + ibSymbols: [ + { _id: 'ib-de-1', conid: 90001, symbol: 'SAP', country: 'Germany', currency: 'EUR', isin: 'DE0007164600' }, + { _id: 'ib-de-2', conid: 90002, symbol: 'ADS', countryCode: 'DE', currency: 'EUR', isin: 'DE000A1EWWW0' }, + { _id: 'ib-us-1', conid: 265598, symbol: 'AAPL', country: 'US', currency: 'USD', isin: 'US0378331005' }, + ], + qmSymbols: [ + // Venue fallback when countryCode is absent + { _id: 'qm-de-1', qmSearchCode: 'SAP:FRA', symbol: 'SAP', exchange: 'FRA', currency: 'EUR', profile: { huge: true } }, + // Country spelling 'Germany' + { _id: 'qm-de-2', qmSearchCode: 'ADS:FRA', symbol: 'ADS', exchange: 'FRA', country: 'Germany', currency: 'EUR' }, + // Out-of-scope US record + { _id: 'qm-us-1', qmSearchCode: 'AAPL:US', symbol: 'AAPL', exchange: 'NSQ', countryCode: 'US' }, + ], + ceoSymbols: [], + eodSymbolChange: [ + { _id: 'sc-de-1', oldSymbol: 'OLDDE', newSymbol: 'NEWDE', exchange: 'F', effective: '2024-09-01' }, + { _id: 'sc-us-1', oldSymbol: 'FB', newSymbol: 'META', exchange: 'US', effective: '2022-06-09' }, + ], + }, + { readOnly: true, applyFilterAndProjection: true } + ); + + const result = await readSecurityMasterSources(reader, { + exchangeLookup: germanLookup, + countries: ['DE'], + }); + + // All three eligible German EOD records survive MongoDB query pushdown + projection. + expect(result.stats.eodSymbols.docsRead).toBe(3); + expect(result.stats.eodSymbols.emitted).toBe(3); + expect(result.stageBInput.eodListings.map(l => l.sourceId)).toEqual([ + 'ADS.F', + 'SIE.XETRA', + 'SVQ.F', + ]); + + // Both German IB records (country='Germany' and countryCode='DE') survive. + expect(result.stats.ibSymbols.docsRead).toBe(2); + expect(result.stats.ibSymbols.emitted).toBe(2); + + // Both German QM records (venue fallback and country='Germany') survive. + expect(result.stats.qmSymbols.docsRead).toBe(2); + expect(result.stats.qmSymbols.emitted).toBe(2); + + // German symbol change survives; US symbol change filtered out by pushdown. + expect(result.stats.eodSymbolChange.docsRead).toBe(1); + expect(result.stats.eodSymbolChange.emitted).toBe(1); + expect(result.stageBInput.symbolChanges[0]?.eodSourceId).toBe('NEWDE.F'); + + // Empty countries: [] yields a valid MongoDB filter (never $or: []) and reads 0 docs. + const emptyResult = await readSecurityMasterSources(reader, { + exchangeLookup: germanLookup, + countries: [], + }); + expect(emptyResult.stats.eodSymbols.docsRead).toBe(0); + expect(emptyResult.stats.ibSymbols.docsRead).toBe(0); + + // Regression: a supported `get`-only ExchangeSourceLookup (without getCodesForCountries) + // must use conservative `{}` pushdown so countryless docs (notably stored-shape US + // eodSymbolChange with exchange='US' and effective, no country field) are not dropped + // before the adapter enforces the country filter. + const getOnlyLookup: ExchangeSourceLookup = { + get: (source, sourceCode) => germanLookup.get(source, sourceCode), + }; + const getOnlyReader = new FakeSourceSymbolReader( + { + eodSymbols: [ + { + _id: 'eod-noloc-us', + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + Exchange: 'NASDAQ', + Currency: 'USD', + Isin: 'US0378331005', + Name: 'Apple Inc.', + }, + { + _id: 'eod-noloc-de', + eodSearchCode: 'SVQ.F', + Code: 'SVQ', + Exchange: 'F', + Currency: 'EUR', + Isin: 'DE0007164600', + Name: 'SAP SE', + }, + ], + ibSymbols: [], + qmSymbols: [ + { _id: 'qm-noloc-us', qmSearchCode: 'AAPL:US', symbol: 'AAPL', exchange: 'NSQ' }, + { _id: 'qm-noloc-de', qmSearchCode: 'SAP:FRA', symbol: 'SAP', exchange: 'FRA' }, + ], + ceoSymbols: [ + { _id: 'ceo-noloc-ca', ceoId: 'RY', symbol: 'RY.TO', exchange: 'TSX' }, + ], + eodSymbolChange: [ + { _id: 'sc-us-stored', oldSymbol: 'FB', newSymbol: 'META', exchange: 'US', effective: '2022-06-09' }, + { _id: 'sc-de-stored', oldSymbol: 'OLDDE', newSymbol: 'NEWDE', exchange: 'F', effective: '2024-09-01' }, + ], + }, + { readOnly: true, applyFilterAndProjection: true } + ); + + const getOnlyResult = await readSecurityMasterSources(getOnlyReader, { + exchangeLookup: getOnlyLookup, + }); + + // Conservative `{}` filter used for venue-fallback collections when getCodesForCountries is absent. + const recordedByCollection = new Map(getOnlyReader.calls.map(c => [c.collectionName, c.filter])); + expect(recordedByCollection.get('eodSymbols')).toEqual({}); + expect(recordedByCollection.get('qmSymbols')).toEqual({}); + expect(recordedByCollection.get('ceoSymbols')).toEqual({}); + expect(recordedByCollection.get('eodSymbolChange')).toEqual({}); + + // Stored-shape countryless US symbol change survives; out-of-scope German change is counted by adapter. + expect(getOnlyResult.stats.eodSymbolChange.docsRead).toBe(2); + expect(getOnlyResult.stats.eodSymbolChange.emitted).toBe(1); + expect(getOnlyResult.stats.eodSymbolChange.skips.outOfScopeCountry).toBe(1); + expect(getOnlyResult.stageBInput.symbolChanges).toEqual([ + { + eodSourceId: 'META.US', + oldTicker: 'FB', + effectiveDate: '2022-06-09', + }, + ]); + assertStatsConservation(getOnlyResult.stats.eodSymbolChange); + + // Countryless US/CA EOD, QM, and CEO rows also survive; German rows skipped by adapter. + expect(getOnlyResult.stats.eodSymbols.emitted).toBe(1); + expect(getOnlyResult.stats.eodSymbols.skips.outOfScopeCountry).toBe(1); + expect(getOnlyResult.stats.qmSymbols.emitted).toBe(1); + expect(getOnlyResult.stats.qmSymbols.skips.outOfScopeCountry).toBe(1); + expect(getOnlyResult.stats.ceoSymbols.emitted).toBe(1); + assertStatsConservation(getOnlyResult.stats.eodSymbols); + assertStatsConservation(getOnlyResult.stats.qmSymbols); + assertStatsConservation(getOnlyResult.stats.ceoSymbols); + }); + + test('edge cases: NMFQS exclusion, delisted preservation, IB ATS handling, CEO .TO/.V & double-strip guard, QM duplicates, invalid ISIN/CUSIP recovery', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + const barSpans = new BarSpanIndex(); + barSpans.merge({ source: 'qm', sourceId: 'VOY:CNX', firstBarDate: '2022-01-03', lastBarDate: '2025-01-03', barCount: 750 }); + barSpans.merge({ source: 'qm', sourceId: 'VOY:CC', firstBarDate: '2020-01-03', lastBarDate: '2021-12-31', barCount: 500 }); + + const reader = new FakeSourceSymbolReader({ + eodSymbols: [ + // NMFQS mutual fund must be excluded and counted + { + eodSearchCode: 'VFIAX.US', + Code: 'VFIAX', + eodExchange: 'US', + Exchange: 'NMFQS', + Country: 'USA', + Currency: 'USD', + Isin: 'US9229087104', + Name: 'Vanguard 500 Index Fund', + }, + // Delisted EOD symbol must be preserved + { + eodSearchCode: 'OLDCO.US', + Code: 'OLDCO', + eodExchange: 'US', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'CA52886N1024', // invalid check digit -> nulled, not thrown + Name: 'Old Co Inc.', + delisted: true, + }, + ], + ibSymbols: [ + // IB ATS venue AEQLIT + invalid ISIN CA8131391062 + valid CUSIP 813137106 -> recovers via Stage A tier2_cusip + { + conid: 777001, + symbol: 'SCU.UN', + exchangeId: 'AEQLIT', + country: 'CA', + currency: 'CAD', + isin: 'CA8131391062', + cusip: '813137106', + description: 'SECOND CUP INCOME FUND', + }, + // IB placeholder ISIN CATSETEST001 (invalid ISIN, invalid CUSIP) -> both nulled and counted + { + conid: 777002, + symbol: 'TEST', + exchangeId: 'OTCLNKECN', + country: 'CA', + currency: 'CAD', + isin: 'CATSETEST001', + cusip: 'BAD000000', + description: 'TEST PLACEHOLDER', + }, + // IB primary_venue exchangeId is preserved as primaryExchange + { + conid: 777003, + symbol: 'IBM', + exchangeId: 'NYSE', + country: 'US', + currency: 'USD', + isin: 'US4592001014', + cusip: '459200101', + description: 'IBM CORP', + }, + ], + qmSymbols: [ + // Duplicate (symbol, exchange-mic) pair on CSE: both active VOY:CNX and inactive VOY:CC must survive + { qmSearchCode: 'VOY:CNX', symbol: 'VOY', exchange: 'CNX', countryCode: 'CA', active: true }, + { qmSearchCode: 'VOY:CC', symbol: 'VOY', exchange: 'CC', countryCode: 'CA', active: false }, + ], + ceoSymbols: [ + { ceoId: 'BIP.UN', symbol: 'BIP.UN.TO', exchange: 'TSX', name: 'Brookfield Infra', lastSeen: '2025-05-01' }, + { ceoId: 'A.V', symbol: 'A.V', exchange: 'CDX', name: 'Armor Minerals', lastSeen: '2025-05-01' }, + { ceoId: 'VOY', symbol: 'VOY', exchange: 'CNQ', name: 'Voyager', lastSeen: '2025-05-01' }, + { ceoId: 'NEO1', symbol: 'NEO1', exchange: 'AQL', name: 'Neo Issuer', lastSeen: '2025-05-01' }, + // Double-strip guard: class suffix itself is 'V' with '.V' venue suffix + { ceoId: 'ABC.V', symbol: 'ABC.V.V', exchange: 'CDX', name: 'ABC Class V', lastSeen: '2025-05-01' }, + ], + eodSymbolChange: [], + }); + + const result = await readSecurityMasterSources(reader, { exchangeLookup, barSpans }); + + // NMFQS excluded from both Stage A and Stage B + expect(result.stats.eodSymbols.skips.excludedMutualFund).toBe(1); + expect(result.stats.eodSymbols.emitted).toBe(1); + expect(result.stats.eodSymbols.invalidIdentifiersNulled).toBe(1); + expect(result.stageARecords.some(r => r.sourceId === 'VFIAX.US')).toBe(false); + expect(result.stageBInput.eodListings.some(l => l.sourceId === 'VFIAX.US')).toBe(false); + + // Delisted EOD doc preserved with nulled invalid ISIN + const oldCo = result.stageARecords.find(r => r.source === 'eod' && r.sourceId === 'OLDCO.US'); + expect(oldCo).toBeDefined(); + expect(oldCo?.isin).toBeNull(); + expect(oldCo?.country).toBeNull(); + + // IB ATS handling & invalid ISIN/CUSIP counting + CUSIP recovery in Stage A + expect(result.stats.ibSymbols.emitted).toBe(3); + expect(result.stats.ibSymbols.invalidIdentifiersNulled).toBe(3); // 1 on 777001 + 2 on 777002 + + const ibAts = result.stageBInput.ibContracts.find(c => c.sourceId === '777001'); + expect(ibAts?.primaryExchange).toBeNull(); + const ibOtc = result.stageBInput.ibContracts.find(c => c.sourceId === '777002'); + expect(ibOtc?.primaryExchange).toBeNull(); + const ibNyse = result.stageBInput.ibContracts.find(c => c.sourceId === '777003'); + expect(ibNyse?.primaryExchange).toBe('NYSE'); + + // Stage A recovers 777001 via tier2_cusip (valid CUSIP 813137106 + CA prefix from invalid ISIN) + const stageA = matchInstrumentsStageA(result.stageARecords); + const scuMember = stageA.instruments + .flatMap(i => i.members) + .find(m => m.source === 'ib' && m.sourceId === '777001'); + expect(scuMember?.method).toBe('tier2_cusip'); + + // Duplicate QM (symbol, exchange) pairs both survive with MIC-inferred CAD currency + const qmSources = result.stageBInput.tickerSources.filter(t => t.source === 'qm'); + expect(qmSources.map(q => q.sourceId)).toEqual(['VOY:CC', 'VOY:CNX']); + expect(qmSources[0]?.currency).toBe('CAD'); + expect(qmSources[1]?.currency).toBe('CAD'); + expect(qmSources[0]?.mic).toBe('XCNQ'); + expect(qmSources[1]?.mic).toBe('XCNQ'); + + // CEO exchange mappings TSX/CDX/CNQ/AQL -> XTSE/XTSX/XCNQ/NEOE + .TO/.V parsing + double-strip guard + const ceoById = new Map( + result.stageBInput.tickerSources.filter(t => t.source === 'ceo').map(t => [t.sourceId, t]) + ); + expect(ceoById.get('BIP.UN')).toMatchObject({ mic: 'XTSE', ticker: 'BIP.UN', currency: 'CAD' }); + expect(ceoById.get('A.V')).toMatchObject({ mic: 'XTSX', ticker: 'A', currency: 'CAD' }); + expect(ceoById.get('VOY')).toMatchObject({ mic: 'XCNQ', ticker: 'VOY', currency: 'CAD' }); + expect(ceoById.get('NEO1')).toMatchObject({ mic: 'NEOE', ticker: 'NEO1', currency: 'CAD' }); + + const abcV = ceoById.get('ABC.V'); + expect(abcV?.ticker).toBe('ABC-V'); + expect(parseTickerDetailed(abcV?.ticker, 'ceo')).toEqual({ + ok: true, + tickerRoot: 'ABC', + classSuffix: 'V', + }); + + assertStatsConservation(result.stats.eodSymbols); + assertStatsConservation(result.stats.ibSymbols); + assertStatsConservation(result.stats.qmSymbols); + assertStatsConservation(result.stats.ceoSymbols); + assertStatsConservation(result.stats.eodSymbolChange); + }); + + test('failure modes: missing id, unmapped exchange, non-string fields, out-of-scope country, invalid conid/date, and mid-stream collection errors', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + + const reader = new FakeSourceSymbolReader({ + eodSymbols: [ + { eodSearchCode: ' ', Code: 'X', Exchange: 'NASDAQ', Country: 'USA' }, // missingId + { eodSearchCode: 12345 as unknown as string, Code: 'X', Exchange: 'NASDAQ', Country: 'USA' }, // invalidFieldType + { eodSearchCode: 'SAP.F', Code: 'SAP', Exchange: 'XETRA', Country: 'Germany' }, // outOfScopeCountry + { eodSearchCode: 'UNK.US', Code: 'UNK', Exchange: 'MYSTERY_EX', Country: 'USA' }, // unmappedExchange + { eodSearchCode: 'BADTYPE.US', Code: 999 as unknown as string, Exchange: 'NASDAQ', Country: 'USA' }, // invalidFieldType + { eodSearchCode: 'GOOD.US', Code: 'GOOD', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD' }, // emitted + ], + ibSymbols: [ + { symbol: 'NOID', country: 'US' }, // missingId + { conid: '123' as unknown as number, symbol: 'STR', country: 'US' }, // invalidFieldType + { conid: 0, symbol: 'ZERO', country: 'US' }, // invalidIdentifier + { conid: -42, symbol: 'NEG', country: 'US' }, // invalidIdentifier + { conid: 12.5, symbol: 'FLOAT', country: 'US' }, // invalidIdentifier + { conid: 500, symbol: 'DE', country: 'DE' }, // outOfScopeCountry + { conid: 501, symbol: 123 as unknown as string, country: 'US' }, // invalidFieldType + { conid: 502, symbol: 'OK', country: 'US', currency: 'USD' }, // emitted + ], + qmSymbols: [ + { qmSearchCode: '', symbol: 'A', exchange: 'NSQ', countryCode: 'US' }, // missingId + { qmSearchCode: 'BAD:US', symbol: ['A'] as unknown as string, exchange: 'NSQ', countryCode: 'US' }, // invalidFieldType + { qmSearchCode: 'DE:XET', symbol: 'SAP', exchange: 'XET', countryCode: 'DE' }, // outOfScopeCountry + { qmSearchCode: 'NOEX:US', symbol: 'A', exchange: 'NOEX', countryCode: 'US' }, // unmappedExchange + { qmSearchCode: 'OK:US', symbol: 'OK', exchange: 'NSQ', countryCode: 'US' }, // emitted + ], + ceoSymbols: [ + { ceoId: ' ', symbol: 'A.TO', exchange: 'TSX' }, // missingId + { ceoId: 'BAD', symbol: 'A.TO', exchange: 'TSX', lastSeen: 12345 as unknown as string }, // invalidFieldType + { ceoId: 'UK1', symbol: 'UK1', exchange: 'TSX', countryCode: 'GB' }, // outOfScopeCountry + { ceoId: 'NOEX', symbol: 'NOEX', exchange: 'UNKNOWN' }, // unmappedExchange + { ceoId: 'OK', symbol: 'OK.TO', exchange: 'TSX' }, // emitted + ], + eodSymbolChange: [ + { oldSymbol: '', newSymbol: 'B', exchange: 'NASDAQ', effective: '2024-05-01' }, // missingId + { oldSymbol: 123 as unknown as string, newSymbol: 'B', exchange: 'NASDAQ', effective: '2024-05-01' }, // invalidFieldType + { oldSymbol: 'A', newSymbol: 'B', exchange: 'XETRA', country: 'Germany', effective: '2024-05-01' }, // outOfScopeCountry + { oldSymbol: 'A', newSymbol: 'B', exchange: 'UNKNOWN_EX', effective: '2024-05-01' }, // unmappedExchange + { oldSymbol: 'A', newSymbol: 'B', exchange: 'NASDAQ', effective: '0001-01-01' }, // invalidIdentifier (<= 0001-01-01) + { oldSymbol: 'A', newSymbol: 'B', exchange: 'NASDAQ', effective: 'not-a-date' }, // invalidIdentifier + { oldSymbol: 'A', newSymbol: 'B', exchange: 'NASDAQ', effective: '2024-05-01', validFrom: '2024-05-01' }, // invalidIdentifier (validFrom >= effectiveDate) + { oldSymbol: 'A'.repeat(30), newSymbol: 'B', exchange: 'NASDAQ', effective: '2024-05-01' }, // invalidIdentifier (root > MAX_TICKER_ROOT_LENGTH) + { oldSymbol: 'OLD', newSymbol: 'NEW', exchange: 'US', effective: '2024-05-01' }, // emitted + ], + }); + + const result = await readSecurityMasterSources(reader, { exchangeLookup }); + + expect(result.stats.eodSymbols.skips).toEqual({ + missingId: 1, + invalidFieldType: 2, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 1, + outOfScopeCountry: 1, + }); + expect(result.stats.eodSymbols.emitted).toBe(1); + + expect(result.stats.ibSymbols.skips).toEqual({ + missingId: 1, + invalidFieldType: 2, + invalidIdentifier: 3, + excludedMutualFund: 0, + unmappedExchange: 0, + outOfScopeCountry: 1, + }); + expect(result.stats.ibSymbols.emitted).toBe(1); + + expect(result.stats.qmSymbols.skips).toEqual({ + missingId: 1, + invalidFieldType: 1, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 1, + outOfScopeCountry: 1, + }); + expect(result.stats.qmSymbols.emitted).toBe(1); + + expect(result.stats.ceoSymbols.skips).toEqual({ + missingId: 1, + invalidFieldType: 1, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 1, + outOfScopeCountry: 1, + }); + expect(result.stats.ceoSymbols.emitted).toBe(1); + + expect(result.stats.eodSymbolChange.skips).toEqual({ + missingId: 1, + invalidFieldType: 1, + invalidIdentifier: 4, + excludedMutualFund: 0, + unmappedExchange: 1, + outOfScopeCountry: 1, + }); + expect(result.stats.eodSymbolChange.emitted).toBe(1); + + assertStatsConservation(result.stats.eodSymbols); + assertStatsConservation(result.stats.ibSymbols); + assertStatsConservation(result.stats.qmSymbols); + assertStatsConservation(result.stats.ceoSymbols); + assertStatsConservation(result.stats.eodSymbolChange); + + // Mid-stream error on each of the 5 collections must reject with the collection name in the message. + const collectionNames = Object.values(SOURCE_SYMBOL_COLLECTIONS); + for (const collection of collectionNames) { + const failingReader = new FakeSourceSymbolReader( + { + [collection]: [ + { eodSearchCode: 'A.US', conid: 1, qmSearchCode: 'A:US', ceoId: 'A', oldSymbol: 'A', newSymbol: 'B', exchange: 'US', effective: '2024-05-01' }, + { eodSearchCode: 'B.US', conid: 2, qmSearchCode: 'B:US', ceoId: 'B', oldSymbol: 'C', newSymbol: 'D', exchange: 'US', effective: '2024-05-02' }, + ], + }, + { + readOnly: true, + failOnCollection: { collection, afterDocs: 1, errorMessage: 'socket hang up' }, + } + ); + + await expect( + readSecurityMasterSources(failingReader, { exchangeLookup }) + ).rejects.toThrow(collection); + } + + // Also verify normalizeCountryIso2 aliases directly. + expect(normalizeCountryIso2('United States of America')).toBe('US'); + expect(normalizeCountryIso2('USA')).toBe('US'); + expect(normalizeCountryIso2('Canada')).toBe('CA'); + expect(normalizeCountryIso2('Germany')).toBe('DE'); + expect(normalizeCountryIso2(' ')).toBeNull(); + }); + + test('determinism: shuffling fake-cursor order across seeds yields byte-identical JSON output sorted by (source, sourceId)', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + + const baseCollections = { + eodSymbols: [ + { eodSearchCode: 'Z.US', Code: 'Z', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US98954M1018', Name: 'Zillow', Type: 'Common Stock' }, + { eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US0378331005', Name: 'Apple', Type: 'Common Stock' }, + // Duplicate sourceId with different names to test full tie-breaker determinism + { eodSearchCode: 'DUP.US', Code: 'DUP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Name: 'Dup B', Type: 'ETF' }, + { eodSearchCode: 'DUP.US', Code: 'DUP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Name: 'Dup A', Type: 'ETF' }, + { eodSearchCode: 'RY.TO', Code: 'RY', Exchange: 'TO', Country: 'Canada', Currency: 'CAD', Isin: 'CA7800871021', Name: 'RBC', type: 'Common Stock' }, + ], + ibSymbols: [ + { conid: 900, symbol: 'Z', exchangeId: 'NASDAQ', country: 'US', currency: 'USD', isin: 'US98954M1018' }, + { conid: 100, symbol: 'AAPL', exchangeId: 'ARCAEDGE', country: 'US', currency: 'USD', isin: 'US0378331005' }, + { conid: 200, symbol: 'RY', exchangeId: 'AEQLIT', country: 'CA', currency: 'CAD', isin: 'CA7800871021' }, + ], + qmSymbols: [ + { qmSearchCode: 'Z:US', symbol: 'Z', exchange: 'NSQ', countryCode: 'US' }, + { qmSearchCode: 'AAPL:US', symbol: 'AAPL', exchange: 'NSQ', countryCode: 'US' }, + { qmSearchCode: 'VOY:CNX', symbol: 'VOY', exchange: 'CNX', countryCode: 'CA' }, + { qmSearchCode: 'VOY:CC', symbol: 'VOY', exchange: 'CC', countryCode: 'CA' }, + ], + ceoSymbols: [ + { ceoId: 'SHOP', symbol: 'SHOP.TO', exchange: 'TSX', lastSeen: '2025-01-01' }, + { ceoId: 'A.V', symbol: 'A.V', exchange: 'CDX', lastSeen: '2025-01-02' }, + { ceoId: 'RY', symbol: 'RY.TO', exchange: 'TSX', lastSeen: '2025-01-03' }, + ], + eodSymbolChange: [ + { oldSymbol: 'FB', newSymbol: 'META', exchange: 'US', effective: '2022-06-09' }, + { oldSymbol: 'ANTM', newSymbol: 'ELV', exchange: 'US', effective: '2022-06-28' }, + ], + }; + + const baseline = await readSecurityMasterSources(new FakeSourceSymbolReader(baseCollections), { + exchangeLookup, + }); + const baselineJson = JSON.stringify(baseline); + const baselineTypeEntries = [...baseline.securityTypeByIsin.entries()]; + expect(baselineTypeEntries).toEqual([ + ['CA7800871021', 'common'], + ['US0378331005', 'common'], + ['US98954M1018', 'common'], + ]); + + // Verify (source, sourceId) compareAscii sort order. + for (let i = 1; i < baseline.stageARecords.length; i++) { + const prev = baseline.stageARecords[i - 1]!; + const curr = baseline.stageARecords[i]!; + const cmp = compareAscii(prev.source, curr.source) || compareAscii(prev.sourceId, curr.sourceId); + expect(cmp).toBeLessThanOrEqual(0); + } + for (let i = 1; i < baseline.stageBInput.tickerSources.length; i++) { + const prev = baseline.stageBInput.tickerSources[i - 1]!; + const curr = baseline.stageBInput.tickerSources[i]!; + const cmp = compareAscii(prev.source, curr.source) || compareAscii(prev.sourceId, curr.sourceId); + expect(cmp).toBeLessThanOrEqual(0); + } + + for (const seed of [11, 42, 1337, 99999]) { + const shuffled = { + eodSymbols: shuffleWithSeed(baseCollections.eodSymbols, seed), + ibSymbols: shuffleWithSeed(baseCollections.ibSymbols, seed + 1), + qmSymbols: shuffleWithSeed(baseCollections.qmSymbols, seed + 2), + ceoSymbols: shuffleWithSeed(baseCollections.ceoSymbols, seed + 3), + eodSymbolChange: shuffleWithSeed(baseCollections.eodSymbolChange, seed + 4), + }; + const candidate = await readSecurityMasterSources(new FakeSourceSymbolReader(shuffled), { + exchangeLookup, + }); + expect(JSON.stringify(candidate)).toBe(baselineJson); + expect([...candidate.securityTypeByIsin.entries()]).toEqual(baselineTypeEntries); + } + + // Reversed-input determinism fixture: duplicate rows sharing (sourceId, isin) with distinct + // object/array malformed `Type` values normalize to a single `null` missing-type sentinel so + // `securityTypeRecords` order is cursor-order independent. + const malformedDocs = [ + { + eodSearchCode: 'MALF.US', + Code: 'MALF', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Name: 'Malformed Type Co', + Type: { kind: 'A', nested: 1 } as unknown as string, + }, + { + eodSearchCode: 'MALF.US', + Code: 'MALF', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Name: 'Malformed Type Co', + Type: { kind: 'B', nested: 2 } as unknown as string, + }, + { + eodSearchCode: 'MALF.US', + Code: 'MALF', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Name: 'Malformed Type Co', + Type: ['ETF'] as unknown as string, + }, + ]; + const forwardMalformed = await readSecurityMasterSources( + new FakeSourceSymbolReader({ eodSymbols: malformedDocs }), + { exchangeLookup } + ); + const reversedMalformed = await readSecurityMasterSources( + new FakeSourceSymbolReader({ eodSymbols: [...malformedDocs].reverse() }), + { exchangeLookup } + ); + expect(JSON.stringify(reversedMalformed)).toBe(JSON.stringify(forwardMalformed)); + expect(forwardMalformed.securityTypeRecords).toEqual([ + { isin: 'US0378331005', rawType: null, sourceId: 'MALF.US' }, + { isin: 'US0378331005', rawType: null, sourceId: 'MALF.US' }, + { isin: 'US0378331005', rawType: null, sourceId: 'MALF.US' }, + ]); + expect(forwardMalformed.securityTypeStats.missingType).toBe(3); + }); + + test('security-type wiring & Stage A integration: maps typed EOD docs (including lowercase type and CUSIP-derived ISIN), keeps non-string Type docs, and reports conflicts/unknowns', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + const expectedDerivedCaIsin = cusipToIsin('813137106', 'CA'); + expect(expectedDerivedCaIsin).not.toBeNull(); + + const reader = new FakeSourceSymbolReader( + { + eodSymbols: [ + // Standard Type: 'Common Stock' + { + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Name: 'Apple Inc.', + Type: 'Common Stock', + }, + // Lowercase `type` fallback + { + eodSearchCode: 'SPY.US', + Code: 'SPY', + Exchange: 'NYSE', + Country: 'USA', + Currency: 'USD', + Isin: 'US78462F1030', + Name: 'SPDR S&P 500 ETF', + type: 'etf', + }, + // CUSIP-derived ISIN: bad ISIN check digit with CA prefix + valid CUSIP 813137106 + { + eodSearchCode: 'SCU-UN.TO', + Code: 'SCU-UN', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA8131391062', + Cusip: '813137106', + Name: 'Second Cup Income Fund', + Type: 'Unit', + }, + // Non-string Type must NOT skip the doc (emitted to Stage A/B, counted in missingType) + { + eodSearchCode: 'RY.TO', + Code: 'RY', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA7800871021', + Name: 'Royal Bank of Canada', + Type: 42 as unknown as string, + }, + // Unknown Type ('Mutual Fund') emitted to Stage A/B, omitted from securityTypeByIsin + { + eodSearchCode: 'META.US', + Code: 'META', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US30303M1027', + Name: 'Meta Platforms Inc.', + Type: 'Mutual Fund', + }, + // Conflicting types across two EOD docs sharing the same ISIN (SHOP) + { + eodSearchCode: 'SHOP.TO', + Code: 'SHOP', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA82509L1076', + Name: 'Shopify Inc.', + Type: 'Common Stock', + }, + { + eodSearchCode: 'SHOP.US', + Code: 'SHOP', + Exchange: 'NYSE', + Country: 'USA', + Currency: 'USD', + Isin: 'CA82509L1076', + Name: 'Shopify Inc.', + Type: 'ETF', + }, + ], + ibSymbols: [], + qmSymbols: [], + ceoSymbols: [], + eodSymbolChange: [], + }, + { readOnly: true, applyFilterAndProjection: true } + ); + + const sources = await readSecurityMasterSources(reader, { exchangeLookup }); + + // All 7 EOD docs emitted (non-string Type did NOT trigger invalidFieldType skip). + expect(sources.stats.eodSymbols.docsRead).toBe(7); + expect(sources.stats.eodSymbols.emitted).toBe(7); + expect(sources.stats.eodSymbols.skips.invalidFieldType).toBe(0); + assertStatsConservation(sources.stats.eodSymbols); + + // Check securityTypeByIsin contents and stats. + expect([...sources.securityTypeByIsin.entries()]).toEqual([ + [expectedDerivedCaIsin!, 'unit'], + ['US0378331005', 'common'], + ['US78462F1030', 'etf'], + ]); + expect(sources.unknownSecurityTypes).toEqual([{ rawType: 'Mutual Fund', count: 1 }]); + expect(sources.securityTypeConflicts).toEqual([ + { + isin: 'CA82509L1076', + types: ['common', 'etf'], + sourceIds: ['SHOP.TO', 'SHOP.US'], + recordCount: 2, + }, + ]); + expect(sources.securityTypeStats).toEqual({ + recordsIn: 7, + classified: 5, + missingIsin: 0, + missingType: 1, + unknownType: 1, + distinctClassifiedIsins: 4, + isinsMapped: 3, + isinsConflicting: 1, + conflictsTruncated: 0, + }); + expect(sources.securityTypeLoaderStats).toEqual(sources.securityTypeStats); + + // Feed reader output directly into Stage A and verify every typed non-conflicting EOD instrument + // resolves to an ISIN present in securityTypeByIsin (zero missing_security_type skips in persistSecurityMaster). + const stageA = matchInstrumentsStageA(sources.stageARecords); + expect(stageA.conflicts).toEqual([]); + expect(stageA.unresolved).toEqual([]); + + const stageAIsins = new Set(stageA.instruments.map(i => i.primaryIsin)); + expect(stageAIsins).toEqual( + new Set([ + 'US0378331005', + 'US78462F1030', + expectedDerivedCaIsin!, + 'CA7800871021', + 'US30303M1027', + 'CA82509L1076', + ]) + ); + + const typedNonConflictingIsins = ['US0378331005', 'US78462F1030', expectedDerivedCaIsin!]; + const missingForTyped = stageA.instruments.filter( + inst => + typedNonConflictingIsins.includes(inst.primaryIsin) && + !sources.securityTypeByIsin.has(inst.primaryIsin) + ); + expect(missingForTyped).toEqual([]); + + // Untyped, unknown-typed, and conflicting instruments are omitted from securityTypeByIsin. + expect(sources.securityTypeByIsin.has('CA7800871021')).toBe(false); + expect(sources.securityTypeByIsin.has('US30303M1027')).toBe(false); + expect(sources.securityTypeByIsin.has('CA82509L1076')).toBe(false); + }); + + test('regression: Stage A-quarantined EOD rows cannot veto a valid member type or supply a type, while raw emitted rows remain available for vocabulary diagnostics', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + + const reader = new FakeSourceSymbolReader( + { + eodSymbols: [ + // Valid EOD Common Stock row for AAPL (matching ISIN + CUSIP) + { + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Cusip: '037833100', + Name: 'Apple Inc.', + Type: 'Common Stock', + }, + // Stale EOD ETF row sharing AAPL's valid ISIN but carrying SPY's valid CUSIP -> + // Stage A quarantines as `isin_cusip_mismatch`. Must NOT veto AAPL's 'common' type. + { + eodSearchCode: 'AAPL_STALE.US', + Code: 'AAPL', + Exchange: 'NYSE', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Cusip: '78462F103', + Name: 'Stale Apple ETF Row', + Type: 'ETF', + }, + // Quarantined-only EOD row with an unmapped raw Type -> must NOT supply a type, + // but its raw Type must stay available in `securityTypeRecords` for vocabulary diagnostics. + { + eodSearchCode: 'BAD_ONLY.US', + Code: 'BADO', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US30303M1027', + Cusip: '037833100', + Name: 'Mismatched Meta Row', + Type: 'Structured Note', + }, + // Duplicate EOD sourceId -> Stage A quarantines both as `duplicate_source_id`. + // Must NOT supply a type for CA7800871021. + { + eodSearchCode: 'DUP.TO', + Code: 'RY', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA7800871021', + Name: 'Royal Bank Dup 1', + Type: 'Preferred Stock', + }, + { + eodSearchCode: 'DUP.TO', + Code: 'RY', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA7800871021', + Name: 'Royal Bank Dup 2', + Type: 'Preferred Stock', + }, + ], + ibSymbols: [], + qmSymbols: [], + ceoSymbols: [], + eodSymbolChange: [], + }, + { readOnly: true, applyFilterAndProjection: true } + ); + + const sources = await readSecurityMasterSources(reader, { exchangeLookup }); + assertStatsConservation(sources.stats.eodSymbols); + expect(sources.stats.eodSymbols.docsRead).toBe(5); + expect(sources.stats.eodSymbols.emitted).toBe(5); + + const stageA = matchInstrumentsStageA(sources.stageARecords); + expect(stageA.instruments.map(i => i.primaryIsin)).toEqual(['US0378331005']); + expect(stageA.instruments[0]?.members.map(m => m.sourceId)).toEqual(['AAPL.US']); + expect( + stageA.conflicts.map(c => `${c.sourceId}:${c.conflictKind}`).sort(compareAscii) + ).toEqual([ + 'AAPL_STALE.US:isin_cusip_mismatch', + 'BAD_ONLY.US:isin_cusip_mismatch', + 'DUP.TO:duplicate_source_id', + 'DUP.TO:duplicate_source_id', + ]); + + // Loader-facing map, conflicts, and loader stats reflect ONLY Stage A-accepted EOD members. + expect([...sources.securityTypeByIsin.entries()]).toEqual([['US0378331005', 'common']]); + expect(sources.securityTypeConflicts).toEqual([]); + expect(sources.securityTypeByIsin.has('US30303M1027')).toBe(false); + expect(sources.securityTypeByIsin.has('CA7800871021')).toBe(false); + expect(sources.securityTypeLoaderStats).toEqual({ + recordsIn: 1, + classified: 1, + missingIsin: 0, + missingType: 0, + unknownType: 0, + distinctClassifiedIsins: 1, + isinsMapped: 1, + isinsConflicting: 0, + conflictsTruncated: 0, + }); + + // Returned vocabulary diagnostics (`securityTypeStats` & `unknownSecurityTypes`) cover ALL 5 + // emitted EOD rows directly, including quarantined rows like `Structured Note`. + expect(sources.securityTypeStats).toEqual({ + recordsIn: 5, + classified: 4, + missingIsin: 0, + missingType: 0, + unknownType: 1, + distinctClassifiedIsins: 2, + isinsMapped: 1, + isinsConflicting: 1, + conflictsTruncated: 0, + }); + expect(sources.unknownSecurityTypes).toEqual([{ rawType: 'Structured Note', count: 1 }]); + + // Helper produces the identical loader-facing map when called explicitly after Stage A. + const explicitStageAMap = buildSecurityTypeByIsinForStageA( + sources.securityTypeRecords, + stageA.instruments + ); + expect([...explicitStageAMap.securityTypeByIsin.entries()]).toEqual([ + ...sources.securityTypeByIsin.entries(), + ]); + expect(explicitStageAMap.stats).toEqual(sources.securityTypeLoaderStats); + + // All 5 emitted EOD rows also remain available in `securityTypeRecords` and reconcile with returned diagnostics. + expect(sources.securityTypeRecords.length).toBe(5); + const rawDiagnostics = buildSecurityTypeByIsin(sources.securityTypeRecords); + expect(rawDiagnostics.stats).toEqual(sources.securityTypeStats); + expect(rawDiagnostics.unknownRawTypes).toEqual(sources.unknownSecurityTypes); + }); + + test('local benchmark: >= 368k synthetic docs (300k eod + 50k qm + 18k ib) sustain >= 25,000 docs/s', async () => { + const EOD_COUNT = 300_000; + const QM_COUNT = 50_000; + const IB_COUNT = 18_000; + const TOTAL_DOCS = EOD_COUNT + QM_COUNT + IB_COUNT; + + const exchangeLookup = createPass1ExchangeLookup(); + + // Incremental AsyncIterable fake cursor so benchmark measures streaming reader/adapter + sort + // throughput without pre-allocating 368k raw fixture objects in RAM before timing starts. + const benchmarkReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find>(collectionName: string): AsyncIterable { + if (collectionName === SOURCE_SYMBOL_COLLECTIONS.eod) { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (let i = 0; i < EOD_COUNT; i++) { + const isMutualFund = i % 10 === 0; + const isCa = !isMutualFund && i % 5 === 0; + const doc = { + eodSearchCode: `SYM${i}.${isCa ? 'TO' : 'US'}`, + Code: `SYM${i}`, + eodExchange: isCa ? 'TO' : 'US', + Exchange: isMutualFund ? 'NMFQS' : isCa ? 'TO' : 'NASDAQ', + Country: isCa ? 'Canada' : 'USA', + Currency: isCa ? 'CAD' : 'USD', + Isin: isCa ? 'CA82509L1076' : 'US0378331005', + Name: `Company ${i}`, + }; + yield doc as unknown as T; + } + }, + }; + } + if (collectionName === SOURCE_SYMBOL_COLLECTIONS.qm) { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (let i = 0; i < QM_COUNT; i++) { + const isCa = i % 4 === 0; + const doc = { + qmSearchCode: `SYM${i}:${isCa ? 'CA' : 'US'}`, + symbol: `SYM${i}`, + exchange: isCa ? 'TSE' : 'NSQ', + countryCode: isCa ? 'CA' : 'US', + active: i % 3 !== 0, + }; + yield doc as unknown as T; + } + }, + }; + } + if (collectionName === SOURCE_SYMBOL_COLLECTIONS.ib) { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (let i = 0; i < IB_COUNT; i++) { + const isCa = i % 5 === 0; + const doc = { + conid: 100_000 + i, + symbol: `SYM${i}`, + exchangeId: isCa ? 'AEQLIT' : 'ARCAEDGE', + country: isCa ? 'CA' : 'US', + currency: isCa ? 'CAD' : 'USD', + isin: isCa ? 'CA82509L1076' : 'US0378331005', + cusip: isCa ? '82509L107' : '037833100', + description: `IB COMPANY ${i}`, + }; + yield doc as unknown as T; + } + }, + }; + } + return { + async *[Symbol.asyncIterator](): AsyncIterator { + // empty cursor + }, + }; + }, + }; + + const started = performance.now(); + const result = await readSecurityMasterSources(benchmarkReader, { exchangeLookup }); + const elapsedMs = performance.now() - started; + const docsPerSec = Math.round(TOTAL_DOCS / (elapsedMs / 1000)); + + process.stdout.write( + `[source-symbol-readers benchmark] ${TOTAL_DOCS} docs (eod=${EOD_COUNT}, qm=${QM_COUNT}, ib=${IB_COUNT}) in ${elapsedMs.toFixed(1)} ms (${docsPerSec.toLocaleString('en-US')} docs/s)\n` + ); + + expect(result.stats.eodSymbols.docsRead).toBe(EOD_COUNT); + expect(result.stats.eodSymbols.skips.excludedMutualFund).toBe(EOD_COUNT / 10); + expect(result.stats.qmSymbols.docsRead).toBe(QM_COUNT); + expect(result.stats.ibSymbols.docsRead).toBe(IB_COUNT); + assertStatsConservation(result.stats.eodSymbols); + assertStatsConservation(result.stats.qmSymbols); + assertStatsConservation(result.stats.ibSymbols); + expect(docsPerSec).toBeGreaterThanOrEqual(25_000); + }); +}); + +describe('security-master source-symbol-readers security-type QA edges', () => { + test('Type/type precedence: blank or non-string `Type` falls back to string `type`; string `Type` wins over `type`', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + const base = { Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD' }; + const reader = new FakeSourceSymbolReader( + { + eodSymbols: [ + { ...base, eodSearchCode: 'AAPL.US', Code: 'AAPL', Isin: 'US0378331005', Name: 'Apple', Type: ' ', type: 'Common Stock' }, + { ...base, eodSearchCode: 'SPY.US', Code: 'SPY', Isin: 'US78462F1030', Name: 'SPY', Type: 7, type: 'ETF' }, + { ...base, eodSearchCode: 'Z.US', Code: 'Z', Isin: 'US98954M1018', Name: 'Zillow', Type: 'Common Stock', type: 'ETF' }, + ], + ibSymbols: [], + qmSymbols: [], + ceoSymbols: [], + eodSymbolChange: [], + }, + { readOnly: true, applyFilterAndProjection: true } + ); + + const sources = await readSecurityMasterSources(reader, { exchangeLookup }); + + assertStatsConservation(sources.stats.eodSymbols); + expect(sources.stats.eodSymbols.emitted).toBe(3); + expect([...sources.securityTypeByIsin.entries()]).toEqual([ + ['US0378331005', 'common'], + ['US78462F1030', 'etf'], + ['US98954M1018', 'common'], + ]); + expect(sources.securityTypeStats.missingType).toBe(0); + expect(sources.securityTypeConflicts).toEqual([]); + }); + + test('mixed EOD + IB sources: full-source Stage A EOD members all have a loader type, IB-only instruments are not typed', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + const reader = new FakeSourceSymbolReader( + { + eodSymbols: [ + { eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US0378331005', Name: 'Apple', Type: 'Common Stock' }, + { eodSearchCode: 'SHOP.TO', Code: 'SHOP', Exchange: 'TO', Country: 'Canada', Currency: 'CAD', Isin: 'CA82509L1076', Name: 'Shopify', Type: 'Common Stock' }, + { eodSearchCode: 'SHOP.US', Code: 'SHOP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Isin: 'CA82509L1076', Name: 'Shopify', Type: 'common stock' }, + ], + ibSymbols: [ + { conid: 265598, symbol: 'AAPL', exchangeId: 'NASDAQ', country: 'US', currency: 'USD', isin: 'US0378331005' }, + { conid: 900, symbol: 'Z', exchangeId: 'NASDAQ', country: 'US', currency: 'USD', isin: 'US98954M1018' }, + ], + qmSymbols: [], + ceoSymbols: [], + eodSymbolChange: [], + }, + { readOnly: true, applyFilterAndProjection: true } + ); + + const sources = await readSecurityMasterSources(reader, { exchangeLookup }); + assertStatsConservation(sources.stats.eodSymbols); + assertStatsConservation(sources.stats.ibSymbols); + + // Same Stage A that the orchestrator will run over every source. + const stageA = matchInstrumentsStageA(sources.stageARecords); + const withEodMember = stageA.instruments.filter(inst => inst.members.some(m => m.source === 'eod')); + expect(withEodMember.map(i => i.primaryIsin)).toEqual(['CA82509L1076', 'US0378331005']); + for (const inst of withEodMember) { + expect(sources.securityTypeByIsin.get(inst.primaryIsin)).toBe('common'); + } + // Zillow is IB-only: IB type inference is out of scope, so it stays untyped (no guessing). + expect(stageA.instruments.some(i => i.primaryIsin === 'US98954M1018')).toBe(true); + expect(sources.securityTypeByIsin.has('US98954M1018')).toBe(false); + expect(sources.securityTypeLoaderStats.isinsMapped).toBe(2); + expect(sources.securityTypeLoaderStats.recordsIn).toBe(3); + }); + + test('maxSecurityTypeConflicts option caps loader conflicts and invalid values reject', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + const docs = [ + { eodSearchCode: 'SHOP.TO', Code: 'SHOP', Exchange: 'TO', Country: 'Canada', Currency: 'CAD', Isin: 'CA82509L1076', Name: 'Shopify', Type: 'Common Stock' }, + { eodSearchCode: 'SHOP.US', Code: 'SHOP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Isin: 'CA82509L1076', Name: 'Shopify', Type: 'ETF' }, + { eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US0378331005', Name: 'Apple', Type: 'Common Stock' }, + { eodSearchCode: 'AAPL.NEO', Code: 'AAPL', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Isin: 'US0378331005', Name: 'Apple', Type: 'CDR' }, + ]; + const make = () => + new FakeSourceSymbolReader( + { eodSymbols: docs, ibSymbols: [], qmSymbols: [], ceoSymbols: [], eodSymbolChange: [] }, + { readOnly: true, applyFilterAndProjection: true } + ); + + const capped = await readSecurityMasterSources(make(), { exchangeLookup, maxSecurityTypeConflicts: 1 }); + expect(capped.securityTypeByIsin.size).toBe(0); + expect(capped.securityTypeConflicts.map(c => c.isin)).toEqual(['CA82509L1076']); + expect(capped.securityTypeLoaderStats.isinsConflicting).toBe(2); + expect(capped.securityTypeLoaderStats.conflictsTruncated).toBe(1); + + await expect( + readSecurityMasterSources(make(), { exchangeLookup, maxSecurityTypeConflicts: -1 }) + ).rejects.toThrow(RangeError); + }); + + test('readEodSymbols on an empty collection returns an empty map and zeroed stats', async () => { + const reader = new FakeSourceSymbolReader( + { eodSymbols: [] }, + { readOnly: true, applyFilterAndProjection: true } + ); + const result = await readEodSymbols(reader, { exchangeLookup: createPass1ExchangeLookup() }); + expect(result.securityTypeByIsin.size).toBe(0); + expect(result.securityTypeRecords).toEqual([]); + expect(result.unknownSecurityTypes).toEqual([]); + expect(result.securityTypeConflicts).toEqual([]); + expect(result.securityTypeStats.recordsIn).toBe(0); + expect(result.securityTypeLoaderStats.recordsIn).toBe(0); + assertStatsConservation(result.stats); + }); +}); diff --git a/tools/curate-etl/Cargo.toml b/tools/curate-etl/Cargo.toml index 39a39fe6..f397feb3 100644 --- a/tools/curate-etl/Cargo.toml +++ b/tools/curate-etl/Cargo.toml @@ -6,3 +6,5 @@ authors.workspace = true license.workspace = true [dependencies] +parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] } + diff --git a/tools/curate-etl/README.md b/tools/curate-etl/README.md index 9f4ab826..f067bedc 100644 --- a/tools/curate-etl/README.md +++ b/tools/curate-etl/README.md @@ -1,6 +1,6 @@ # `curate-etl` -Dedicated zero-dependency Rust crate for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, and the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check. +Dedicated Rust crate (single direct dependency: `parquet` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, and the `M1.2i` streaming Zstd Parquet writer for `bars_1d`. ## Scope & Sign Conventions @@ -74,6 +74,144 @@ Rules: - `volume_checked + volume_unchecked == rows_out` and `volume_within_tolerance + volume_mismatched == volume_checked` - `qm_rows_in == qm_unique_partners + qm_invalid_volume_dropped + qm_duplicate_collapsed + qm_duplicate_conflict_dropped` +## `fx_1d` Builder (`M1.2e`) + +`build_fx_1d` (`src/fx.rs`) merges `CAD.FOREX` daily bars (`FxSource::EodCadForex`, `"eod_cad_forex"`, 1971–2025) and `teMarketData.USDCAD` daily bars (`FxSource::TeUsdCad`, `"te_usdcad"`, through 2026+) into a single sorted, unique `USDCAD` series (`Fx1dRow`) matching the `fx_1d/part.parquet` value columns in `design/DATA-CONTRACTS.md` (excluding `ts`/`known_at` timestamps, which belong to the later writer task). + +Rules: +1. **Quote convention:** Both inputs are USD/CAD quotes (CAD per 1 USD); no inversion is performed in this module (`CADUSD.FOREX` inversion is out of scope). +2. **Per-source filtering (strict priority, never panics or aborts):** + - `dropped_invalid_ohlc`: any OHLC field non-finite or `<= 0.0`. + - `dropped_inconsistent_ohlc`: `high < low`, or `open`/`close` outside `[low, high]`. +3. **Per-source deduplication on `session_date`:** Bitwise-identical duplicates collapse to one (`duplicate_collapsed += n - 1`); conflicting duplicate groups drop entirely (`duplicate_conflict_dropped += n`). +4. **Merge precedence:** `EodCadForex` wins on overlapping dates (`te_superseded_by_eod += 1`); `TeUsdCad` fills interior gaps and all dates after EOD's last date (as well as dates where EOD dropped an invalid or conflicting group). +5. **Read-only overlap cross-check:** On every date where both sources survive, evaluates `|eod.close - te.close| / eod.close <= FX_OVERLAP_REL_TOLERANCE` (`0.01`, 1% inclusive with a small IEEE-754 rounding slack so exact decimal 1% pairs like `1.4000` vs. `1.4140` are not falsely flagged), counts `overlap_checked`, `overlap_within_tolerance`, and `overlap_mismatched`, and tracks raw `max_overlap_rel` without modifying emitted rows. +6. **No-look-ahead lookup (`fx_rate_on_or_before`):** Binary-searches sorted `Fx1dRow` slices for the latest row with `session_date <= date` and `date - session_date <= max_stale_days`. Carries forward across weekends/holidays within `max_stale_days`, returns `None` before the first row or when stale, and never returns a later date. +7. **Determinism & accounting invariants:** Any permutation of `eod` or `te` yields bitwise-identical `rows` and `stats`, and: + - Per source: `rows_in == rows_kept + dropped_invalid_ohlc + dropped_inconsistent_ohlc + duplicate_collapsed + duplicate_conflict_dropped` + - Merge: `rows_out == eod.rows_kept + te.rows_kept - te_superseded_by_eod == eod_rows_out + te_rows_out` + - Overlap: `overlap_within_tolerance + overlap_mismatched == overlap_checked == te_superseded_by_eod` + +Deferred out of `src/fx.rs`: `ts`/`known_at` timestamp derivation (later writer task), `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring FX into `src/adj.rs` cross-currency dividends. + +## `shorts` Builder (`M1.2f`) + +`build_shorts` (`src/shorts.rs`) turns raw `ceoShorts` semi-monthly short-interest report rows (`CeoShortReport`) into sorted, unique per-`(key, report_date)` point-in-time `ShortRow` rows matching `shorts/part.parquet` in `design/DATA-CONTRACTS.md` (`listing_id, report_date, known_at, shares_short, net_change, pct_float, source`). + +Rules: +1. **Canadian TSX business-day calendar (`2008-01-01..=2030-12-31`):** + - `is_canadian_business_day(epoch_day)` and `add_canadian_business_days(epoch_day, n)` cover `MIN_SUPPORTED_YEAR = 2008` through `MAX_SUPPORTED_YEAR = 2030` (`MIN_SUPPORTED_DATE = 13_879` ..= `MAX_SUPPORTED_DATE = 22_279`), strictly covering the `2017-01-01..=2027-12-31` dataset window plus year-end `+4` business-day rollovers. Dates outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` (or stepping past `MAX_SUPPORTED_DATE`) return `ShortsError::DateOutOfRange` rather than guessing or panicking. + - Non-business days: Saturdays, Sundays, and the 9 TSX market holidays: + 1. **New Year's Day** (Jan 1; Sat → Mon Jan 3, Sun → Mon Jan 2) + 2. **Family Day** (3rd Monday of February, TSX holiday since 2008) + 3. **Good Friday** (computed Gregorian Easter Sunday − 2 days) + 4. **Victoria Day** (Monday strictly before May 25) + 5. **Canada Day** (Jul 1; Sat → Mon Jul 3, Sun → Mon Jul 2) + 6. **Civic Holiday** (1st Monday of August) + 7. **Labour Day** (1st Monday of September) + 8. **Thanksgiving** (2nd Monday of October) + 9. **Christmas Day & Boxing Day** (Mon–Thu → Dec 25/26; Fri → Dec 25 & Mon Dec 28; Sat → Mon Dec 27 & Tue Dec 28; Sun → Mon Dec 26 & Tue Dec 27) + - Federal holidays where TSX remains open (National Day for Truth and Reconciliation on Sept 30 and Remembrance Day on Nov 11) are treated as normal TSX business days. + - When `report_date` itself falls on a non-business day (e.g. a Saturday month-end), `add_canadian_business_days(report_date, 4)` counts strictly forward so `known_at_date` is the 4th TSX business day strictly after `report_date` (`known_at_date > report_date` always holds). +2. **`America/Toronto` ET → UTC DST conversion (`et_to_utc_micros`):** + - Applies North American post-2007 DST rules (2nd Sunday of March 02:00 → 1st Sunday of November 02:00 = EDT `UTC-4`, otherwise EST `UTC-5`). + - `known_at_utc_micros` is `17:00:00 America/Toronto` on `known_at_date` (`21:00:00 UTC` in EDT, `22:00:00 UTC` in EST). + - Rejects out-of-range dates (`DateOutOfRange`), invalid wall-clock components (`InvalidLocalTime`), spring-forward nonexistent times `02:00..03:00` (`NonexistentLocalTime`), and fall-back ambiguous times `01:00..02:00` (`AmbiguousLocalTime`). + - Exposed publicly alongside `epoch_days_to_ymd` so the upcoming `events` builder (`16:05 ET` lag) can reuse it directly. +3. **Bad-row resilience, sanitization, and deduplication:** + - Every input row's `report_date + 4` business days is validated first so out-of-range dates fail deterministically with `ShortsError::DateOutOfRange` regardless of row order or bad numeric fields. + - Non-finite or negative `shares_short` rows are dropped and counted in `dropped_invalid_shares_short` (without incrementing optional-field null counters); `-0.0` is normalized to `0.0`. + - Non-finite `net_change` and `pct_float` values are sanitized to `None` and counted in `nulled_invalid_net_change` and `nulled_invalid_pct_float`; `-0.0` is normalized to `0.0`. + - Bitwise-identical duplicates on `(key, report_date)` collapse (`duplicate_collapsed += n - 1`); conflicting duplicate groups drop entirely (`duplicate_conflict_dropped += n`). + - Every emitted row carries `source = "ceo_shorts"`, `known_at_date > report_date`, and is strictly sorted by `(key, report_date)`. +4. **Determinism & accounting invariants:** + - Any input permutation yields bitwise-identical `rows` and `stats`. + - `rows_in == rows_out + dropped_invalid_shares_short + duplicate_collapsed + duplicate_conflict_dropped`. +5. **CIRO publication-lag note:** The `+4` Canadian business-day `17:00 ET` rule is the locked contract proxy from `design/DATA-CONTRACTS.md` (not an observed CIRO scrape timestamp). Downstream signal studies should still run `+1` business-day lag stress tests around holidays and month-end boundaries. + +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). + +## `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. + +Rules: +1. **Filing timestamps (`kind = "filing"`):** + - `parse_filing_timefiled` strictly parses `YYYY-MM-DDTHH:MM:SS EST` (`UTC-5`) and `YYYY-MM-DDTHH:MM:SS EDT` (`UTC-4`). Using the explicit abbreviation's fixed offset avoids DST calendar range limits so pre-2008 filings convert cleanly. + - Emits `ts_micros = known_at_micros = UTC(timefiled)` and `known_at_source = "filing_timestamp"`. + - Malformed strings (`filings_skipped_malformed_timestamp`), missing/unknown zones such as `PST`/`UTC`/`Z` (`filings_skipped_unknown_zone`), and invalid calendar dates or wall-clock times (`filings_skipped_invalid_date_time`) are skipped and counted without panicking. + - *Provenance caveat:* EDGAR filings accepted after `17:30 ET` are converted directly to UTC without next-business-day shifting (per the M1.2g contract); downstream intraday studies should apply exchange-session routing and post-`17:30 ET` visibility rules on top of `known_at_micros`. +2. **Table-driven form groups & periodic-report predicate (`classify_form_type`, `is_periodic_financial_report`):** + - Exact EDGAR codes (checked after stripping optional `/A` and standalone `Amended` markers such as `10-K (Amended)` so `"4"` never matches `"40-F"`, `"424B5"`, or `"45-106F1"`): `10-K` (`"10-k"`), `10-Q` (`"10-q"`), `8-K` (`"8-k"`), `4` (`"4"`), `144` (`"144"`), `40-F` (`"40-f"`). + - SEDAR+ substring rules in fixed priority order: `Interim financial statements/report` (`"interim_financial_statements"`), `Annual financial statements` (`"annual_financial_statements"`), `MD&A` (`"mda"`), `52-109` (`"52-109"`), `NI 43-101` (`"ni_43_101"`), `45-106F1` (`"45-106f1"`), `News release` (`"news_release"`). Everything else maps to `"other"`. + - Amendments (`/A` or standalone `"amended"`) map to the same group with `is_amendment: true` and the raw `form_type` preserved in `payload_json`. + - `is_periodic_financial_report` is `true` only for `10-K`, `10-Q`, `40-F`, `Interim financial statements`, and `Annual financial statements` (for the M2 `fundamentals_pit` filing join). +3. **Earnings linking & conservative `16:05 ET` lag (`kind = "earnings"`):** + - Precedence: + 1. If the same `key` has a qualifying filing (`8-K` or `News release`, including amendments) whose local ET calendar date matches `report_date` (including late-evening ET filings whose UTC date is the next day), `known_at_micros` = earliest such filing's UTC timestamp (`known_at_source = "filing_timestamp"`, deterministic tie-break on `(filing_id, form_type, url)`). + 2. Otherwise `known_at_micros = report_date 16:05:00 America/Toronto` via `shorts::et_to_utc_micros` (`known_at_source = "statutory_lag_estimate"`). This fallback is intended for T+1 open use (not same-day intraday cutoffs, since a later same-date `8-K` or `News release` filing supersedes the fallback with its actual filing timestamp). It applies to `N/A`, `BTO`, and `AMC` alike whenever no linked filing provides a real timestamp—unlinked `BTO`/`AMC` rows are never stamped earlier than `16:05 ET`. + 3. Unlinked `report_date` values outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` (`2008-01-01..=2030-12-31`) are skipped and counted in `earnings_skipped_out_of_range` (pre-2008 dates with a linked same-day filing still succeed). + - `ts_micros = known_at_micros`; `subtype` = normalized announce time (`"bto"` / `"amc"` / `"unknown"`). + - Post-hoc overwritten `consensusEps` is deliberately omitted from `QmEarning` and `payload_json` per `design/DATA-CONTRACTS.md` §1. +4. **Payload JSON, deduplication, sorting & accounting:** + - Hand-written `std`-only RFC 8259 JSON encoder with strict string escaping, non-ASCII UTF-8 passthrough, stable key order, `-0.0` normalized to `0`, and non-finite `f64` (`NaN`/`±inf`) emitted as `null`. + - Exact duplicate filings collapse (`filings_duplicate_collapsed`); identical normalized `(key, report_date)` earnings collapse (`earnings_duplicate_collapsed`) and conflicting `(key, report_date)` groups drop entirely (`earnings_duplicate_conflict_dropped`). + - Output rows are sorted deterministically by `(key, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)` and `EventsStats` reconciles exactly per kind (`filings_in == filings_out + skips + dup`, `earnings_in == earnings_out + oor + dup + conflict`, `earnings_out == linked + lagged`, `rows_out == filings_out + earnings_out`). + +Deferred out of `src/events.rs`: MongoDB `qmFilings` / `qmEarnings` BSON cursors, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, and M2 `fundamentals_pit` joins. + +## `provider_mapping` Table (`M1.2h`) + +`ProviderMappingTable` (`src/provider_mapping.rs`) is a pure, zero-allocation in-RAM lookup table resolving `(source, source_id, bar_date)` to a permanent `listing_id: i32` over inclusive date ranges, mirroring `provider_mapping` in `database/postgres/init/34-security-master.sql`. + +Rules: +1. **Inclusive date ranges & open-ended active spans:** `valid_from` and `valid_to` are UTC Gregorian epoch days (`split::ymd_to_epoch_days`). `valid_to = Some(d)` is inclusive (`valid_from <= bar_date <= d`); `valid_to = None` is open-ended (`bar_date >= valid_from`). Unknown keys, dates before the first range, interior gap dates (e.g., ticker reuse `FB.US` `2012-05-18..=2022-06-08` → `2025-01-02..`), and dates after a closed last range return `None`. +2. **Verbatim key storage (no trimming):** Empty or whitespace-only `source` / `source_id` strings return `EmptySource` / `EmptySourceId`, but non-empty strings with leading or trailing whitespace are stored and matched verbatim (never trimmed or merged with unspaced IDs). +3. **Strict PostgreSQL PK & overlap validation (`from_rows`):** + - Rejects `listing_id <= 0` (`InvalidListingId`) and `valid_to < valid_from` (`InvalidRange`). + - **Exact-duplicate policy:** Every duplicate `(source, source_id, valid_from)`—including bitwise-identical duplicate rows—is rejected with `DuplicateValidFrom`, matching the PostgreSQL `PRIMARY KEY (source, source_id, valid_from)` constraint. + - Rejects intersecting inclusive ranges (including touching endpoints `prev.valid_to == curr.valid_from` and any open-ended range followed by a later range) with `OverlappingRanges`. Adjacent ranges (`prev.valid_to = d`, `curr.valid_from = d + 1`) are accepted, and boundary checks avoid `valid_to + 1` overflow at `i32::MAX`. + - Deterministic for any input row permutation. +4. **Zero-allocation lookups & sorted-stream cursor:** + - `resolve(source, source_id, bar_date)` and `ranges_for(source, source_id)` perform zero heap allocations: all `MappingRange`s live in a single contiguous `Vec` arena indexed by a sorted per-source `HashMap` (linear scan for `<= 8` sources, binary search otherwise) plus binary search over the key's ranges. + - `ProviderMappingCursor` (via `cursor_for(source, source_id)` or `ProviderMappingCursor::new(ranges)`) resolves ascending `bar_date` streams for a single key in amortised O(1), automatically falling back to binary search on out-of-order probes so its output always matches `ProviderMappingTable::resolve` identically. + +## `bars_1d` Parquet Writer (`M1.2i`) + +`write_bars_1d_dataset` (`src/parquet_bars.rs`) streams strictly ascending `(listing_id, session_date)` `Bars1dParquetRow` records into Zstd-compressed, year-partitioned Parquet files matching `design/DATA-CONTRACTS.md` (§3A). + +1. **Exact 12-column contract schema (`bars_1d_parquet_schema`):** + - `listing_id` (`INT32`, `REQUIRED`) + - `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + - `session_date` (`INT32`, `REQUIRED`, `DATE`) + - `open`, `high`, `low`, `close`, `volume` (`DOUBLE`, `REQUIRED`) + - `vwap` (`DOUBLE`, `OPTIONAL`) + - `currency`, `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`, dictionary-encoded) + - `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +2. **Partition layout & compression:** + - Writes `/bars_1d/year=YYYY/part.parquet` lazily per observed `session_date` calendar year (`1900..=2200`); empty input and empty years create no directories or files. + - Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `Bars1dWriteOptions::zstd_level`). + - Bounded streaming buffers (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `Bars1dWriteOptions::row_group_rows`): each active year buffers at most one row group of columnar data (with string interning for `currency`/`source`), flushing and clearing buffers on every row-group boundary. + - Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files. +3. **Sort, concurrency & atomicity rules:** + - Input must already be sorted strictly ascending by `(listing_id, session_date)`; within each year file rows remain in `(listing_id, session_date)` order. + - Concurrent writers targeting the same `/bars_1d` directory are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (30 s default timeout returning `ParquetBarsError::LockTimeout` with the lock path if a crashed process left a stale lock behind). Every year partition writes to an exclusively created per-run staging file (`part.parquet..tmp`), flushes, and calls `File::sync_all()` before publication. During 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, all open writers are dropped, replaced partitions are restored from backup, newly published partitions are removed (reporting any rollback failures alongside the original error via `RollbackFailed`), and only staging files owned by the current run are unlinked. +4. **Typed errors (`ParquetBarsError`):** + - `InvalidRowGroupRows` (`row_group_rows == 0`) + - `InvalidZstdLevel { level }` + - `UnsortedInput { prev_listing_id, prev_session_date, listing_id, session_date }` + - `DuplicateKey { listing_id, session_date }` + - `SessionYearOutOfRange { listing_id, session_date, year, min_year, max_year }` + - `LockTimeout { path, waited }` + - `RollbackFailed { cause, failures }` + - `Io { path, source }` + - `Parquet { path, source }` +5. **Measured baseline (`2026-11-28`):** + - Command: `cargo run --release -p curate-etl --offline -- bench-parquet-bars` + - Input: `rows=5000000`, `listings=2000`, `raw_row_bytes=84` (20 years `2006..=2025`) + - Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000` + - Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` + ## Local Benchmarks ### `bench-split` @@ -131,13 +269,85 @@ Command: `cargo run --release -p curate-etl --offline -- bench-bars` - Build: `rows_out=9488072`, `keys_out=20000`, `elapsed=842.38 ms`, `throughput=11871057 rows/s`, `latency=84.24 ns/row`, `checksum=0x25fae7ad0816891b` (identical across back-to-back runs) - Stats: `invalid_ohlc=20006`, `inconsistent_ohlc=19818`, `invalid_vol=19812`, `dup_collapsed=47627`, `dup_conflict=404665`, `checked=4721305`, `within_tol=4673885`, `mismatched=47420`, `unchecked=4766767`, `max_rel_diff=0.130435`, `samples=100` -## Deferred Follow-Ups (`M1.2e+` / `M2`) +### `bench-fx` -This crate currently uses `std` only so it builds strictly offline. Follow-up tasks (IO wiring and crates.io dependencies) will add: +Fixed-seed (`std`-only SplitMix64) benchmark over ~20,000 daily USD/CAD rows (~80% `CAD.FOREX`, ~20% `teMarketData.USDCAD` with an overlap window, interior gaps, post-EOD tail, injected bad/duplicate rows, and ~5% overlap mismatches), timing `build_fx_1d` plus `1,000,000` zero-allocation `fx_rate_on_or_before` lookups: -- `bars_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata -- `year=YYYY` partitioning, Zstd-compressed Parquet writer for curated daily/intraday datasets, and `qmPrices` OHLC cross-check +```bash +cargo run --release -p curate-etl --offline -- bench-fx [rows] +``` + +Command: `cargo run --release -p curate-etl --offline -- bench-fx` + +- Input: `rows=20000`, `eod_rows=16000`, `te_rows=4000` +- Build: `rows_out=17172`, `eod_out=15336`, `te_out=1836`, `elapsed=0.741 ms`, `throughput=26993285 rows/s`, `latency=37.05 ns/row` +- Lookup: `lookups=1000000`, `hits=999224`, `elapsed=25.68 ms`, `throughput=38946650 lookups/s`, `latency=25.68 ns/lookup`, `checksum=0x21e746bd53f3e7ff` (identical across back-to-back runs) +- Stats: `eod_invalid=164`, `eod_inconsistent=170`, `eod_dup_collapsed=165`, `eod_dup_conflict=165`, `te_invalid=21`, `te_inconsistent=23`, `te_dup_collapsed=21`, `te_dup_conflict=34`, `te_superseded=2065`, `overlap_checked=2065`, `within_tol=1954`, `mismatched=111`, `max_overlap_rel=0.025000` + +### `bench-shorts` + +Fixed-seed (`std`-only SplitMix64) benchmark over `700,000` synthetic `ceoShorts` report rows across `12,500` `i32` `listing_id` keys on semi-monthly (15th and month-end) dates spanning `2017-04-15..=2026-04-30` with injected negative/NaN `shares_short`, non-finite optional fields, identical duplicates, and conflicting duplicates, timing only `build_shorts`: + +```bash +cargo run --release -p curate-etl --offline -- bench-shorts [rows] +``` + +Command: `cargo run --release -p curate-etl --offline -- bench-shorts` + +- Input: `rows=700000`, `keys=12500` +- Build: `rows_out=528426`, `keys_out=12500`, `elapsed=49.76 ms`, `throughput=14068555 rows/s`, `latency=71.08 ns/row`, `checksum=0x1a99126eaa1a519b` (identical across back-to-back runs) +- Stats: `invalid_shares=6915`, `nulled_net_change=3673`, `nulled_pct_float=3500`, `dup_collapsed=5352`, `dup_conflict=159307` + +### `bench-events` + +Fixed-seed (`std`-only SplitMix64) benchmark over `500,000` synthetic rows (~98.5% `qmFilings`, ~1.5% `qmEarnings`, mirroring `30.52M` filings / `444.9k` earnings) across `20,000` `i32` `listing_id` keys with EST/EDT/pre-2008/late-evening timestamps, all EDGAR/SEDAR+ form groups, linked + unlinked earnings, and injected malformed/skipped/duplicate/conflicting rows, timing only `build_events`: + +```bash +cargo run --release -p curate-etl --offline -- bench-events [rows] +``` + +Command: `cargo run --release -p curate-etl --offline -- bench-events` + +- Input: `rows=500000`, `filings=492500`, `earnings=7500`, `keys=20000` +- Build: `rows_out=491190`, `filings_out=484531`, `earnings_out=6659`, `keys_out=20000`, `elapsed=268.55 ms`, `throughput=1861871 rows/s`, `latency=537.09 ns/row`, `checksum=0xbf74cd745a2646c6` (identical across back-to-back runs) +- Stats: `malformed_ts=1525`, `unknown_zone=1496`, `invalid_dt=2476`, `filing_dup=2472`, `linked=2569`, `lagged_1605=4090`, `earnings_oor=37`, `earnings_dup=98`, `earnings_conflict=706` +- Extrapolation to full `30.52M` `qmFilings` + `444.9k` `qmEarnings` (`30,964,900` rows): ~`16.6 s` single-threaded CPU time (excluding MongoDB BSON streaming and Zstd Parquet I/O). + +### `bench-provider-mapping` + +Fixed-seed (`std`-only SplitMix64), zero-allocation lookup benchmark over `60,000` `(source, source_id)` keys across 4 sources (`eod`, `qm`, `ib`, `ceo`) with 10% multi-range keys (`6,000` keys with 2–3 date ranges and interior gaps modeling ticker reuse), shuffling `68,000` input rows before timing `ProviderMappingTable::from_rows` and running `10,000,000` `resolve` lookups (~5% misses across unknown key/source, pre-first, interior gap, and post-last): + +```bash +cargo run --release -p curate-etl --offline -- bench-provider-mapping [lookups] +``` + +Command: `cargo run --release -p curate-etl --offline -- bench-provider-mapping` + +- Table: `keys=60000`, `ranges=68000`, `multi_range_keys=6000`, `build=17.45 ms`, `throughput=3896541 rows/s` +- Lookup: `lookups=10000000`, `hits=9443294`, `misses=556706`, `elapsed=447.14 ms`, `throughput=22364140 lookups/s`, `latency=44.71 ns/lookup`, `checksum=0xad8536129cafb697` (identical across back-to-back runs) + +### `bench-parquet-bars` + +Fixed-seed (`std`-only SplitMix64) streaming Zstd Parquet write benchmark over `5,000,000` sorted `Bars1dParquetRow` rows across `2,000` listings and 20 years (`2006..=2025`), writing `bars_1d/year=YYYY/part.parquet` into a fresh temp directory under `std::env::temp_dir()`, verifying Parquet footer row counts across all 20 files, and deleting the temp directory: + +```bash +cargo run --release -p curate-etl --offline -- bench-parquet-bars [rows] +``` + +Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-parquet-bars` + +- Input: `rows=5000000`, `listings=2000`, `raw_row_bytes=84` +- Output: `files=20`, `row_groups=20`, `bytes=231330139`, `read_back_rows=5000000` +- Perf: `elapsed=1422.27 ms`, `throughput=3515517 rows/s`, `write=155.11 MB/s`, `size=46.27 bytes/row`, `compression=1.82x` + +## Deferred Follow-Ups (`M1.3+` / `M2`) + +This crate currently depends only on `parquet` (Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline once the Cargo cache is populated. Follow-up tasks will add: + +- `bars_1d` and `fx_1d` schema metadata columns (`ts`, `known_at`, `currency`, `source`, `vwap`) requiring exchange session/timezone and listing metadata +- `CADUSD.FOREX` inversion, `fx_1m` intraday FX, and wiring `fx_1d` into `src/adj.rs` cross-currency dividends +- Zstd Parquet writers for the remaining curated tables (`adj_factors`, `corporate_actions`, `fx_1d`, `events`, `shorts`) and `qmPrices` OHLC cross-check - Read-only MongoDB `RawDocumentBuf` streaming cursors (`eodPrices`, `eodIntraday1M`, `qmSplits`) -- PostgreSQL `provider_mapping` preload keyed by `listing_id: i32` (supported via generic `SplitTable`) +- PostgreSQL I/O preload into `ProviderMappingTable` and rewiring the builders to resolve `(source, source_id, bar_date) -> listing_id: i32` - `rayon` parallel sharding across symbol/date partitions - QuestDB ILP v2 writer for time-series ingestion diff --git a/tools/curate-etl/src/bench.rs b/tools/curate-etl/src/bench.rs index 0ccf7d25..4ab31613 100644 --- a/tools/curate-etl/src/bench.rs +++ b/tools/curate-etl/src/bench.rs @@ -1,27 +1,57 @@ //! Fixed-seed, std-only benchmark for the split-factor lookup and un-adjustment hot loop. +use std::borrow::Cow; +use std::fs::{self, File}; use std::hint::black_box; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; use std::time::Instant; +use parquet::errors::ParquetError; +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::corporate_actions::{ build_corporate_actions, CorporateActionError, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, SplitActionEvent, }; +use crate::events::{build_events, EventsStats, QmEarning, QmFiling}; +use crate::fx::{build_fx_1d, fx_rate_on_or_before, Fx1dStats, FxDailyBar}; +use crate::parquet_bars::{ + write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, ParquetBarsError, +}; +use crate::provider_mapping::{ProviderMappingError, ProviderMappingRow, ProviderMappingTable}; +use crate::shorts::{build_shorts, epoch_days_to_ymd, CeoShortReport, ShortsError, ShortsStats}; use crate::split::{unadjust_volume, ymd_to_epoch_days, SplitError, SplitEvent, SplitTable}; 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_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_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; pub const BENCH_KEY_COUNT: usize = 20_000; pub const BENCH_EVENT_COUNT: usize = 19_000; +pub const PROVIDER_MAPPING_BENCH_KEY_COUNT: usize = 60_000; +const SHORTS_BENCH_KEY_COUNT: usize = 12_500; +const PARQUET_BARS_BENCH_BASE_LISTINGS: usize = 2_000; 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 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 PROVIDER_MAPPING_BENCH_SEED: u64 = 0x570C_4B07_9407_1D00; +const PARQUET_BARS_BENCH_SEED: u64 = 0x570C_4B07_9A49_BA45; const SAMPLE_RATIOS: [f64; 9] = [2.0, 3.0, 4.0, 5.0, 10.0, 0.5, 0.25, 0.1, 0.05]; /// Deterministic SplitMix64 generator (zero external dependencies). @@ -594,6 +624,1338 @@ pub fn run_bars_benchmark(rows: usize) -> Result { }) } +/// Summary metrics produced by [`run_fx_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct FxBenchReport { + pub rows: usize, + pub eod_rows_in: usize, + pub te_rows_in: usize, + pub rows_out: usize, + pub build_elapsed_ms: f64, + pub build_rows_per_sec: f64, + pub build_ns_per_row: f64, + pub lookups: usize, + pub lookup_hits: usize, + pub lookup_elapsed_ms: f64, + pub lookups_per_sec: f64, + pub ns_per_lookup: f64, + pub checksum: u64, + pub stats: Fx1dStats, +} + +fn shuffle_slice(items: &mut [T], rng: &mut SplitMix64) { + for i in (1..items.len()).rev() { + let j = (rng.next_u64() % (i as u64 + 1)) as usize; + items.swap(i, j); + } +} + +#[inline] +fn next_weekday(date: i32) -> i32 { + let next = date + 1; + // 1970-01-01 was Thursday (0=Thu, 1=Fri, 2=Sat, 3=Sun, 4=Mon). + match next.rem_euclid(7) { + 2 => next + 2, + 3 => next + 1, + _ => next, + } +} + +/// Runs the fixed-seed `build_fx_1d` + [`fx_rate_on_or_before`] benchmark for `rows` total daily +/// FX rows across `CAD.FOREX` (~80%) and `teMarketData.USDCAD` (~20%). +/// +/// Generates deterministic USD/CAD bars with an overlap window, interior EOD gaps, a post-EOD TE +/// tail, small shares of invalid/inconsistent/identical-duplicate/conflicting-duplicate rows, and +/// ~5% intentional overlap mismatches. Shuffles both inputs deterministically, times +/// [`build_fx_1d`], then times [`DEFAULT_FX_BENCH_LOOKUPS`] (`1_000_000`, or `0` when `rows == 0`) +/// zero-allocation [`fx_rate_on_or_before`] lookups. +pub fn run_fx_benchmark(rows: usize) -> FxBenchReport { + if rows == 0 { + let built = build_fx_1d(&[], &[]); + return FxBenchReport { + rows: 0, + eod_rows_in: 0, + te_rows_in: 0, + rows_out: 0, + build_elapsed_ms: 0.0, + build_rows_per_sec: 0.0, + build_ns_per_row: 0.0, + lookups: 0, + lookup_hits: 0, + lookup_elapsed_ms: 0.0, + lookups_per_sec: 0.0, + ns_per_lookup: 0.0, + checksum: 0, + stats: built.stats, + }; + } + + let base_date = ymd_to_epoch_days(1971, 1, 4).unwrap_or(368); + let mut rng = SplitMix64::new(FX_BENCH_SEED); + + let te_target = rows / 5; + let eod_target = rows - te_target; + + let mut eod: Vec = Vec::with_capacity(eod_target); + let mut eod_valid_history: Vec = Vec::with_capacity(eod_target); + let mut interior_gap_dates: Vec = Vec::new(); + let mut cur_date = base_date; + let mut rate = 1.01_f64; + + for _ in 0..eod_target { + let roll = rng.next_u64() % 1_000; + if roll < 10 { + if let Some(&prev) = eod_valid_history.last() { + eod.push(prev); + continue; + } + } else if roll < 15 { + if let Some(&prev) = eod_valid_history.last() { + let mut conflicting = prev; + conflicting.close = (conflicting.close + 0.002).min(conflicting.high); + if conflicting.close.to_bits() == prev.close.to_bits() { + conflicting.high += 0.002; + conflicting.close += 0.001; + } + eod.push(conflicting); + continue; + } + } + + // Advance calendar date, skipping weekends and occasional interior gaps. + cur_date = next_weekday(cur_date); + if rng.next_u64() % 20 == 0 { + interior_gap_dates.push(cur_date); + cur_date = next_weekday(cur_date); + } + + let step = ((rng.next_u64() % 201) as f64 - 100.0) * 0.0001; + rate = (rate + step).clamp(0.92, 1.60); + let half_spread = ((rng.next_u64() % 80) + 10) as f64 * 0.0001; + let low = (rate - half_spread).max(0.50); + let high = rate + half_spread; + let open = low + (high - low) * ((rng.next_u64() % 100) as f64 * 0.01); + let close = rate; + + let bar = match roll { + 15..=24 => FxDailyBar { + session_date: cur_date, + open: -1.0, + high, + low, + close, + }, + 25..=34 => FxDailyBar { + session_date: cur_date, + open, + high: low - 0.01, + low, + close, + }, + _ => { + let b = FxDailyBar { + session_date: cur_date, + open, + high, + low, + close, + }; + eod_valid_history.push(b); + b + } + }; + eod.push(bar); + } + + let last_eod_date = cur_date; + let mut te: Vec = Vec::with_capacity(te_target); + let mut te_last_valid: Option = None; + + // ~60% of TE rows overlap EOD's recent window + interior gaps; ~40% extend past EOD's tail. + let te_overlap_target = (te_target * 3) / 5; + let te_tail_target = te_target - te_overlap_target; + let overlap_start = eod_valid_history.len().saturating_sub(te_overlap_target); + + for idx in 0..te_overlap_target { + let roll = rng.next_u64() % 1_000; + if roll < 10 { + if let Some(prev) = te_last_valid { + te.push(prev); + continue; + } + } else if roll < 15 { + if let Some(mut prev) = te_last_valid { + prev.close = (prev.close + 0.002).min(prev.high); + if prev.close.to_bits() == te_last_valid.map_or(0, |b| b.close.to_bits()) { + prev.high += 0.002; + prev.close += 0.001; + } + te.push(prev); + continue; + } + } + + // Fill some interior EOD gaps, otherwise overlap EOD dates. + let (session_date, base_bar) = if idx % 10 == 0 && !interior_gap_dates.is_empty() { + let gap_date = interior_gap_dates[(idx / 10) % interior_gap_dates.len()]; + let ref_bar = eod_valid_history + .get(overlap_start + idx) + .copied() + .unwrap_or(FxDailyBar { + session_date: gap_date, + open: 1.35, + high: 1.36, + low: 1.34, + close: 1.35, + }); + (gap_date, ref_bar) + } else if let Some(&ref_bar) = eod_valid_history.get(overlap_start + idx) { + (ref_bar.session_date, ref_bar) + } else { + ( + last_eod_date + 1 + idx as i32, + FxDailyBar { + session_date: last_eod_date + 1 + idx as i32, + open: 1.35, + high: 1.36, + low: 1.34, + close: 1.35, + }, + ) + }; + + // ~5% intentional overlap mismatches (+2.5%), ~95% within 1% (±0.30%). + let factor = if rng.next_u64() % 20 == 0 { + 1.025 + } else { + let jitter_bp = (rng.next_u64() % 61) as f64 - 30.0; + 1.0 + jitter_bp * 0.0001 + }; + let open = base_bar.open * factor; + let high = base_bar.high * factor; + let low = base_bar.low * factor; + let close = base_bar.close * factor; + + let bar = match roll { + 15..=24 => FxDailyBar { + session_date, + open: f64::NAN, + high, + low, + close, + }, + 25..=34 => FxDailyBar { + session_date, + open, + high: low - 0.01, + low, + close, + }, + _ => { + let b = FxDailyBar { + session_date, + open, + high, + low, + close, + }; + te_last_valid = Some(b); + b + } + }; + te.push(bar); + } + + let mut tail_date = last_eod_date; + let mut tail_rate = rate; + for _ in 0..te_tail_target { + tail_date = next_weekday(tail_date); + let step = ((rng.next_u64() % 201) as f64 - 100.0) * 0.0001; + tail_rate = (tail_rate + step).clamp(0.92, 1.60); + let half_spread = ((rng.next_u64() % 80) + 10) as f64 * 0.0001; + let low = (tail_rate - half_spread).max(0.50); + let high = tail_rate + half_spread; + let open = low + (high - low) * ((rng.next_u64() % 100) as f64 * 0.01); + te.push(FxDailyBar { + session_date: tail_date, + open, + high, + low, + close: tail_rate, + }); + } + + shuffle_slice(&mut eod, &mut rng); + shuffle_slice(&mut te, &mut rng); + + let eod_rows_in = eod.len(); + let te_rows_in = te.len(); + + let build_start = Instant::now(); + let built = build_fx_1d(&eod, &te); + let build_elapsed_secs = build_start.elapsed().as_secs_f64(); + let build_elapsed_ms = build_elapsed_secs * 1_000.0; + let (build_rows_per_sec, build_ns_per_row) = compute_rates(rows, build_elapsed_secs); + + let mut rows_hash = 0u64; + for row in &built.rows { + rows_hash = mix_u64(rows_hash, row.session_date as u64); + rows_hash = mix_u64(rows_hash, row.open.to_bits()); + rows_hash = mix_u64(rows_hash, row.high.to_bits()); + rows_hash = mix_u64(rows_hash, row.low.to_bits()); + rows_hash = mix_u64(rows_hash, row.close.to_bits()); + rows_hash = mix_u64(rows_hash, row.source as u64); + } + + let lookups = DEFAULT_FX_BENCH_LOOKUPS; + let (query_min, query_span) = match (built.rows.first(), built.rows.last()) { + (Some(first), Some(last)) => { + let min_q = first.session_date - 10; + let max_q = last.session_date + 10; + (min_q, (i64::from(max_q) - i64::from(min_q) + 1) as u64) + } + _ => (base_date, 100u64), + }; + + let mut lookup_hash = 0u64; + let mut lookup_hits = 0usize; + let lookup_start = Instant::now(); + for _ in 0..lookups { + let query_date = query_min + (rng.next_u64() % query_span) as i32; + if let Some(row) = fx_rate_on_or_before(&built.rows, query_date, 4) { + lookup_hits += 1; + lookup_hash = mix_u64(lookup_hash, row.close.to_bits()); + } else { + lookup_hash = mix_u64(lookup_hash, 0xDEAD_BEEF_u64); + } + } + let lookup_hash = black_box(lookup_hash); + let lookup_elapsed_secs = lookup_start.elapsed().as_secs_f64(); + let lookup_elapsed_ms = lookup_elapsed_secs * 1_000.0; + let (lookups_per_sec, ns_per_lookup) = compute_rates(lookups, lookup_elapsed_secs); + + let checksum = black_box(mix_u64(rows_hash, lookup_hash)); + + FxBenchReport { + rows, + eod_rows_in, + te_rows_in, + rows_out: built.stats.rows_out, + build_elapsed_ms, + build_rows_per_sec, + build_ns_per_row, + lookups, + lookup_hits, + lookup_elapsed_ms, + lookups_per_sec, + ns_per_lookup, + checksum, + stats: built.stats, + } +} + +/// Summary metrics produced by [`run_shorts_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ShortsBenchReport { + pub rows: usize, + pub key_count: usize, + pub rows_out: usize, + pub keys_out: usize, + pub build_elapsed_ms: f64, + pub rows_per_sec: f64, + pub ns_per_row: f64, + pub checksum: u64, + pub stats: ShortsStats, +} + +fn semi_monthly_report_dates() -> Vec { + let mut dates = Vec::with_capacity(220); + let mut year = 2017_i32; + let mut month = 4_u32; + while year < 2026 || (year == 2026 && month <= 4) { + let mid = ymd_to_epoch_days(year, month, 15).expect("valid 15th"); + let (next_y, next_m) = if month == 12 { + (year + 1, 1) + } else { + (year, month + 1) + }; + let month_end = ymd_to_epoch_days(next_y, next_m, 1).expect("valid next month") - 1; + dates.push(mid); + dates.push(month_end); + year = next_y; + month = next_m; + } + dates +} + +/// Runs the fixed-seed `build_shorts` benchmark for `rows` synthetic `ceoShorts` rows. +/// +/// Generates `rows` deterministic reports across `12_500` `i32` `listing_id` keys on semi-monthly +/// (15th and month-end) dates spanning `2017-04-15..=2026-04-30` with small shares of negative/NaN +/// `shares_short`, non-finite optional fields, identical duplicates, and conflicting duplicates, +/// shuffles deterministically, times only [`build_shorts`], and returns throughput plus a +/// deterministic `u64` checksum. +pub fn run_shorts_benchmark(rows: usize) -> Result { + if rows == 0 { + let built = build_shorts::(Vec::new())?; + return Ok(ShortsBenchReport { + rows: 0, + key_count: SHORTS_BENCH_KEY_COUNT, + rows_out: 0, + keys_out: 0, + build_elapsed_ms: 0.0, + rows_per_sec: 0.0, + ns_per_row: 0.0, + checksum: 0, + stats: built.stats, + }); + } + + let report_dates = semi_monthly_report_dates(); + let mut rng = SplitMix64::new(SHORTS_BENCH_SEED); + let mut reports: Vec> = Vec::with_capacity(rows); + let mut last_valid: Option> = None; + + for _ in 0..rows { + let roll = rng.next_u64() % 1_000; + if roll < 10 { + if let Some(prev) = last_valid.clone() { + reports.push(prev); + continue; + } + } else if roll < 15 { + if let Some(mut prev) = last_valid.clone() { + prev.shares_short += 100.0; + reports.push(prev); + continue; + } + } + + let key = (rng.next_u64() % (SHORTS_BENCH_KEY_COUNT as u64)) as i32 + 1; + let report_date = report_dates[(rng.next_u64() as usize) % report_dates.len()]; + let shares = ((rng.next_u64() % 5_000_000) + 100) as f64; + let net_raw = ((rng.next_u64() % 200_000) as f64) - 100_000.0; + let pct_raw = ((rng.next_u64() % 1_500) as f64) * 0.01; + + let row = match roll { + 15..=19 => CeoShortReport { + key, + report_date, + shares_short: -50.0, + net_change: Some(net_raw), + pct_float: Some(pct_raw), + }, + 20..=24 => CeoShortReport { + key, + report_date, + shares_short: f64::NAN, + net_change: Some(net_raw), + pct_float: Some(pct_raw), + }, + 25..=29 => { + let r = CeoShortReport { + key, + report_date, + shares_short: shares, + net_change: Some(f64::NAN), + pct_float: Some(pct_raw), + }; + last_valid = Some(r.clone()); + r + } + 30..=34 => { + let r = CeoShortReport { + key, + report_date, + shares_short: shares, + net_change: Some(net_raw), + pct_float: Some(f64::INFINITY), + }; + last_valid = Some(r.clone()); + r + } + _ => { + let net_change = if rng.next_u64() % 10 == 0 { + None + } else { + Some(net_raw) + }; + let pct_float = if rng.next_u64() % 4 == 0 { + None + } else { + Some(pct_raw) + }; + let r = CeoShortReport { + key, + report_date, + shares_short: shares, + net_change, + pct_float, + }; + last_valid = Some(r.clone()); + r + } + }; + reports.push(row); + } + + shuffle_slice(&mut reports, &mut rng); + + let build_start = Instant::now(); + let built = build_shorts(reports)?; + let build_elapsed_secs = build_start.elapsed().as_secs_f64(); + let build_elapsed_ms = build_elapsed_secs * 1_000.0; + let (rows_per_sec, ns_per_row) = compute_rates(rows, build_elapsed_secs); + + let mut hash = 0u64; + for row in &built.rows { + hash = mix_u64(hash, row.key as u64); + hash = mix_u64(hash, row.report_date as u64); + hash = mix_u64(hash, row.known_at_date as u64); + hash = mix_u64(hash, row.known_at_utc_micros as u64); + hash = mix_u64(hash, row.shares_short.to_bits()); + hash = mix_u64(hash, row.net_change.map_or(u64::MAX, f64::to_bits)); + hash = mix_u64(hash, row.pct_float.map_or(u64::MAX, f64::to_bits)); + let source_bits = row + .source + .bytes() + .fold(0u64, |acc, b| acc.wrapping_shl(8) | u64::from(b)); + hash = mix_u64(hash, source_bits); + } + let checksum = black_box(hash); + + Ok(ShortsBenchReport { + rows, + key_count: SHORTS_BENCH_KEY_COUNT, + rows_out: built.stats.rows_out, + keys_out: built.stats.keys_out, + build_elapsed_ms, + rows_per_sec, + ns_per_row, + checksum, + stats: built.stats, + }) +} + +/// Summary metrics produced by [`run_events_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct EventsBenchReport { + pub rows: usize, + pub filings_in: usize, + pub earnings_in: usize, + pub key_count: usize, + pub rows_out: usize, + pub keys_out: usize, + pub build_elapsed_ms: f64, + pub rows_per_sec: f64, + pub ns_per_row: f64, + pub checksum: u64, + pub stats: EventsStats, +} + +const BENCH_FORM_TYPES: &[&str] = &[ + "8-K", + "News release", + "4", + "10-Q", + "10-K", + "10-K/A", + "144", + "40-F", + "Interim financial statements/report", + "Annual financial statements", + "MD&A", + "52-109", + "NI 43-101", + "45-106F1", + "424B5", + "8-K/A", +]; + +const BENCH_ANNOUNCE_TIMES: &[&str] = &["N/A", "AMC", "BTO"]; + +fn mix_bytes(mut hash: u64, bytes: &[u8]) -> u64 { + let mut chunks = bytes.chunks_exact(8); + for chunk in &mut chunks { + let mut buf = [0u8; 8]; + buf.copy_from_slice(chunk); + hash = mix_u64(hash, u64::from_le_bytes(buf)); + } + let rem = chunks.remainder(); + if !rem.is_empty() { + let mut buf = [0u8; 8]; + buf[..rem.len()].copy_from_slice(rem); + hash = mix_u64(hash, u64::from_le_bytes(buf)); + } + mix_u64(hash, bytes.len() as u64) +} + +/// Runs the fixed-seed `build_events` benchmark for `rows` total synthetic `qmFilings` (~98.5%) +/// and `qmEarnings` (~1.5%) rows across `20_000` `i32` `listing_id` keys. +/// +/// Mirrors the empirical `30.52M` filings / `444.9k` earnings ratio with EST/EDT/pre-2008/ +/// late-evening timestamps, all EDGAR and SEDAR+ form groups, linked + unlinked earnings, and +/// small shares of malformed/skipped/duplicate/conflicting rows. Shuffles both inputs +/// deterministically, times only [`build_events`], and returns throughput plus a deterministic +/// `u64` checksum. +pub fn run_events_benchmark(rows: usize) -> EventsBenchReport { + if rows == 0 { + let built = build_events::(Vec::new(), Vec::new()); + return EventsBenchReport { + rows: 0, + filings_in: 0, + earnings_in: 0, + key_count: BENCH_KEY_COUNT, + rows_out: 0, + keys_out: 0, + build_elapsed_ms: 0.0, + rows_per_sec: 0.0, + ns_per_row: 0.0, + checksum: 0, + stats: built.stats, + }; + } + + let min_filing_date = ymd_to_epoch_days(2003, 1, 1).unwrap_or(12_053); + let max_filing_date = ymd_to_epoch_days(2026, 4, 30).unwrap_or(20_573); + let filing_span = (max_filing_date - min_filing_date + 1) as u64; + + let min_earning_date = ymd_to_epoch_days(2008, 1, 1).unwrap_or(13_879); + let max_earning_date = ymd_to_epoch_days(2026, 4, 30).unwrap_or(20_573); + let earning_span = (max_earning_date - min_earning_date + 1) as u64; + + let earnings_target = (rows * 15) / 1_000; + let filings_target = rows - earnings_target; + + let mut rng = SplitMix64::new(EVENTS_BENCH_SEED); + let mut filings: Vec> = Vec::with_capacity(filings_target); + let mut link_pool: Vec<(i32, i32)> = Vec::with_capacity(earnings_target.min(16_384)); + let mut last_valid_filing: Option> = None; + + for idx in 0..filings_target { + let roll = rng.next_u64() % 1_000; + if roll < 5 { + if let Some(prev) = last_valid_filing.clone() { + filings.push(prev); + continue; + } + } + + let key = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1; + let epoch_day = min_filing_date + (rng.next_u64() % filing_span) as i32; + let (y, m, d) = epoch_days_to_ymd(epoch_day); + let form_idx = (rng.next_u64() as usize) % BENCH_FORM_TYPES.len(); + let form_type = BENCH_FORM_TYPES[form_idx].to_string(); + let filing_id = if rng.next_u64() % 10 == 0 { + None + } else { + Some(format!("F{idx:08}")) + }; + let url = if rng.next_u64() % 4 == 0 { + None + } else { + Some(format!("https://filings.example/{key}/{idx}")) + }; + + let timefiled = match roll { + 5..=7 => "bad-timestamp".to_string(), + 8..=10 => format!("{y:04}-{m:02}-{d:02}T12:00:00 PST"), + 11..=13 => format!("{y:04}-02-30T12:00:00 EST"), + 14..=15 => format!("{y:04}-{m:02}-{d:02}T25:00:00 EST"), + _ => { + // Mix morning, midday, and late-evening ET (crossing into next UTC day). + let hour = if roll < 60 { + 21 + (rng.next_u64() % 3) as u32 + } else { + 6 + (rng.next_u64() % 13) as u32 + }; + let minute = (rng.next_u64() % 60) as u32; + let second = (rng.next_u64() % 60) as u32; + let zone = if (4..=10).contains(&m) { "EDT" } else { "EST" }; + let ts = format!("{y:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02} {zone}"); + if matches!(form_idx, 0 | 1 | 15) && link_pool.len() < 16_384 { + link_pool.push((key, epoch_day)); + } + ts + } + }; + + let row = QmFiling { + key, + timefiled, + form_type, + filing_id, + url, + }; + if roll >= 16 { + last_valid_filing = Some(row.clone()); + } + filings.push(row); + } + + let mut earnings: Vec> = Vec::with_capacity(earnings_target); + let mut last_valid_earning: Option> = None; + + for _ in 0..earnings_target { + let roll = rng.next_u64() % 1_000; + if roll < 15 { + if let Some(prev) = last_valid_earning.clone() { + earnings.push(prev); + continue; + } + } else if roll < 25 { + if let Some(mut prev) = last_valid_earning.clone() { + prev.actual_eps = Some(prev.actual_eps.unwrap_or(0.0) + 0.10); + earnings.push(prev); + continue; + } + } + + let (key, report_date) = if roll < 30 && !link_pool.is_empty() { + // Out-of-range unlinked date (< 2008-01-01) + let k = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1; + let d = ymd_to_epoch_days(2005, 6, 15).unwrap_or(12_949); + (k, d) + } else if roll < 450 && !link_pool.is_empty() { + let pick = (rng.next_u64() as usize) % link_pool.len(); + link_pool[pick] + } else { + let k = (rng.next_u64() % (BENCH_KEY_COUNT as u64)) as i32 + 1; + let d = min_earning_date + (rng.next_u64() % earning_span) as i32; + (k, d) + }; + + let announce_time = + BENCH_ANNOUNCE_TIMES[(rng.next_u64() as usize) % BENCH_ANNOUNCE_TIMES.len()] + .to_string(); + let actual_eps = if roll % 50 == 0 { + Some(f64::NAN) + } else { + Some((((rng.next_u64() % 1_000) as f64) - 200.0) * 0.01) + }; + let revenue = Some(((rng.next_u64() % 5_000_000) + 10_000) as f64); + + let row = QmEarning { + key, + report_date, + announce_time, + fiscal_period_end: Some(report_date - 35), + actual_eps, + revenue, + }; + if roll >= 30 { + last_valid_earning = Some(row.clone()); + } + earnings.push(row); + } + + shuffle_slice(&mut filings, &mut rng); + shuffle_slice(&mut earnings, &mut rng); + + let filings_in = filings.len(); + let earnings_in = earnings.len(); + + let build_start = Instant::now(); + let built = build_events(filings, earnings); + let build_elapsed_secs = build_start.elapsed().as_secs_f64(); + let build_elapsed_ms = build_elapsed_secs * 1_000.0; + let (rows_per_sec, ns_per_row) = compute_rates(rows, build_elapsed_secs); + + let mut hash = 0u64; + for row in &built.rows { + hash = mix_u64(hash, row.key as u64); + hash = mix_u64(hash, row.ts_micros as u64); + hash = mix_u64(hash, row.known_at_micros as u64); + hash = mix_bytes(hash, row.known_at_source.as_bytes()); + hash = mix_bytes(hash, row.kind.as_bytes()); + hash = mix_bytes(hash, row.subtype.as_bytes()); + hash = mix_bytes(hash, row.payload_json.as_bytes()); + } + let checksum = black_box(hash); + + EventsBenchReport { + rows, + filings_in, + earnings_in, + key_count: BENCH_KEY_COUNT, + rows_out: built.stats.rows_out, + keys_out: built.stats.keys_out, + build_elapsed_ms, + rows_per_sec, + ns_per_row, + checksum, + stats: built.stats, + } +} + +/// Summary metrics produced by [`run_provider_mapping_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ProviderMappingBenchReport { + pub key_count: usize, + pub range_count: usize, + pub multi_range_keys: usize, + pub build_elapsed_ms: f64, + pub build_rows_per_sec: f64, + pub lookups: usize, + pub hits: usize, + pub misses: usize, + pub lookup_elapsed_ms: f64, + pub lookups_per_sec: f64, + pub ns_per_lookup: f64, + pub checksum: u64, +} + +struct ProviderMappingBenchKey { + source: &'static str, + source_id: String, + first_from: i32, + gap_date: Option, + last_to: Option, +} + +/// Runs the fixed-seed [`ProviderMappingTable`] build and zero-allocation `resolve` benchmark. +/// +/// Generates `60_000` `(source, source_id)` keys across 4 sources (`eod`, `qm`, `ib`, `ceo`), +/// with ~10% multi-range keys (2–3 date ranges and interior gaps modeling ticker reuse such as +/// `FB` 2012–2022 -> `FB` 2025 ETF), shuffles input rows before timing `from_rows`, then runs +/// `lookups` zero-allocation `resolve` probes with ~5% misses spanning unknown key/source, +/// pre-first, interior gap, and post-last dates. +pub fn run_provider_mapping_benchmark( + lookups: usize, +) -> Result { + const SOURCES: [&str; 4] = ["eod", "qm", "ib", "ceo"]; + let min_date = ymd_to_epoch_days(1990, 1, 1).unwrap_or(7_305); + let max_date = ymd_to_epoch_days(2025, 12, 31).unwrap_or(20_453); + + let mut rng = SplitMix64::new(PROVIDER_MAPPING_BENCH_SEED); + let mut rows: Vec = + Vec::with_capacity(PROVIDER_MAPPING_BENCH_KEY_COUNT + 8_000); + let mut bench_keys: Vec = + Vec::with_capacity(PROVIDER_MAPPING_BENCH_KEY_COUNT); + let mut multi_range_indices: Vec = + Vec::with_capacity(PROVIDER_MAPPING_BENCH_KEY_COUNT / 10 + 16); + let mut closed_last_indices: Vec = + Vec::with_capacity(PROVIDER_MAPPING_BENCH_KEY_COUNT / 3); + + let mut next_listing_id = 1i32; + + for k in 0..PROVIDER_MAPPING_BENCH_KEY_COUNT { + let source = SOURCES[k % SOURCES.len()]; + let source_id = match k % SOURCES.len() { + 0 => format!("SYM{k:05}.US"), + 1 => format!("QM{k:05}"), + 2 => format!("{}", 100_000_000 + k), + _ => format!("CEO{k:05}"), + }; + + let range_count = if k % 30 == 0 { + 3 + } else if k % 10 == 0 { + 2 + } else { + 1 + }; + + let first_from = min_date + (rng.next_u64() % 3_000) as i32; + let mut cur_from = first_from; + let mut gap_date: Option = None; + let mut last_to: Option = None; + + for r in 0..range_count { + let is_last = r + 1 == range_count; + let is_open_ended = is_last && (k % 4 != 0); + let span = 600 + (rng.next_u64() % 1_800) as i32; + let valid_to = if is_open_ended { + None + } else { + Some((cur_from + span).min(max_date - 30)) + }; + + rows.push(ProviderMappingRow { + source: source.to_string(), + source_id: source_id.clone(), + valid_from: cur_from, + valid_to, + listing_id: next_listing_id, + }); + next_listing_id += 1; + + if let Some(to) = valid_to { + if is_last { + last_to = Some(to); + } else { + if gap_date.is_none() { + gap_date = Some(to + 1); + } + let gap_len = 60 + (rng.next_u64() % 400) as i32; + cur_from = to + 1 + gap_len; + } + } + } + + if range_count > 1 { + multi_range_indices.push(k); + } + if last_to.is_some() { + closed_last_indices.push(k); + } + bench_keys.push(ProviderMappingBenchKey { + source, + source_id, + first_from, + gap_date, + last_to, + }); + } + + let multi_range_keys = multi_range_indices.len(); + let row_count = rows.len(); + shuffle_slice(&mut rows, &mut rng); + + let build_start = Instant::now(); + let table = ProviderMappingTable::from_rows(rows)?; + let build_elapsed_secs = build_start.elapsed().as_secs_f64(); + let build_elapsed_ms = build_elapsed_secs * 1_000.0; + let (build_rows_per_sec, _) = compute_rates(row_count, build_elapsed_secs); + + if lookups == 0 { + return Ok(ProviderMappingBenchReport { + key_count: table.len(), + range_count: table.range_count(), + multi_range_keys, + build_elapsed_ms, + build_rows_per_sec, + lookups: 0, + hits: 0, + misses: 0, + lookup_elapsed_ms: 0.0, + lookups_per_sec: 0.0, + ns_per_lookup: 0.0, + checksum: 0, + }); + } + + let key_count = bench_keys.len(); + let multi_len = multi_range_indices.len(); + let closed_len = closed_last_indices.len(); + let mut hits = 0usize; + let mut misses = 0usize; + let mut hash = 0u64; + + let lookup_start = Instant::now(); + for _ in 0..lookups { + let roll = rng.next_u64() % 100; + let resolved = if roll < 5 { + match roll { + 0 => { + let src = SOURCES[(rng.next_u64() as usize) % SOURCES.len()]; + table.resolve(src, "UNKNOWN_999999", min_date + 5_000) + } + 1 => { + let key = &bench_keys[(rng.next_u64() as usize) % key_count]; + table.resolve("unknown_src", key.source_id.as_str(), key.first_from) + } + 2 => { + let key = &bench_keys[(rng.next_u64() as usize) % key_count]; + table.resolve(key.source, key.source_id.as_str(), key.first_from - 1) + } + 3 => { + let idx = multi_range_indices[(rng.next_u64() as usize) % multi_len]; + let key = &bench_keys[idx]; + let probe = key.gap_date.unwrap_or(key.first_from - 1); + table.resolve(key.source, key.source_id.as_str(), probe) + } + _ => { + let idx = closed_last_indices[(rng.next_u64() as usize) % closed_len]; + let key = &bench_keys[idx]; + let probe = key.last_to.map_or(key.first_from - 1, |to| to + 1); + table.resolve(key.source, key.source_id.as_str(), probe) + } + } + } else { + let key = &bench_keys[(rng.next_u64() as usize) % key_count]; + let hi = key.last_to.unwrap_or(max_date); + let span = (hi - key.first_from + 1).max(1) as u64; + let bar_date = key.first_from + (rng.next_u64() % span) as i32; + table.resolve(key.source, key.source_id.as_str(), bar_date) + }; + + match resolved { + Some(listing_id) => { + hits += 1; + hash = mix_u64(hash, listing_id as u64); + } + None => { + misses += 1; + hash = mix_u64(hash, u64::MAX); + } + } + } + let checksum = black_box(hash); + let lookup_elapsed_secs = lookup_start.elapsed().as_secs_f64(); + let lookup_elapsed_ms = lookup_elapsed_secs * 1_000.0; + let (lookups_per_sec, ns_per_lookup) = compute_rates(lookups, lookup_elapsed_secs); + + Ok(ProviderMappingBenchReport { + key_count: table.len(), + range_count: table.range_count(), + multi_range_keys, + build_elapsed_ms, + build_rows_per_sec, + lookups, + hits, + misses, + lookup_elapsed_ms, + lookups_per_sec, + ns_per_lookup, + checksum, + }) +} + +/// Summary metrics produced by [`run_parquet_bars_benchmark`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct ParquetBarsBenchReport { + pub rows: usize, + pub read_back_rows: usize, + pub listing_count: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub raw_row_bytes: usize, + pub elapsed_ms: f64, + pub rows_per_sec: f64, + pub mb_per_sec: f64, + pub bytes_per_row: f64, + pub compression_ratio: f64, +} + +static BENCH_TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + +struct BenchTempDir { + path: PathBuf, +} + +impl BenchTempDir { + fn new_in(base: &Path) -> Result { + let pid = std::process::id(); + for _ in 0..1024 { + let seq = BENCH_TEMP_DIR_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + let path = base.join(format!("curate-etl-bench-pq-bars-{pid}-{seq}")); + match fs::create_dir(&path) { + Ok(()) => return Ok(Self { path }), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(source) => { + return Err(ParquetBarsError::Io { path, source }); + } + } + } + Err(ParquetBarsError::Io { + path: base.to_path_buf(), + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique benchmark temp directory names", + ), + }) + } + + fn new() -> Result { + Self::new_in(&std::env::temp_dir()) + } +} + +impl Drop for BenchTempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +struct ParquetBarsBenchIter { + weekdays: Vec, + listing_count: usize, + base_per_listing: usize, + rem_listings: usize, + cur_listing: usize, + cur_day_idx: usize, + cur_listing_rows: usize, + cur_close: f64, + rng: SplitMix64, +} + +impl ParquetBarsBenchIter { + fn new(rows: usize, weekdays: Vec) -> Self { + let min_listings = if rows == 0 { + PARQUET_BARS_BENCH_BASE_LISTINGS + } else { + rows.div_ceil(weekdays.len()) + .max(PARQUET_BARS_BENCH_BASE_LISTINGS) + }; + let active_listings = rows.min(min_listings); + let base_per_listing = if active_listings == 0 { + 0 + } else { + rows / active_listings + }; + let rem_listings = if active_listings == 0 { + 0 + } else { + rows % active_listings + }; + let mut iter = Self { + weekdays, + listing_count: active_listings, + base_per_listing, + rem_listings, + cur_listing: 0, + cur_day_idx: 0, + cur_listing_rows: 0, + cur_close: 50.0, + rng: SplitMix64::new(PARQUET_BARS_BENCH_SEED), + }; + if active_listings > 0 { + iter.setup_listing(0); + } + iter + } + + fn setup_listing(&mut self, listing_idx: usize) { + self.cur_listing = listing_idx; + self.cur_day_idx = 0; + self.cur_listing_rows = + self.base_per_listing + usize::from(listing_idx < self.rem_listings); + self.cur_close = 5.0 + ((self.rng.next_u64() % 25_000) as f64) * 0.01; + } +} + +impl Iterator for ParquetBarsBenchIter { + type Item = Bars1dParquetRow; + + fn next(&mut self) -> Option { + if self.cur_listing >= self.listing_count { + return None; + } + if self.cur_day_idx >= self.cur_listing_rows { + let next_listing = self.cur_listing + 1; + if next_listing >= self.listing_count { + self.cur_listing = next_listing; + return None; + } + self.setup_listing(next_listing); + } + + let listing_id = (self.cur_listing + 1) as i32; + let w = self.weekdays.len(); + let n = self.cur_listing_rows; + let date_pos = if n == 1 { + (self.cur_listing.wrapping_mul(257)) % w + } else { + (self.cur_day_idx * w) / n + }; + let session_date = self.weekdays[date_pos]; + self.cur_day_idx += 1; + + let r1 = self.rng.next_u64(); + let r2 = self.rng.next_u64(); + + // Small realistic random walk in cents. + let delta_bps = ((r1 & 0xFF) as i64) - 128; + let next_close = (self.cur_close * (1.0 + (delta_bps as f64) * 0.0002)).clamp(0.5, 5_000.0); + let open = self.cur_close; + let spread = 0.005 + (((r1 >> 8) & 0x3F) as f64) * 0.0005; + let high = open.max(next_close) * (1.0 + spread); + let low = (open.min(next_close) * (1.0 - spread)).max(0.01); + self.cur_close = next_close; + + let volume = ((r2 & 0x3F_FFFF) + 100) as f64; + let vwap = if (r2 >> 22) & 0x3 == 0 { + None + } else { + Some((open + high + low + next_close) * 0.25) + }; + let currency = if listing_id % 5 == 0 { + Cow::Borrowed("CAD") + } else { + Cow::Borrowed("USD") + }; + let source = Cow::Borrowed("eod_unadj"); + let ts_micros = i64::from(session_date) * 86_400_000_000 + 21 * 3_600_000_000; + let known_at_micros = ts_micros + 900_000_000; + + Some(Bars1dParquetRow { + listing_id, + ts_micros, + session_date, + open, + high, + low, + close: next_close, + volume, + vwap, + currency, + source, + known_at_micros, + }) + } +} + +fn collect_bench_weekdays_2006_2025() -> Vec { + let start = ymd_to_epoch_days(2006, 1, 2).expect("valid start date"); + let end = ymd_to_epoch_days(2025, 12, 31).expect("valid end date"); + let mut days = Vec::with_capacity(5_300); + let mut d = start; + while d <= end { + let dow = (d + 4).rem_euclid(7); + if (1..=5).contains(&dow) { + days.push(d); + } + d += 1; + } + days +} + +fn verify_parquet_bars_row_count( + out_dir: &Path, + years: impl IntoIterator, + expected_rows: usize, +) -> Result { + let mut read_back_rows = 0usize; + for year in years { + let path = out_dir.join(format!("bars_1d/year={year:04}/part.parquet")); + let file = File::open(&path).map_err(|source| ParquetBarsError::Io { + path: path.clone(), + source, + })?; + let reader = SerializedFileReader::new(file).map_err(|source| { + ParquetBarsError::Parquet { + path: path.clone(), + source, + } + })?; + let file_rows = usize::try_from(reader.metadata().file_metadata().num_rows()).map_err( + |_| ParquetBarsError::Parquet { + path: path.clone(), + source: ParquetError::General(format!( + "negative or overflowing Parquet footer row count: {}", + reader.metadata().file_metadata().num_rows() + )), + }, + )?; + read_back_rows = read_back_rows.checked_add(file_rows).ok_or_else(|| { + ParquetBarsError::Parquet { + path: path.clone(), + source: ParquetError::General("read-back row count overflow".to_string()), + } + })?; + } + + if read_back_rows != expected_rows { + return Err(ParquetBarsError::Parquet { + path: out_dir.join("bars_1d"), + source: ParquetError::General(format!( + "parquet row count mismatch: expected {expected_rows}, read back {read_back_rows}" + )), + }); + } + + Ok(read_back_rows) +} + +fn run_parquet_bars_benchmark_tracked( + rows: usize, +) -> Result<(ParquetBarsBenchReport, PathBuf), ParquetBarsError> { + let temp = BenchTempDir::new()?; + let temp_path = temp.path.clone(); + + if rows == 0 { + let stats = write_bars_1d_dataset( + &temp.path, + std::iter::empty::(), + Bars1dWriteOptions::default(), + )?; + let read_back_rows = + verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), 0)?; + let report = ParquetBarsBenchReport { + rows: 0, + read_back_rows, + listing_count: 0, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_BARS_RAW_ROW_BYTES, + elapsed_ms: 0.0, + rows_per_sec: 0.0, + mb_per_sec: 0.0, + bytes_per_row: 0.0, + compression_ratio: 0.0, + }; + drop(temp); + return Ok((report, temp_path)); + } + + let weekdays = collect_bench_weekdays_2006_2025(); + let iter = ParquetBarsBenchIter::new(rows, weekdays); + let listing_count = iter.listing_count; + + let start = Instant::now(); + let stats = write_bars_1d_dataset(&temp.path, iter, Bars1dWriteOptions::default())?; + let elapsed_secs = start.elapsed().as_secs_f64(); + let elapsed_ms = elapsed_secs * 1_000.0; + + if stats.rows_written != rows { + return Err(ParquetBarsError::Parquet { + path: temp.path.join("bars_1d"), + source: ParquetError::General(format!( + "writer row count mismatch: expected {rows}, stats reported {}", + stats.rows_written + )), + }); + } + + let read_back_rows = + verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), rows)?; + + let (rows_per_sec, _) = compute_rates(rows, elapsed_secs); + let mb_per_sec = if elapsed_secs > 0.0 && elapsed_secs.is_finite() { + (stats.bytes_written as f64 / (1024.0 * 1024.0)) / elapsed_secs + } else { + 0.0 + }; + let bytes_per_row = stats.bytes_written as f64 / rows as f64; + let raw_bytes = (rows as f64) * (PARQUET_BARS_RAW_ROW_BYTES as f64); + let compression_ratio = if stats.bytes_written > 0 { + raw_bytes / (stats.bytes_written as f64) + } else { + 0.0 + }; + + drop(temp); + + Ok(( + ParquetBarsBenchReport { + rows, + read_back_rows, + listing_count, + files_written: stats.files_written, + row_groups_written: stats.row_groups_written, + bytes_written: stats.bytes_written, + raw_row_bytes: PARQUET_BARS_RAW_ROW_BYTES, + elapsed_ms, + rows_per_sec, + mb_per_sec, + bytes_per_row, + compression_ratio, + }, + temp_path, + )) +} + +/// Runs the fixed-seed Zstd Parquet `bars_1d` writer benchmark for `rows` sorted daily bars +/// spanning `2006..=2025` across `>= 2,000` listings, reads back Parquet footer row counts, +/// and deletes its temporary output directory. +pub fn run_parquet_bars_benchmark(rows: usize) -> Result { + let (report, _) = run_parquet_bars_benchmark_tracked(rows)?; + Ok(report) +} + #[cfg(test)] mod tests { use super::*; @@ -752,4 +2114,280 @@ mod tests { assert_eq!(report.rows_per_sec, 0.0); assert_eq!(report.ns_per_row, 0.0); } + + #[test] + fn fx_benchmark_small_run_is_deterministic() { + let a = run_fx_benchmark(2_000); + let b = run_fx_benchmark(2_000); + + assert_eq!(a.rows, 2_000); + assert_eq!(a.eod_rows_in + a.te_rows_in, 2_000); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.lookups, DEFAULT_FX_BENCH_LOOKUPS); + assert_eq!(a.lookup_hits, b.lookup_hits); + assert!(a.lookup_hits > 0 && a.lookup_hits < a.lookups); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.build_rows_per_sec.is_finite() && a.build_rows_per_sec >= 0.0); + assert!(a.build_ns_per_row.is_finite() && a.build_ns_per_row >= 0.0); + assert!(a.lookups_per_sec.is_finite() && a.lookups_per_sec >= 0.0); + assert!(a.ns_per_lookup.is_finite() && a.ns_per_lookup >= 0.0); + assert!(a.stats.eod.dropped_invalid_ohlc > 0); + assert!(a.stats.eod.dropped_inconsistent_ohlc > 0); + assert!(a.stats.eod.duplicate_collapsed > 0); + assert!(a.stats.eod.duplicate_conflict_dropped > 0); + assert!(a.stats.te_superseded_by_eod > 0); + assert!(a.stats.overlap_within_tolerance > 0); + assert!(a.stats.overlap_mismatched > 0); + assert!(a.stats.te_rows_out > 0); + } + + #[test] + fn fx_benchmark_zero_rows_handles_cleanly() { + let report = run_fx_benchmark(0); + assert_eq!(report.rows, 0); + assert_eq!(report.eod_rows_in, 0); + assert_eq!(report.te_rows_in, 0); + assert_eq!(report.rows_out, 0); + assert_eq!(report.lookups, 0); + assert_eq!(report.lookup_hits, 0); + assert_eq!(report.stats, Fx1dStats::default()); + assert_eq!(report.checksum, 0); + assert_eq!(report.build_rows_per_sec, 0.0); + assert_eq!(report.build_ns_per_row, 0.0); + assert_eq!(report.lookups_per_sec, 0.0); + assert_eq!(report.ns_per_lookup, 0.0); + } + + #[test] + fn next_weekday_skips_saturdays_and_sundays() { + let thu = ymd_to_epoch_days(2025, 1, 2).unwrap(); + let fri = ymd_to_epoch_days(2025, 1, 3).unwrap(); + let sat = ymd_to_epoch_days(2025, 1, 4).unwrap(); + let sun = ymd_to_epoch_days(2025, 1, 5).unwrap(); + let mon = ymd_to_epoch_days(2025, 1, 6).unwrap(); + + assert_eq!(next_weekday(thu), fri); + assert_eq!(next_weekday(fri), mon); + assert_eq!(next_weekday(sat), mon); + assert_eq!(next_weekday(sun), mon); + } + + #[test] + fn shorts_benchmark_small_run_is_deterministic() { + let a = run_shorts_benchmark(5_000).unwrap(); + let b = run_shorts_benchmark(5_000).unwrap(); + + assert_eq!(a.rows, 5_000); + assert_eq!(a.stats.rows_in, 5_000); + assert_eq!(a.key_count, SHORTS_BENCH_KEY_COUNT); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.keys_out, b.keys_out); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.ns_per_row.is_finite() && a.ns_per_row >= 0.0); + assert!(a.stats.dropped_invalid_shares_short > 0); + assert!(a.stats.nulled_invalid_net_change > 0); + assert!(a.stats.nulled_invalid_pct_float > 0); + assert!(a.stats.duplicate_collapsed > 0); + assert!(a.stats.duplicate_conflict_dropped > 0); + } + + #[test] + fn shorts_benchmark_zero_rows_handles_cleanly() { + let report = run_shorts_benchmark(0).unwrap(); + assert_eq!(report.rows, 0); + assert_eq!(report.key_count, SHORTS_BENCH_KEY_COUNT); + assert_eq!(report.rows_out, 0); + assert_eq!(report.keys_out, 0); + assert_eq!(report.stats, ShortsStats::default()); + assert_eq!(report.checksum, 0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.ns_per_row, 0.0); + } + + #[test] + fn events_benchmark_small_run_is_deterministic() { + let a = run_events_benchmark(20_000); + let b = run_events_benchmark(20_000); + + assert_eq!(a.rows, 20_000); + assert_eq!(a.filings_in + a.earnings_in, 20_000); + assert_eq!(a.stats.filings_in, a.filings_in); + assert_eq!(a.stats.earnings_in, a.earnings_in); + assert_eq!(a.key_count, BENCH_KEY_COUNT); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.keys_out, b.keys_out); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.ns_per_row.is_finite() && a.ns_per_row >= 0.0); + assert!(a.stats.filings_out > 0); + assert!(a.stats.filings_skipped_malformed_timestamp > 0); + assert!(a.stats.filings_skipped_unknown_zone > 0); + assert!(a.stats.filings_skipped_invalid_date_time > 0); + assert!(a.stats.filings_duplicate_collapsed > 0); + assert!(a.stats.earnings_linked_to_filing > 0); + assert!(a.stats.earnings_lagged_1605 > 0); + } + + #[test] + fn events_benchmark_zero_rows_handles_cleanly() { + let report = run_events_benchmark(0); + assert_eq!(report.rows, 0); + assert_eq!(report.filings_in, 0); + assert_eq!(report.earnings_in, 0); + assert_eq!(report.key_count, BENCH_KEY_COUNT); + assert_eq!(report.rows_out, 0); + assert_eq!(report.keys_out, 0); + assert_eq!(report.stats, EventsStats::default()); + assert_eq!(report.checksum, 0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.ns_per_row, 0.0); + } + + #[test] + fn provider_mapping_benchmark_small_run_is_deterministic() { + let a = run_provider_mapping_benchmark(50_000).unwrap(); + let b = run_provider_mapping_benchmark(50_000).unwrap(); + + assert_eq!(a.key_count, PROVIDER_MAPPING_BENCH_KEY_COUNT); + assert_eq!(a.key_count, b.key_count); + assert_eq!(a.range_count, b.range_count); + assert!(a.range_count > a.key_count); + assert_eq!(a.multi_range_keys, b.multi_range_keys); + assert_eq!(a.multi_range_keys, PROVIDER_MAPPING_BENCH_KEY_COUNT / 10); + assert_eq!(a.lookups, 50_000); + assert_eq!(a.hits + a.misses, a.lookups); + assert_eq!(a.hits, b.hits); + assert_eq!(a.misses, b.misses); + assert!(a.hits > 0 && a.misses > 0); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + assert!(a.build_rows_per_sec.is_finite() && a.build_rows_per_sec >= 0.0); + assert!(a.lookups_per_sec.is_finite() && a.lookups_per_sec >= 0.0); + assert!(a.ns_per_lookup.is_finite() && a.ns_per_lookup >= 0.0); + } + + #[test] + fn provider_mapping_benchmark_zero_lookups_handles_cleanly() { + let report = run_provider_mapping_benchmark(0).unwrap(); + assert_eq!(report.key_count, PROVIDER_MAPPING_BENCH_KEY_COUNT); + assert!(report.range_count > report.key_count); + assert_eq!( + report.multi_range_keys, + PROVIDER_MAPPING_BENCH_KEY_COUNT / 10 + ); + assert_eq!(report.lookups, 0); + assert_eq!(report.hits, 0); + assert_eq!(report.misses, 0); + assert_eq!(report.lookup_elapsed_ms, 0.0); + assert_eq!(report.lookups_per_sec, 0.0); + assert_eq!(report.ns_per_lookup, 0.0); + assert_eq!(report.checksum, 0); + } + + #[test] + fn parquet_bars_benchmark_small_run_is_deterministic_and_cleans_up() { + let (a, dir_a) = run_parquet_bars_benchmark_tracked(10_000).unwrap(); + let (b, dir_b) = run_parquet_bars_benchmark_tracked(10_000).unwrap(); + + assert!(!dir_a.exists(), "temp dir {} should be removed", dir_a.display()); + assert!(!dir_b.exists(), "temp dir {} should be removed", dir_b.display()); + assert_eq!(a.rows, 10_000); + assert_eq!(a.read_back_rows, 10_000); + assert_eq!(a.listing_count, PARQUET_BARS_BENCH_BASE_LISTINGS); + assert_eq!(a.files_written, b.files_written); + assert!(a.files_written >= 2); + assert_eq!(a.row_groups_written, b.row_groups_written); + assert_eq!(a.bytes_written, b.bytes_written); + assert!(a.bytes_written > 0); + assert_eq!(a.raw_row_bytes, PARQUET_BARS_RAW_ROW_BYTES); + assert!(a.rows_per_sec.is_finite() && a.rows_per_sec >= 0.0); + assert!(a.mb_per_sec.is_finite() && a.mb_per_sec >= 0.0); + assert!(a.bytes_per_row.is_finite() && a.bytes_per_row > 0.0); + assert!(a.compression_ratio.is_finite() && a.compression_ratio > 0.0); + } + + #[test] + fn parquet_bars_benchmark_zero_rows_handles_cleanly() { + let (report, dir) = run_parquet_bars_benchmark_tracked(0).unwrap(); + assert!(!dir.exists(), "temp dir {} should be removed", dir.display()); + assert_eq!(report.rows, 0); + assert_eq!(report.read_back_rows, 0); + assert_eq!(report.listing_count, 0); + assert_eq!(report.files_written, 0); + assert_eq!(report.row_groups_written, 0); + assert_eq!(report.bytes_written, 0); + assert_eq!(report.raw_row_bytes, PARQUET_BARS_RAW_ROW_BYTES); + assert_eq!(report.elapsed_ms, 0.0); + assert_eq!(report.rows_per_sec, 0.0); + assert_eq!(report.mb_per_sec, 0.0); + assert_eq!(report.bytes_per_row, 0.0); + assert_eq!(report.compression_ratio, 0.0); + } + + #[test] + fn verify_parquet_bars_row_count_returns_error_on_mismatch() { + let temp = BenchTempDir::new().unwrap(); + let weekdays = collect_bench_weekdays_2006_2025(); + let iter = ParquetBarsBenchIter::new(250, weekdays); + let stats = + write_bars_1d_dataset(&temp.path, iter, Bars1dWriteOptions::default()).unwrap(); + + let matched = + verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), 250) + .unwrap(); + assert_eq!(matched, 250); + + let err = + verify_parquet_bars_row_count(&temp.path, stats.rows_by_year.keys().copied(), 255) + .unwrap_err(); + let msg = err.to_string(); + assert!( + matches!(err, ParquetBarsError::Parquet { .. }), + "expected Parquet error, got {err:?}" + ); + assert!( + msg.contains("255") && msg.contains("250"), + "error must report expected (255) and actual (250) row counts, got: {msg}" + ); + + let err_zero = verify_parquet_bars_row_count(&temp.path, std::iter::empty(), 10) + .unwrap_err(); + let msg_zero = err_zero.to_string(); + assert!( + msg_zero.contains("10") && msg_zero.contains('0'), + "error must report expected (10) and actual (0) row counts, got: {msg_zero}" + ); + } + + #[test] + fn bench_temp_dir_retries_on_collision_and_preserves_existing_dir() { + let root = BenchTempDir::new().unwrap(); + let pid = std::process::id(); + let next_seq = BENCH_TEMP_DIR_SEQ.load(AtomicOrdering::Relaxed); + let colliding = root + .path + .join(format!("curate-etl-bench-pq-bars-{pid}-{next_seq}")); + fs::create_dir(&colliding).unwrap(); + let sentinel = colliding.join("keep.txt"); + fs::write(&sentinel, b"do-not-delete").unwrap(); + + let created_path = { + let dir = BenchTempDir::new_in(&root.path).unwrap(); + assert_ne!(dir.path, colliding); + assert!(dir.path.is_dir()); + assert_eq!(fs::read(&sentinel).unwrap(), b"do-not-delete"); + dir.path.clone() + }; + + assert!(!created_path.exists()); + assert!(colliding.is_dir()); + assert_eq!(fs::read(&sentinel).unwrap(), b"do-not-delete"); + } } diff --git a/tools/curate-etl/src/cli.rs b/tools/curate-etl/src/cli.rs index a3f7e591..b03e400c 100644 --- a/tools/curate-etl/src/cli.rs +++ b/tools/curate-etl/src/cli.rs @@ -5,7 +5,9 @@ use crate::bench::{ DEFAULT_ADJ_BENCH_EVENTS, DEFAULT_BARS_BENCH_ROWS, DEFAULT_BENCH_ROWS, - DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, + DEFAULT_CORPORATE_ACTIONS_BENCH_EVENTS, DEFAULT_EVENTS_BENCH_ROWS, DEFAULT_FX_BENCH_ROWS, + DEFAULT_PARQUET_BARS_BENCH_ROWS, DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, + DEFAULT_SHORTS_BENCH_ROWS, }; /// Parsed CLI command to execute. @@ -17,6 +19,11 @@ pub enum CliAction { BenchAdj(usize), BenchCorporateActions(usize), BenchBars(usize), + BenchFx(usize), + BenchShorts(usize), + BenchEvents(usize), + BenchProviderMapping(usize), + BenchParquetBars(usize), } /// Formats full help text including binary name and version. @@ -30,7 +37,12 @@ pub fn format_usage(name: &str, version: &str) -> String { {name} bench-split [rows] Run fixed-seed split lookup + un-adjust benchmark (default: {DEFAULT_BENCH_ROWS})\n\ {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})" + {name} bench-bars [rows] Run fixed-seed bars_1d build + cross-check benchmark (default: {DEFAULT_BARS_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-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})" ) } @@ -43,7 +55,12 @@ pub fn format_usage_stderr(name: &str) -> String { {name} bench-split [rows]\n\ {name} bench-adj [events]\n\ {name} bench-corporate-actions [events]\n\ - {name} bench-bars [rows]" + {name} bench-bars [rows]\n\ + {name} bench-fx [rows]\n\ + {name} bench-shorts [rows]\n\ + {name} bench-events [rows]\n\ + {name} bench-provider-mapping [lookups]\n\ + {name} bench-parquet-bars [rows]" ) } @@ -92,6 +109,54 @@ pub fn parse_args(args: &[String]) -> Result { )), }, ["bench-bars", _, ..] => Err("too many arguments for bench-bars".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)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-fx", _, ..] => Err("too many arguments for bench-fx".to_string()), + ["bench-shorts"] => Ok(CliAction::BenchShorts(DEFAULT_SHORTS_BENCH_ROWS)), + ["bench-shorts", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchShorts(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-shorts", _, ..] => Err("too many arguments for bench-shorts".to_string()), + ["bench-events"] => Ok(CliAction::BenchEvents(DEFAULT_EVENTS_BENCH_ROWS)), + ["bench-events", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchEvents(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-events", _, ..] => Err("too many arguments for bench-events".to_string()), + ["bench-provider-mapping"] => Ok(CliAction::BenchProviderMapping( + DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS, + )), + ["bench-provider-mapping", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchProviderMapping(n)), + _ => Err(format!( + "invalid lookup count '{raw}' (expected a positive integer)" + )), + }, + ["bench-provider-mapping", _, ..] => { + Err("too many arguments for bench-provider-mapping".to_string()) + } + ["bench-parquet-bars"] => Ok(CliAction::BenchParquetBars( + DEFAULT_PARQUET_BARS_BENCH_ROWS, + )), + ["bench-parquet-bars", raw] => match raw.parse::() { + Ok(n) if n > 0 => Ok(CliAction::BenchParquetBars(n)), + _ => Err(format!( + "invalid row count '{raw}' (expected a positive integer)" + )), + }, + ["bench-parquet-bars", _, ..] => { + Err("too many arguments for bench-parquet-bars".to_string()) + } [other, ..] => Err(format!("unknown argument '{other}'")), } } @@ -193,6 +258,88 @@ mod tests { assert!(parse_args(&to_args(&["bench-bars", "10", "20"])).is_err()); } + #[test] + fn parses_and_validates_bench_fx_args() { + assert_eq!( + parse_args(&to_args(&["bench-fx"])), + Ok(CliAction::BenchFx(DEFAULT_FX_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-fx", "5000"])), + Ok(CliAction::BenchFx(5_000)) + ); + assert!(parse_args(&to_args(&["bench-fx", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-fx", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-fx", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-fx", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_shorts_args() { + assert_eq!( + parse_args(&to_args(&["bench-shorts"])), + Ok(CliAction::BenchShorts(DEFAULT_SHORTS_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-shorts", "50000"])), + Ok(CliAction::BenchShorts(50_000)) + ); + assert!(parse_args(&to_args(&["bench-shorts", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-shorts", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-shorts", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-shorts", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_events_args() { + assert_eq!( + parse_args(&to_args(&["bench-events"])), + Ok(CliAction::BenchEvents(DEFAULT_EVENTS_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-events", "50000"])), + Ok(CliAction::BenchEvents(50_000)) + ); + assert!(parse_args(&to_args(&["bench-events", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-events", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-events", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-events", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_provider_mapping_args() { + assert_eq!( + parse_args(&to_args(&["bench-provider-mapping"])), + Ok(CliAction::BenchProviderMapping( + DEFAULT_PROVIDER_MAPPING_BENCH_LOOKUPS + )) + ); + assert_eq!( + parse_args(&to_args(&["bench-provider-mapping", "250000"])), + Ok(CliAction::BenchProviderMapping(250_000)) + ); + assert!(parse_args(&to_args(&["bench-provider-mapping", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-provider-mapping", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-provider-mapping", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-provider-mapping", "10", "20"])).is_err()); + } + + #[test] + fn parses_and_validates_bench_parquet_bars_args() { + assert_eq!( + parse_args(&to_args(&["bench-parquet-bars"])), + Ok(CliAction::BenchParquetBars(DEFAULT_PARQUET_BARS_BENCH_ROWS)) + ); + assert_eq!( + parse_args(&to_args(&["bench-parquet-bars", "250000"])), + Ok(CliAction::BenchParquetBars(250_000)) + ); + assert!(parse_args(&to_args(&["bench-parquet-bars", "0"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-bars", "-5"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-bars", "abc"])).is_err()); + assert!(parse_args(&to_args(&["bench-parquet-bars", "10", "20"])).is_err()); + } + #[test] fn usage_strings_mention_all_benchmarks() { let full = format_usage("curate-etl", "0.1.0"); @@ -200,11 +347,21 @@ mod tests { assert!(full.contains("bench-adj")); assert!(full.contains("bench-corporate-actions")); assert!(full.contains("bench-bars")); + assert!(full.contains("bench-fx")); + assert!(full.contains("bench-shorts")); + assert!(full.contains("bench-events")); + assert!(full.contains("bench-provider-mapping")); + assert!(full.contains("bench-parquet-bars")); let short = format_usage_stderr("curate-etl"); assert!(short.contains("bench-split")); assert!(short.contains("bench-adj")); assert!(short.contains("bench-corporate-actions")); assert!(short.contains("bench-bars")); + assert!(short.contains("bench-fx")); + assert!(short.contains("bench-shorts")); + assert!(short.contains("bench-events")); + assert!(short.contains("bench-provider-mapping")); + assert!(short.contains("bench-parquet-bars")); } } diff --git a/tools/curate-etl/src/events.rs b/tools/curate-etl/src/events.rs new file mode 100644 index 00000000..9c9ef553 --- /dev/null +++ b/tools/curate-etl/src/events.rs @@ -0,0 +1,1157 @@ +//! Pure, in-memory `events` builder (`qmFilings` `timefiled` → UTC + form groups; `qmEarnings` +//! linked to same-day `8-K` / `News release` filing or conservatively lagged to `16:05 ET`). +//! +//! Produces deterministically sorted [`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 `year=YYYY` +//! partitioning. +//! +//! ## Point-in-time & Provenance Rules +//! - **Filings (`kind = "filing"`):** `timefiled` is parsed strictly as `YYYY-MM-DDTHH:MM:SS EST` +//! (`UTC-5`) or `YYYY-MM-DDTHH:MM:SS EDT` (`UTC-4`). Using the explicit zone abbreviation's +//! fixed offset avoids DST calendar range limits so pre-2008 filings convert cleanly. +//! `ts_micros = known_at_micros = UTC(timefiled)` with `known_at_source = "filing_timestamp"`. +//! *Caveat:* EDGAR filings accepted after `17:30 ET` are not shifted to the next business day +//! here (per the M1.2g contract); downstream intraday studies should apply exchange-session +//! routing / post-`17:30 ET` visibility rules on top of `known_at_micros`. +//! - **Earnings (`kind = "earnings"`):** +//! 1. If the same `key` has a qualifying filing (`8-K` or `News release`, including amendments) +//! whose local ET calendar date matches `report_date`, `known_at_micros` is the earliest such +//! filing's UTC timestamp (`known_at_source = "filing_timestamp"`). +//! 2. Otherwise `known_at_micros = report_date 16:05:00 America/Toronto` via +//! [`crate::shorts::et_to_utc_micros`] (`known_at_source = "statutory_lag_estimate"`). +//! This conservative fallback is intended for T+1 open use (not same-day intraday cutoffs, +//! since a later same-date `8-K` / `News release` filing supersedes the fallback with its +//! actual filing timestamp). It applies to `N/A`, `BTO`, and `AMC` rows alike whenever no +//! linked filing provides a verified timestamp—unlinked `BTO`/`AMC` rows are never stamped +//! earlier than `16:05 ET`. +//! 3. Unlinked `report_date` values outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` +//! (`2008-01-01..=2030-12-31`) are skipped and counted (`earnings_skipped_out_of_range`). +//! 4. Post-hoc overwritten `consensusEps` is deliberately omitted from [`QmEarning`] and +//! earnings `payload_json` per `design/DATA-CONTRACTS.md` §1. + +use std::error::Error; +use std::fmt::{self, Write as _}; + +use crate::shorts::{epoch_days_to_ymd, et_to_utc_micros}; +use crate::split::ymd_to_epoch_days; + +/// Canonical `kind` label for `qmFilings` rows. +pub const EVENT_KIND_FILING: &str = "filing"; + +/// Canonical `kind` label for `qmEarnings` rows. +pub const EVENT_KIND_EARNINGS: &str = "earnings"; + +/// Provenance label when `known_at_micros` comes directly from a parsed `qmFilings.timefiled`. +pub const KNOWN_AT_SOURCE_FILING_TIMESTAMP: &str = "filing_timestamp"; + +/// Provenance label when an unlinked earnings row falls back to `report_date 16:05 ET`. +pub const KNOWN_AT_SOURCE_STATUTORY_LAG: &str = "statutory_lag_estimate"; + +/// Conservative fallback hour (`16:05 America/Toronto`) for unlinked earnings rows. +pub const EARNINGS_FALLBACK_HOUR_ET: u8 = 16; + +/// Conservative fallback minute (`16:05 America/Toronto`) for unlinked earnings rows. +pub const EARNINGS_FALLBACK_MINUTE_ET: u8 = 5; + +const MICROS_PER_DAY: i64 = 86_400_000_000; + +/// Returns the UTC Gregorian calendar year for `ts_micros` (microseconds since +/// `1970-01-01T00:00:00Z`), used for `events/year=YYYY/part.parquet` partitioning. +#[inline] +pub fn partition_year_utc(ts_micros: i64) -> i32 { + let epoch_day = ts_micros.div_euclid(MICROS_PER_DAY) as i32; + epoch_days_to_ymd(epoch_day).0 +} + +/// Typed parse errors returned by [`parse_filing_timefiled`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FilingTimeError { + /// Input did not match the exact 19-byte ASCII `YYYY-MM-DDTHH:MM:SS` prefix structure. + MalformedFormat, + /// Input had a valid timestamp prefix but was missing a zone or used a zone other than + /// `" EST"` or `" EDT"`. + UnknownZone, + /// Calendar date components were not a valid Gregorian date (e.g., `2025-02-30`). + InvalidDate, + /// Clock components were outside `00:00:00..=23:59:59`. + InvalidTime, +} + +impl fmt::Display for FilingTimeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::MalformedFormat => { + write!(f, "malformed filing timestamp (expected YYYY-MM-DDTHH:MM:SS EST|EDT)") + } + Self::UnknownZone => { + write!(f, "missing or unsupported filing time zone (expected ' EST' or ' EDT')") + } + Self::InvalidDate => write!(f, "invalid Gregorian calendar date in filing timestamp"), + Self::InvalidTime => { + write!(f, "invalid wall-clock time in filing timestamp (expected 00:00:00..=23:59:59)") + } + } + } +} + +impl Error for FilingTimeError {} + +/// Parsed `qmFilings.timefiled` carrying both the UTC instant and the local ET calendar date. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ParsedFilingTime { + /// UTC timestamp in microseconds since `1970-01-01T00:00:00Z`. + pub utc_micros: i64, + /// Local Eastern Time calendar date as days since `1970-01-01` (used for same-day earnings + /// linking even when late-evening ET crosses into the next UTC calendar day). + pub et_date: i32, +} + +#[inline] +fn parse_2_digits(bytes: &[u8], offset: usize) -> Option { + let a = bytes[offset]; + let b = bytes[offset + 1]; + if a.is_ascii_digit() && b.is_ascii_digit() { + Some(u32::from(a - b'0') * 10 + u32::from(b - b'0')) + } else { + None + } +} + +#[inline] +fn parse_4_digits(bytes: &[u8], offset: usize) -> Option { + let hi = parse_2_digits(bytes, offset)?; + let lo = parse_2_digits(bytes, offset + 2)?; + Some((hi * 100 + lo) as i32) +} + +/// Strictly parses a `qmFilings.timefiled` string of the form `YYYY-MM-DDTHH:MM:SS EST` or +/// `YYYY-MM-DDTHH:MM:SS EDT`. +/// +/// Uses the explicit zone abbreviation's fixed offset (`EST = UTC-5`, `EDT = UTC-4`) so historical +/// pre-2008 filings convert without DST table range restrictions. Never panics and never guesses +/// on malformed strings, unknown zones, or invalid calendar dates/times. +pub fn parse_filing_timefiled(raw: &str) -> Result { + let bytes = raw.as_bytes(); + if bytes.len() < 19 + || bytes[4] != b'-' + || bytes[7] != b'-' + || bytes[10] != b'T' + || bytes[13] != b':' + || bytes[16] != b':' + { + return Err(FilingTimeError::MalformedFormat); + } + + let year = parse_4_digits(bytes, 0).ok_or(FilingTimeError::MalformedFormat)?; + let month = parse_2_digits(bytes, 5).ok_or(FilingTimeError::MalformedFormat)?; + let day = parse_2_digits(bytes, 8).ok_or(FilingTimeError::MalformedFormat)?; + let hour = parse_2_digits(bytes, 11).ok_or(FilingTimeError::MalformedFormat)?; + let minute = parse_2_digits(bytes, 14).ok_or(FilingTimeError::MalformedFormat)?; + let second = parse_2_digits(bytes, 17).ok_or(FilingTimeError::MalformedFormat)?; + + let offset_hours: i64 = match &bytes[19..] { + b" EST" => 5, + b" EDT" => 4, + _ => return Err(FilingTimeError::UnknownZone), + }; + + let et_date = ymd_to_epoch_days(year, month, day).map_err(|_| FilingTimeError::InvalidDate)?; + if hour > 23 || minute > 59 || second > 59 { + return Err(FilingTimeError::InvalidTime); + } + + let local_secs = i64::from(hour) * 3_600 + i64::from(minute) * 60 + i64::from(second); + let utc_secs = i64::from(et_date) * 86_400 + local_secs + offset_hours * 3_600; + Ok(ParsedFilingTime { + utc_micros: utc_secs * 1_000_000, + et_date, + }) +} + +/// Canonical form-group classification for US EDGAR and Canadian SEDAR+ filings. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum FilingFormGroup { + Form10K, + Form10Q, + Form8K, + Form4, + Form144, + Form40F, + InterimFinancials, + AnnualFinancials, + Mda, + Form52109, + Ni43101, + Form45106F1, + NewsRelease, + Other, +} + +impl FilingFormGroup { + /// Canonical lowercase `subtype` string written to [`EventRow::subtype`]. + #[inline] + pub const fn as_str(self) -> &'static str { + match self { + Self::Form10K => "10-k", + Self::Form10Q => "10-q", + Self::Form8K => "8-k", + Self::Form4 => "4", + Self::Form144 => "144", + Self::Form40F => "40-f", + Self::InterimFinancials => "interim_financial_statements", + Self::AnnualFinancials => "annual_financial_statements", + Self::Mda => "mda", + Self::Form52109 => "52-109", + Self::Ni43101 => "ni_43_101", + Self::Form45106F1 => "45-106f1", + Self::NewsRelease => "news_release", + Self::Other => "other", + } + } + + /// Returns `true` iff this form group is a periodic financial report eligible for the M2 + /// `fundamentals_pit` filing join (`10-K`, `10-Q`, `40-F`, `Interim financial statements`, + /// `Annual financial statements`). + #[inline] + pub const fn is_periodic_financial_report(self) -> bool { + matches!( + self, + Self::Form10K + | Self::Form10Q + | Self::Form40F + | Self::InterimFinancials + | Self::AnnualFinancials + ) + } + + /// Returns `true` iff this form group may anchor a same-day `qmEarnings` announcement time + /// (`8-K` or `News release`). + #[inline] + pub const fn is_earnings_link_candidate(self) -> bool { + matches!(self, Self::Form8K | Self::NewsRelease) + } +} + +/// Exact-match EDGAR form table (checked after stripping optional `/A` amendment suffix). +/// Keeping EDGAR codes exact prevents `"4"` from falsely matching `"40-F"`, `"424B5"`, or +/// `"45-106F1"`. +const EXACT_EDGAR_FORM_RULES: &[(&str, FilingFormGroup)] = &[ + ("10-K", FilingFormGroup::Form10K), + ("10-Q", FilingFormGroup::Form10Q), + ("8-K", FilingFormGroup::Form8K), + ("4", FilingFormGroup::Form4), + ("144", FilingFormGroup::Form144), + ("40-F", FilingFormGroup::Form40F), +]; + +/// Fixed-priority substring rules for Canadian SEDAR+ filing descriptions. +const SEDAR_SUBSTRING_RULES: &[(&str, FilingFormGroup)] = &[ + ("INTERIM FINANCIAL STATEMENTS", FilingFormGroup::InterimFinancials), + ("INTERIM FINANCIAL REPORT", FilingFormGroup::InterimFinancials), + ("ANNUAL FINANCIAL STATEMENTS", FilingFormGroup::AnnualFinancials), + ("MD&A", FilingFormGroup::Mda), + ("MANAGEMENT'S DISCUSSION AND ANALYSIS", FilingFormGroup::Mda), + ("52-109", FilingFormGroup::Form52109), + ("43-101", FilingFormGroup::Ni43101), + ("45-106F1", FilingFormGroup::Form45106F1), + ("NEWS RELEASE", FilingFormGroup::NewsRelease), +]; + +/// Returns `true` iff `upper` contains `"AMENDED"` as a standalone ASCII token (not embedded in a +/// longer word such as `"UNAMENDED"`). +fn contains_standalone_amended(upper: &str) -> bool { + let bytes = upper.as_bytes(); + let needle = "AMENDED"; + let mut offset = 0; + while let Some(rel) = upper[offset..].find(needle) { + let start = offset + rel; + let end = start + needle.len(); + let left_ok = start == 0 || !bytes[start - 1].is_ascii_alphanumeric(); + let right_ok = end == bytes.len() || !bytes[end].is_ascii_alphanumeric(); + if left_ok && right_ok { + return true; + } + offset = start + 1; + } + false +} + +/// Strips leading/trailing amendment markers (`/A`, `(AMENDED)`, or standalone `AMENDED` with +/// adjacent whitespace/punctuation separators) from an uppercased form label so exact EDGAR codes +/// such as `"10-K (Amended)"` or `"Amended 10-Q"` retain their underlying form group. +fn strip_amendment_markers(mut s: &str) -> (&str, bool) { + let mut stripped_any = false; + loop { + let trimmed = s.trim(); + let next = if let Some(prefix) = trimmed.strip_suffix("/A") { + Some(prefix.trim_end()) + } else if let Some(prefix) = trimmed.strip_suffix("(AMENDED)") { + Some(prefix.trim_end_matches(|c: char| { + c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':') + })) + } else if let Some(suffix) = trimmed.strip_prefix("(AMENDED)") { + Some(suffix.trim_start_matches(|c: char| { + c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':') + })) + } else if let Some(prefix) = trimmed.strip_suffix("AMENDED") { + if prefix + .as_bytes() + .last() + .is_some_and(|&b| b.is_ascii_whitespace() || matches!(b, b'-' | b',' | b':')) + { + Some(prefix.trim_end_matches(|c: char| { + c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':') + })) + } else { + None + } + } else if let Some(suffix) = trimmed.strip_prefix("AMENDED") { + if suffix + .as_bytes() + .first() + .is_some_and(|&b| b.is_ascii_whitespace() || matches!(b, b'-' | b',' | b':')) + { + Some(suffix.trim_start_matches(|c: char| { + c.is_ascii_whitespace() || matches!(c, '-' | ',' | ':') + })) + } else { + None + } + } else { + None + }; + + match next { + Some(rest) => { + stripped_any = true; + s = rest; + } + None => { + s = trimmed; + break; + } + } + } + (s, stripped_any) +} + +/// Classifies a raw `qmFilings.form_type` into `(FilingFormGroup, is_amendment)`. +/// +/// - Trims ASCII whitespace and compares case-insensitively. +/// - Detects and strips `/A` suffixes (e.g. `10-K/A`, `8-K/A`, `40-F/A`) and standalone +/// `"amended"` markers (e.g. `10-K (Amended)`, `10-Q - Amended`, `Amended 40-F`) before exact +/// EDGAR matching so amendments retain their underlying [`FilingFormGroup`]. +/// - Checks exact EDGAR codes first, then SEDAR+ substring rules in fixed priority order, +/// defaulting to [`FilingFormGroup::Other`]. +pub fn classify_form_type(form_type: &str) -> (FilingFormGroup, bool) { + let trimmed = form_type.trim(); + if trimmed.is_empty() { + return (FilingFormGroup::Other, false); + } + + let upper = trimmed.to_ascii_uppercase(); + let (base, stripped_amendment) = strip_amendment_markers(&upper); + let is_amendment = stripped_amendment || contains_standalone_amended(base); + + for &(code, group) in EXACT_EDGAR_FORM_RULES { + if base == code { + return (group, is_amendment); + } + } + + for &(needle, group) in SEDAR_SUBSTRING_RULES { + if base.contains(needle) { + return (group, is_amendment); + } + } + + (FilingFormGroup::Other, is_amendment) +} + +/// Convenience predicate returning `true` iff `form_type` classifies as a periodic financial +/// report (`10-K`, `10-Q`, `40-F`, `Interim financial statements`, `Annual financial statements`, +/// including amendments). +#[inline] +pub fn is_periodic_financial_report(form_type: &str) -> bool { + classify_form_type(form_type) + .0 + .is_periodic_financial_report() +} + +/// Normalizes `qmEarnings.announceTime` into `"bto"`, `"amc"`, or `"unknown"`. +#[inline] +pub fn normalize_announce_time(raw: &str) -> &'static str { + let trimmed = raw.trim(); + if trimmed.eq_ignore_ascii_case("bto") { + "bto" + } else if trimmed.eq_ignore_ascii_case("amc") { + "amc" + } else { + "unknown" + } +} + +/// A single raw `qmFilings` input record. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QmFiling { + pub key: K, + /// Raw Eastern timestamp string, e.g. `"2025-01-31T06:01:27 EST"`. + pub timefiled: String, + /// Raw EDGAR or SEDAR+ form type string, e.g. `"10-K/A"` or `"News release"`. + pub form_type: String, + /// Optional provider filing / accession identifier included in `payload_json`. + pub filing_id: Option, + /// Optional filing document URL included in `payload_json`. + pub url: Option, +} + +/// A single raw `qmEarnings` input record. +/// +/// Deliberately omits `consensusEps`, which is overwritten post-hoc in `qmEarnings` per +/// `design/DATA-CONTRACTS.md` §1 and is not point-in-time safe. +#[derive(Debug, Clone, PartialEq)] +pub struct QmEarning { + pub key: K, + /// Earnings report calendar date (ET) as days since `1970-01-01` (UTC Gregorian). + pub report_date: i32, + /// Raw provider announce-time code (`"BTO"`, `"AMC"`, `"N/A"`, etc.). + pub announce_time: String, + /// Optional fiscal period end date as days since `1970-01-01`. + pub fiscal_period_end: Option, + /// Optional reported actual EPS (non-finite values emit as `null` in `payload_json`). + pub actual_eps: Option, + /// Optional reported revenue (non-finite values emit as `null` in `payload_json`). + pub revenue: Option, +} + +/// A single curated `events` row matching `events/year=YYYY/part.parquet`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EventRow { + pub key: K, + /// Event timestamp in UTC microseconds since `1970-01-01T00:00:00Z`. + pub ts_micros: i64, + /// Point-in-time availability timestamp in UTC microseconds since `1970-01-01T00:00:00Z`. + pub known_at_micros: i64, + /// Provenance of `known_at_micros` (`"filing_timestamp"` or `"statutory_lag_estimate"`). + pub known_at_source: &'static str, + /// Event category (`"filing"` or `"earnings"`). + pub kind: &'static str, + /// Normalized form group (filings) or announce time (`"bto"` / `"amc"` / `"unknown"`, earnings). + pub subtype: String, + /// Compact RFC 8259 JSON object with stable key ordering. + pub payload_json: String, +} + +impl EventRow { + /// Returns the UTC Gregorian partition year of [`Self::ts_micros`] (`year=YYYY`). + #[inline] + pub fn partition_year(&self) -> i32 { + partition_year_utc(self.ts_micros) + } +} + +/// Exact per-kind accounting counters produced alongside [`EventsBuild::rows`]. +/// +/// Conservation invariants: +/// - `filings_in == filings_out + filings_skipped_malformed_timestamp + filings_skipped_unknown_zone + filings_skipped_invalid_date_time + filings_duplicate_collapsed` +/// - `earnings_in == earnings_out + earnings_skipped_out_of_range + earnings_duplicate_collapsed + earnings_duplicate_conflict_dropped` +/// - `earnings_out == earnings_linked_to_filing + earnings_lagged_1605` +/// - `rows_out == filings_out + earnings_out` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct EventsStats { + pub filings_in: usize, + pub filings_out: usize, + pub filings_skipped_malformed_timestamp: usize, + pub filings_skipped_unknown_zone: usize, + pub filings_skipped_invalid_date_time: usize, + pub filings_duplicate_collapsed: usize, + pub earnings_in: usize, + pub earnings_out: usize, + pub earnings_linked_to_filing: usize, + pub earnings_lagged_1605: usize, + pub earnings_skipped_out_of_range: usize, + pub earnings_duplicate_collapsed: usize, + pub earnings_duplicate_conflict_dropped: usize, + pub rows_out: usize, + pub keys_out: usize, +} + +/// Output of [`build_events`]: deterministically sorted `events` rows and reconciling stats. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EventsBuild { + pub rows: Vec>, + pub stats: EventsStats, +} + +#[inline] +fn sanitize_opt_f64(value: Option) -> Option { + match value { + Some(v) if v.is_finite() => Some(if v == 0.0 { 0.0 } else { v }), + _ => None, + } +} + +const HEX_LOWER: &[u8; 16] = b"0123456789abcdef"; + +fn push_json_str(out: &mut String, s: &str) { + out.push('"'); + let bytes = s.as_bytes(); + let mut start = 0usize; + for (idx, &b) in bytes.iter().enumerate() { + let escaped = match b { + b'"' => Some("\\\""), + b'\\' => Some("\\\\"), + 0x08 => Some("\\b"), + 0x0C => Some("\\f"), + b'\n' => Some("\\n"), + b'\r' => Some("\\r"), + b'\t' => Some("\\t"), + 0x00..=0x1F => { + if start < idx { + out.push_str(&s[start..idx]); + } + out.push_str("\\u00"); + out.push(HEX_LOWER[(b >> 4) as usize] as char); + out.push(HEX_LOWER[(b & 0x0F) as usize] as char); + start = idx + 1; + continue; + } + _ => None, + }; + if let Some(esc) = escaped { + if start < idx { + out.push_str(&s[start..idx]); + } + out.push_str(esc); + start = idx + 1; + } + } + if start < bytes.len() { + out.push_str(&s[start..]); + } + out.push('"'); +} + +#[inline] +fn push_json_opt_str(out: &mut String, s: Option<&str>) { + match s { + Some(v) => push_json_str(out, v), + None => out.push_str("null"), + } +} + +#[inline] +fn push_json_opt_f64(out: &mut String, v: Option) { + match sanitize_opt_f64(v) { + Some(x) => { + let _ = write!(out, "{x}"); + } + None => out.push_str("null"), + } +} + +#[inline] +fn push_json_date(out: &mut String, epoch_day: i32) { + let (y, m, d) = epoch_days_to_ymd(epoch_day); + let _ = write!(out, "\"{y:04}-{m:02}-{d:02}\""); +} + +#[inline] +fn push_json_opt_date(out: &mut String, epoch_day: Option) { + match epoch_day { + Some(d) => push_json_date(out, d), + None => out.push_str("null"), + } +} + +/// Encodes a filing event's `payload_json` as a compact RFC 8259 JSON object with stable key +/// ordering: `{"filing_id":...,"form_type":...,"is_amendment":...,"url":...}`. +pub fn encode_filing_payload_json( + filing_id: Option<&str>, + form_type: &str, + is_amendment: bool, + url: Option<&str>, +) -> String { + let cap = 56 + + filing_id.map_or(4, str::len) + + form_type.len() + + url.map_or(4, str::len); + let mut out = String::with_capacity(cap); + out.push_str("{\"filing_id\":"); + push_json_opt_str(&mut out, filing_id); + out.push_str(",\"form_type\":"); + push_json_str(&mut out, form_type); + out.push_str(",\"is_amendment\":"); + out.push_str(if is_amendment { "true" } else { "false" }); + out.push_str(",\"url\":"); + push_json_opt_str(&mut out, url); + out.push('}'); + out +} + +/// Encodes an earnings event's `payload_json` as a compact RFC 8259 JSON object with stable key +/// ordering: +/// `{"actual_eps":...,"announce_time":...,"fiscal_period_end":...,"linked_filing_id":...,"report_date":"YYYY-MM-DD","revenue":...}`. +/// +/// Non-finite numeric values emit as `null`, `-0.0` normalizes to `0.0`, and `consensusEps` is +/// deliberately omitted. +pub fn encode_earnings_payload_json( + actual_eps: Option, + announce_time: &str, + fiscal_period_end: Option, + linked_filing_id: Option<&str>, + report_date: i32, + revenue: Option, +) -> String { + let cap = 112 + announce_time.len() + linked_filing_id.map_or(4, str::len); + let mut out = String::with_capacity(cap); + out.push_str("{\"actual_eps\":"); + push_json_opt_f64(&mut out, actual_eps); + out.push_str(",\"announce_time\":"); + push_json_str(&mut out, announce_time); + out.push_str(",\"fiscal_period_end\":"); + push_json_opt_date(&mut out, fiscal_period_end); + out.push_str(",\"linked_filing_id\":"); + push_json_opt_str(&mut out, linked_filing_id); + out.push_str(",\"report_date\":"); + push_json_date(&mut out, report_date); + out.push_str(",\"revenue\":"); + push_json_opt_f64(&mut out, revenue); + out.push('}'); + out +} + +struct QualifyingLink { + key: K, + et_date: i32, + utc_micros: i64, + filing_id: Option, + form_type: String, + url: Option, +} + +struct NormalizedEarning { + key: K, + report_date: i32, + ts_micros: i64, + known_at_source: &'static str, + is_linked: bool, + link_idx: Option, + subtype: &'static str, + fiscal_period_end: Option, + actual_eps: Option, + revenue: Option, +} + +impl NormalizedEarning { + #[inline] + fn values_bit_eq(&self, other: &Self) -> bool { + self.subtype == other.subtype + && self.fiscal_period_end == other.fiscal_period_end + && self.actual_eps.map(f64::to_bits) == other.actual_eps.map(f64::to_bits) + && self.revenue.map(f64::to_bits) == other.revenue.map(f64::to_bits) + } +} + +/// Builds deterministically sorted point-in-time `events` rows from raw `qmFilings` and +/// `qmEarnings` streams. +/// +/// Infallible: malformed timestamps, unknown zones, invalid dates/times, and out-of-range +/// unlinked earnings dates are counted in [`EventsStats`] and skipped without panicking. +/// Any permutation of `filings` and `earnings` produces identical `rows` and `stats`. +pub fn build_events(filings: IF, earnings: IE) -> EventsBuild +where + K: Ord + Clone, + IF: IntoIterator>, + IE: IntoIterator>, +{ + let filings_iter = filings.into_iter(); + let (filings_lower, _) = filings_iter.size_hint(); + let mut stats = EventsStats::default(); + let mut rows: Vec> = Vec::with_capacity(filings_lower); + let mut links: Vec> = Vec::new(); + + for filing in filings_iter { + stats.filings_in += 1; + + let parsed = match parse_filing_timefiled(&filing.timefiled) { + Ok(p) => p, + Err(FilingTimeError::MalformedFormat) => { + stats.filings_skipped_malformed_timestamp += 1; + continue; + } + Err(FilingTimeError::UnknownZone) => { + stats.filings_skipped_unknown_zone += 1; + continue; + } + Err(FilingTimeError::InvalidDate | FilingTimeError::InvalidTime) => { + stats.filings_skipped_invalid_date_time += 1; + continue; + } + }; + + let (group, is_amendment) = classify_form_type(&filing.form_type); + let payload_json = encode_filing_payload_json( + filing.filing_id.as_deref(), + &filing.form_type, + is_amendment, + filing.url.as_deref(), + ); + + if group.is_earnings_link_candidate() { + links.push(QualifyingLink { + key: filing.key.clone(), + et_date: parsed.et_date, + utc_micros: parsed.utc_micros, + filing_id: filing.filing_id, + form_type: filing.form_type, + url: filing.url, + }); + } + + rows.push(EventRow { + key: filing.key, + ts_micros: parsed.utc_micros, + known_at_micros: parsed.utc_micros, + known_at_source: KNOWN_AT_SOURCE_FILING_TIMESTAMP, + kind: EVENT_KIND_FILING, + subtype: group.as_str().to_string(), + payload_json, + }); + } + + // Retain the strictly earliest deterministic qualifying filing per (key, et_date). + links.sort_unstable_by(|a, b| { + a.key + .cmp(&b.key) + .then_with(|| a.et_date.cmp(&b.et_date)) + .then_with(|| a.utc_micros.cmp(&b.utc_micros)) + .then_with(|| a.filing_id.cmp(&b.filing_id)) + .then_with(|| a.form_type.cmp(&b.form_type)) + .then_with(|| a.url.cmp(&b.url)) + }); + links.dedup_by(|later, earlier| earlier.key == later.key && earlier.et_date == later.et_date); + + // Collapse exact duplicate filing rows. + rows.sort_unstable_by(|a, b| { + a.key + .cmp(&b.key) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + }); + let filings_before_dedup = rows.len(); + rows.dedup_by(|b, a| { + a.key == b.key + && a.ts_micros == b.ts_micros + && a.subtype == b.subtype + && a.payload_json == b.payload_json + }); + stats.filings_duplicate_collapsed = filings_before_dedup - rows.len(); + stats.filings_out = rows.len(); + + // Scan and resolve earnings rows against qualifying links or 16:05 ET fallback. + let earnings_iter = earnings.into_iter(); + let (earnings_lower, _) = earnings_iter.size_hint(); + let mut norm_earnings: Vec> = Vec::with_capacity(earnings_lower); + + for earning in earnings_iter { + stats.earnings_in += 1; + + let link_lookup = links.binary_search_by(|l| { + l.key + .cmp(&earning.key) + .then_with(|| l.et_date.cmp(&earning.report_date)) + }); + + let (ts_micros, known_at_source, is_linked, link_idx) = match link_lookup { + Ok(idx) => ( + links[idx].utc_micros, + KNOWN_AT_SOURCE_FILING_TIMESTAMP, + true, + Some(idx), + ), + Err(_) => match et_to_utc_micros( + earning.report_date, + EARNINGS_FALLBACK_HOUR_ET, + EARNINGS_FALLBACK_MINUTE_ET, + 0, + ) { + Ok(utc) => (utc, KNOWN_AT_SOURCE_STATUTORY_LAG, false, None), + Err(_) => { + stats.earnings_skipped_out_of_range += 1; + continue; + } + }, + }; + + norm_earnings.push(NormalizedEarning { + key: earning.key, + report_date: earning.report_date, + ts_micros, + known_at_source, + is_linked, + link_idx, + subtype: normalize_announce_time(&earning.announce_time), + fiscal_period_end: earning.fiscal_period_end, + actual_eps: sanitize_opt_f64(earning.actual_eps), + revenue: sanitize_opt_f64(earning.revenue), + }); + } + + norm_earnings.sort_unstable_by(|a, b| { + a.key + .cmp(&b.key) + .then_with(|| a.report_date.cmp(&b.report_date)) + }); + + // Reserve only the exact upper bound for earnings rows so appending a small earnings batch + // onto a multi-million-row filings vector does not double the vector's capacity. + rows.reserve_exact(norm_earnings.len()); + let len = norm_earnings.len(); + let mut read_idx = 0usize; + while read_idx < len { + let mut group_end = read_idx + 1; + while group_end < len + && norm_earnings[group_end].key == norm_earnings[read_idx].key + && norm_earnings[group_end].report_date == norm_earnings[read_idx].report_date + { + group_end += 1; + } + + let group_len = group_end - read_idx; + let first = &norm_earnings[read_idx]; + let all_identical = norm_earnings[read_idx + 1..group_end] + .iter() + .all(|other| first.values_bit_eq(other)); + + if all_identical { + stats.earnings_duplicate_collapsed += group_len - 1; + if first.is_linked { + stats.earnings_linked_to_filing += 1; + } else { + stats.earnings_lagged_1605 += 1; + } + + let linked_filing_id = first + .link_idx + .and_then(|idx| links[idx].filing_id.as_deref()); + let payload_json = encode_earnings_payload_json( + first.actual_eps, + first.subtype, + first.fiscal_period_end, + linked_filing_id, + first.report_date, + first.revenue, + ); + rows.push(EventRow { + key: first.key.clone(), + ts_micros: first.ts_micros, + known_at_micros: first.ts_micros, + known_at_source: first.known_at_source, + kind: EVENT_KIND_EARNINGS, + subtype: first.subtype.to_string(), + payload_json, + }); + } else { + stats.earnings_duplicate_conflict_dropped += group_len; + } + + read_idx = group_end; + } + + stats.earnings_out = stats.earnings_linked_to_filing + stats.earnings_lagged_1605; + + rows.sort_unstable_by(|a, b| { + a.key + .cmp(&b.key) + .then_with(|| a.ts_micros.cmp(&b.ts_micros)) + .then_with(|| a.kind.cmp(b.kind)) + .then_with(|| a.subtype.cmp(&b.subtype)) + .then_with(|| a.payload_json.cmp(&b.payload_json)) + .then_with(|| a.known_at_micros.cmp(&b.known_at_micros)) + .then_with(|| a.known_at_source.cmp(b.known_at_source)) + }); + + stats.rows_out = rows.len(); + let mut keys_out = 0usize; + let mut prev_key: Option<&K> = None; + for row in &rows { + if prev_key != Some(&row.key) { + keys_out += 1; + prev_key = Some(&row.key); + } + } + stats.keys_out = keys_out; + + EventsBuild { rows, stats } +} + +#[cfg(test)] +mod tests { + use super::*; + + 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 assert_invariants(build: &EventsBuild) { + let s = &build.stats; + assert_eq!( + s.filings_in, + s.filings_out + + s.filings_skipped_malformed_timestamp + + s.filings_skipped_unknown_zone + + s.filings_skipped_invalid_date_time + + s.filings_duplicate_collapsed, + "filing accounting mismatch: {s:?}" + ); + assert_eq!( + s.earnings_in, + s.earnings_out + + s.earnings_skipped_out_of_range + + s.earnings_duplicate_collapsed + + s.earnings_duplicate_conflict_dropped, + "earnings accounting mismatch: {s:?}" + ); + assert_eq!( + s.earnings_out, + s.earnings_linked_to_filing + s.earnings_lagged_1605 + ); + assert_eq!(s.rows_out, s.filings_out + s.earnings_out); + assert_eq!(s.rows_out, build.rows.len()); + + for pair in build.rows.windows(2) { + assert!( + ( + &pair[0].key, + pair[0].ts_micros, + pair[0].kind, + &pair[0].subtype, + &pair[0].payload_json + ) <= ( + &pair[1].key, + pair[1].ts_micros, + pair[1].kind, + &pair[1].subtype, + &pair[1].payload_json + ), + "rows must be deterministically sorted" + ); + } + } + + #[test] + fn parse_filing_timefiled_converts_est_edt_leap_and_pre_2008_exact_to_microsecond() { + let est = parse_filing_timefiled("2025-01-31T06:01:27 EST").unwrap(); + assert_eq!(est.utc_micros, utc_micros(2025, 1, 31, 11, 1, 27)); + assert_eq!(est.et_date, day(2025, 1, 31)); + + let edt = parse_filing_timefiled("2025-07-15T16:30:45 EDT").unwrap(); + assert_eq!(edt.utc_micros, utc_micros(2025, 7, 15, 20, 30, 45)); + assert_eq!(edt.et_date, day(2025, 7, 15)); + + let pre_2008 = parse_filing_timefiled("2003-07-15T14:30:00 EDT").unwrap(); + assert_eq!(pre_2008.utc_micros, utc_micros(2003, 7, 15, 18, 30, 0)); + assert_eq!(pre_2008.et_date, day(2003, 7, 15)); + + let leap = parse_filing_timefiled("2024-02-29T23:45:10 EST").unwrap(); + assert_eq!(leap.utc_micros, utc_micros(2024, 3, 1, 4, 45, 10)); + assert_eq!(leap.et_date, day(2024, 2, 29)); + } + + #[test] + fn parse_filing_timefiled_rejects_malformed_unknown_zone_and_invalid_dates_times() { + for bad in [ + "", + "2025-01-31 06:01:27 EST", + "2025/01/31T06:01:27 EST", + "2025-1-31T06:01:27 EST", + "not-a-timestamp", + ] { + assert_eq!( + parse_filing_timefiled(bad), + Err(FilingTimeError::MalformedFormat), + "expected MalformedFormat for {bad:?}" + ); + } + + for bad_zone in [ + "2025-01-31T06:01:27", + "2025-01-31T06:01:27 PST", + "2025-01-31T06:01:27 UTC", + "2025-01-31T06:01:27Z", + "2025-01-31T06:01:27 est", + "2025-01-31T06:01:27 EST ", + ] { + assert_eq!( + parse_filing_timefiled(bad_zone), + Err(FilingTimeError::UnknownZone), + "expected UnknownZone for {bad_zone:?}" + ); + } + + for bad_date in [ + "2025-02-30T06:01:27 EST", + "2025-02-29T06:01:27 EST", + "2025-13-01T06:01:27 EST", + "2025-00-10T06:01:27 EST", + ] { + assert_eq!( + parse_filing_timefiled(bad_date), + Err(FilingTimeError::InvalidDate), + "expected InvalidDate for {bad_date:?}" + ); + } + + for bad_time in [ + "2025-01-31T24:00:00 EST", + "2025-01-31T25:00:00 EST", + "2025-01-31T12:60:00 EST", + "2025-01-31T12:00:60 EST", + ] { + assert_eq!( + parse_filing_timefiled(bad_time), + Err(FilingTimeError::InvalidTime), + "expected InvalidTime for {bad_time:?}" + ); + } + } + + #[test] + fn classify_form_type_covers_all_edgar_sedar_amendments_and_negative_cases() { + let cases = [ + ("10-K", FilingFormGroup::Form10K, false, true, false), + ("10-K/A", FilingFormGroup::Form10K, true, true, false), + ("10-K (Amended)", FilingFormGroup::Form10K, true, true, false), + ("10-K/A (Amended)", FilingFormGroup::Form10K, true, true, false), + (" 10-q ", FilingFormGroup::Form10Q, false, true, false), + ("10-Q/A", FilingFormGroup::Form10Q, true, true, false), + ("10-Q - Amended", FilingFormGroup::Form10Q, true, true, false), + ("8-K", FilingFormGroup::Form8K, false, false, true), + ("8-K/A", FilingFormGroup::Form8K, true, false, true), + ("8-K (Amended)", FilingFormGroup::Form8K, true, false, true), + ("4", FilingFormGroup::Form4, false, false, false), + ("4/A", FilingFormGroup::Form4, true, false, false), + ("144", FilingFormGroup::Form144, false, false, false), + ("40-F", FilingFormGroup::Form40F, false, true, false), + ("40-F/A", FilingFormGroup::Form40F, true, true, false), + ("Amended 40-F", FilingFormGroup::Form40F, true, true, false), + ("UNAMENDED", FilingFormGroup::Other, false, false, false), + ( + "Interim financial statements/report", + FilingFormGroup::InterimFinancials, + false, + true, + false, + ), + ( + "Amended interim financial statements/report", + FilingFormGroup::InterimFinancials, + true, + true, + false, + ), + ( + "Annual financial statements", + FilingFormGroup::AnnualFinancials, + false, + true, + false, + ), + ("MD&A", FilingFormGroup::Mda, false, false, false), + ("52-109", FilingFormGroup::Form52109, false, false, false), + ("NI 43-101", FilingFormGroup::Ni43101, false, false, false), + ("45-106F1", FilingFormGroup::Form45106F1, false, false, false), + ( + "News release", + FilingFormGroup::NewsRelease, + false, + false, + true, + ), + ("424B5", FilingFormGroup::Other, false, false, false), + ("S-3", FilingFormGroup::Other, false, false, false), + ("DEF 14A", FilingFormGroup::Other, false, false, false), + ("", FilingFormGroup::Other, false, false, false), + ]; + + for (raw, expected_group, expected_amend, expected_periodic, expected_link) in cases { + let (group, is_amend) = classify_form_type(raw); + assert_eq!(group, expected_group, "group mismatch for {raw:?}"); + assert_eq!(is_amend, expected_amend, "amendment mismatch for {raw:?}"); + assert_eq!( + group.is_periodic_financial_report(), + expected_periodic, + "periodic mismatch for {raw:?}" + ); + assert_eq!( + is_periodic_financial_report(raw), + expected_periodic, + "free predicate mismatch for {raw:?}" + ); + assert_eq!( + group.is_earnings_link_candidate(), + expected_link, + "link candidate mismatch for {raw:?}" + ); + } + } + + #[test] + fn json_encoding_escapes_special_chars_and_handles_non_finite_numbers() { + let filing_json = encode_filing_payload_json( + Some("acc-\"1\"\\x\n\t\x00\x1f"), + "10-K/A", + true, + Some("https://example.com/café"), + ); + assert_eq!( + filing_json, + "{\"filing_id\":\"acc-\\\"1\\\"\\\\x\\n\\t\\u0000\\u001f\",\"form_type\":\"10-K/A\",\"is_amendment\":true,\"url\":\"https://example.com/café\"}" + ); + + let earnings_json = encode_earnings_payload_json( + Some(f64::NAN), + "unknown", + Some(day(2024, 12, 31)), + None, + day(2025, 1, 31), + Some(-0.0), + ); + assert_eq!( + earnings_json, + "{\"actual_eps\":null,\"announce_time\":\"unknown\",\"fiscal_period_end\":\"2024-12-31\",\"linked_filing_id\":null,\"report_date\":\"2025-01-31\",\"revenue\":0}" + ); + assert!(!earnings_json.contains("consensusEps")); + assert!(!earnings_json.contains("consensus_eps")); + } + + #[test] + fn partition_year_utc_tracks_utc_year_across_year_end_et_rollover() { + let late_dec31 = parse_filing_timefiled("2024-12-31T21:30:00 EST").unwrap(); + assert_eq!(late_dec31.et_date, day(2024, 12, 31)); + assert_eq!(partition_year_utc(late_dec31.utc_micros), 2025); + + let mid_dec31 = parse_filing_timefiled("2024-12-31T16:00:00 EST").unwrap(); + assert_eq!(partition_year_utc(mid_dec31.utc_micros), 2024); + } + + #[test] + fn build_events_empty_and_basic_reconciliation() { + let empty = build_events::(Vec::new(), Vec::new()); + assert!(empty.rows.is_empty()); + assert_eq!(empty.stats, EventsStats::default()); + assert_invariants(&empty); + } +} diff --git a/tools/curate-etl/src/fx.rs b/tools/curate-etl/src/fx.rs new file mode 100644 index 00000000..7353bc80 --- /dev/null +++ b/tools/curate-etl/src/fx.rs @@ -0,0 +1,658 @@ +//! Pure, in-memory `fx_1d` USD/CAD builder (`CAD.FOREX` + `teMarketData.USDCAD`). +//! +//! Produces sorted, unique per-`session_date` USD/CAD rows (CAD per 1 USD) matching the +//! `fx_1d/part.parquet` value columns in `design/DATA-CONTRACTS.md` (excluding `ts`/`known_at` +//! timestamps, which belong to the later writer task). +//! +//! Rules: +//! - Both input streams are USD/CAD quotes (CAD per 1 USD); no inversion is performed here. +//! - Bad single rows never panic or abort the build; each source is filtered in strict priority +//! order (`dropped_invalid_ohlc`, then `dropped_inconsistent_ohlc`) and deduplicated on +//! `session_date` (bitwise-identical duplicates collapse; conflicting duplicate groups drop +//! entirely). +//! - Merge precedence: `EodCadForex` wins on overlapping dates (counting `te_superseded_by_eod`), +//! while `TeUsdCad` fills interior gaps and dates after EOD's last date. +//! - Overlap cross-check is strictly read-only: on every date where both sources survive, checks +//! `|eod.close - te.close| / eod.close <= FX_OVERLAP_REL_TOLERANCE` (1%) and tracks +//! `max_overlap_rel` without modifying emitted rows. +//! - [`fx_rate_on_or_before`] provides no-look-ahead binary-search lookup with bounded staleness. + +use std::cmp::Ordering; +use std::fmt; + +/// Canonical currency pair label emitted on every [`Fx1dRow`]. +pub const FX_PAIR_USDCAD: &str = "USDCAD"; + +/// Relative close-price tolerance (1%) for the read-only EOD vs. TE overlap cross-check. +pub const FX_OVERLAP_REL_TOLERANCE: f64 = 0.01; + +/// IEEE-754 rounding slack for the inclusive [`FX_OVERLAP_REL_TOLERANCE`] boundary so decimal +/// USD/CAD quotes that are mathematically exactly 1% apart (e.g. `1.4000` vs. `1.4140`, where +/// `(1.4140 - 1.4000) / 1.4000 = 0.010000000000000009`) are not falsely flagged as mismatches. +const FX_OVERLAP_REL_ROUNDING_EPS: f64 = 4.0 * f64::EPSILON; + +/// Provenance source for a curated `fx_1d` USD/CAD row. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum FxSource { + /// EODHD `CAD.FOREX` daily history (1971–2025). + EodCadForex, + /// TradingEconomics `teMarketData.USDCAD` daily history (fills gaps and tail through 2026+). + TeUsdCad, +} + +impl FxSource { + /// Canonical lowercase snake_case label written to the `source` column. + #[inline] + pub const fn as_str(self) -> &'static str { + match self { + Self::EodCadForex => "eod_cad_forex", + Self::TeUsdCad => "te_usdcad", + } + } +} + +impl fmt::Display for FxSource { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// A single raw daily USD/CAD FX bar (CAD per 1 USD). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct FxDailyBar { + /// Session date as days since `1970-01-01` (UTC Gregorian, matching [`crate::ymd_to_epoch_days`]). + pub session_date: i32, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, +} + +/// A single curated `fx_1d` row, sorted and unique by `session_date`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Fx1dRow { + pub pair: &'static str, + pub session_date: i32, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + pub source: FxSource, +} + +/// Per-source filtering and deduplication counters. +/// +/// Conservation invariant: +/// `rows_in == rows_kept + dropped_invalid_ohlc + dropped_inconsistent_ohlc + duplicate_collapsed + duplicate_conflict_dropped` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct FxSourceStats { + pub rows_in: usize, + pub rows_kept: usize, + pub dropped_invalid_ohlc: usize, + pub dropped_inconsistent_ohlc: usize, + pub duplicate_collapsed: usize, + pub duplicate_conflict_dropped: usize, +} + +/// Summary counters and read-only overlap audit metrics produced alongside [`Fx1dBuild::rows`]. +/// +/// Conservation invariants: +/// - Per source (`eod`, `te`): +/// `rows_in == rows_kept + dropped_invalid_ohlc + dropped_inconsistent_ohlc + duplicate_collapsed + duplicate_conflict_dropped` +/// - Output merge: +/// `rows_out == eod.rows_kept + te.rows_kept - te_superseded_by_eod` +/// and `rows_out == eod_rows_out + te_rows_out` +/// - Overlap cross-check: +/// `overlap_within_tolerance + overlap_mismatched == overlap_checked == te_superseded_by_eod` +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct Fx1dStats { + pub eod: FxSourceStats, + pub te: FxSourceStats, + pub rows_out: usize, + pub eod_rows_out: usize, + pub te_rows_out: usize, + pub te_superseded_by_eod: usize, + pub overlap_checked: usize, + pub overlap_within_tolerance: usize, + pub overlap_mismatched: usize, + pub max_overlap_rel: f64, +} + +/// Output of [`build_fx_1d`]: sorted, unique USD/CAD rows and exact accounting/overlap stats. +#[derive(Debug, Clone, PartialEq)] +pub struct Fx1dBuild { + pub rows: Vec, + pub stats: Fx1dStats, +} + +#[inline] +fn is_valid_rate(rate: f64) -> bool { + rate.is_finite() && rate > 0.0 +} + +#[inline] +fn bar_values_bit_eq(a: &FxDailyBar, b: &FxDailyBar) -> 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() +} + +/// Filters, sorts, and deduplicates one FX source in strict priority order: +/// 1. Drop invalid OHLC (any field non-finite or `<= 0.0`). +/// 2. Drop inconsistent OHLC (`high < low`, or `open`/`close` outside `[low, high]`). +/// 3. Sort by `session_date` and compact in-place: bitwise-identical duplicates collapse to one; +/// conflicting duplicate groups drop entirely. +fn clean_source(input: &[FxDailyBar]) -> (Vec, FxSourceStats) { + let mut stats = FxSourceStats { + rows_in: input.len(), + ..FxSourceStats::default() + }; + let mut valid = Vec::with_capacity(input.len()); + + for &bar in input { + if !is_valid_rate(bar.open) + || !is_valid_rate(bar.high) + || !is_valid_rate(bar.low) + || !is_valid_rate(bar.close) + { + stats.dropped_invalid_ohlc += 1; + continue; + } + if bar.high < bar.low + || bar.open < bar.low + || bar.open > bar.high + || bar.close < bar.low + || bar.close > bar.high + { + stats.dropped_inconsistent_ohlc += 1; + continue; + } + valid.push(bar); + } + + valid.sort_unstable_by_key(|b| b.session_date); + + let len = valid.len(); + let mut write_idx = 0usize; + let mut read_idx = 0usize; + + while read_idx < len { + let session_date = valid[read_idx].session_date; + let mut group_end = read_idx + 1; + while group_end < len && valid[group_end].session_date == session_date { + group_end += 1; + } + let group_len = group_end - read_idx; + let first = valid[read_idx]; + let all_identical = valid[read_idx + 1..group_end] + .iter() + .all(|other| bar_values_bit_eq(&first, other)); + + if all_identical { + stats.duplicate_collapsed += group_len - 1; + if write_idx != read_idx { + valid[write_idx] = first; + } + write_idx += 1; + } else { + stats.duplicate_conflict_dropped += group_len; + } + read_idx = group_end; + } + + valid.truncate(write_idx); + stats.rows_kept = valid.len(); + (valid, stats) +} + +#[inline] +fn to_fx_row(bar: FxDailyBar, source: FxSource) -> Fx1dRow { + Fx1dRow { + pair: FX_PAIR_USDCAD, + session_date: bar.session_date, + open: bar.open, + high: bar.high, + low: bar.low, + close: bar.close, + source, + } +} + +/// Builds a sorted, unique `fx_1d` USD/CAD series by merging `CAD.FOREX` (`eod`) and +/// `teMarketData.USDCAD` (`te`). +/// +/// - Never panics or aborts on single-row data errors. +/// - `EodCadForex` takes precedence on overlapping dates; `TeUsdCad` fills interior gaps and +/// dates after EOD's last date (as well as dates where EOD dropped an invalid or conflicting +/// group). +/// - On every overlapping date where both sources survive, performs a read-only relative close +/// cross-check against [`FX_OVERLAP_REL_TOLERANCE`] (1%) without mutating emitted rows. +/// - Any permutation of `eod` or `te` yields bitwise-identical `rows` and `stats`. +pub fn build_fx_1d(eod: &[FxDailyBar], te: &[FxDailyBar]) -> Fx1dBuild { + let (eod_clean, eod_stats) = clean_source(eod); + let (te_clean, te_stats) = clean_source(te); + + let mut stats = Fx1dStats { + eod: eod_stats, + te: te_stats, + ..Fx1dStats::default() + }; + + let mut rows = Vec::with_capacity(eod_clean.len() + te_clean.len()); + let mut i = 0usize; + let mut j = 0usize; + + while i < eod_clean.len() && j < te_clean.len() { + let e = eod_clean[i]; + let t = te_clean[j]; + match e.session_date.cmp(&t.session_date) { + Ordering::Less => { + rows.push(to_fx_row(e, FxSource::EodCadForex)); + stats.eod_rows_out += 1; + i += 1; + } + Ordering::Greater => { + rows.push(to_fx_row(t, FxSource::TeUsdCad)); + stats.te_rows_out += 1; + j += 1; + } + Ordering::Equal => { + rows.push(to_fx_row(e, FxSource::EodCadForex)); + stats.eod_rows_out += 1; + stats.te_superseded_by_eod += 1; + stats.overlap_checked += 1; + + let rel = (e.close - t.close).abs() / e.close; + if rel > stats.max_overlap_rel { + stats.max_overlap_rel = rel; + } + if rel <= FX_OVERLAP_REL_TOLERANCE + FX_OVERLAP_REL_ROUNDING_EPS { + stats.overlap_within_tolerance += 1; + } else { + stats.overlap_mismatched += 1; + } + + i += 1; + j += 1; + } + } + } + + while i < eod_clean.len() { + rows.push(to_fx_row(eod_clean[i], FxSource::EodCadForex)); + stats.eod_rows_out += 1; + i += 1; + } + + while j < te_clean.len() { + rows.push(to_fx_row(te_clean[j], FxSource::TeUsdCad)); + stats.te_rows_out += 1; + j += 1; + } + + stats.rows_out = rows.len(); + + Fx1dBuild { rows, stats } +} + +/// Binary-search lookup of the latest [`Fx1dRow`] in `rows` (assumed sorted ascending by +/// `session_date`, as returned by [`build_fx_1d`]) with `session_date <= date` and +/// `date - session_date <= max_stale_days`. +/// +/// Carries forward across weekends and holidays up to `max_stale_days`, never looks ahead to a +/// later date, and returns `None` if `rows` is empty, `date` precedes the first row, or the +/// latest prior row is older than `max_stale_days`. +#[inline] +pub fn fx_rate_on_or_before( + rows: &[Fx1dRow], + date: i32, + max_stale_days: u32, +) -> Option<&Fx1dRow> { + let idx = rows.partition_point(|r| r.session_date <= date); + if idx == 0 { + return None; + } + let candidate = &rows[idx - 1]; + let age = i64::from(date) - i64::from(candidate.session_date); + if age <= i64::from(max_stale_days) { + Some(candidate) + } else { + None + } +} + +#[cfg(test)] +mod tests { + 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).unwrap() + } + + fn bar(session_date: i32, open: f64, high: f64, low: f64, close: f64) -> FxDailyBar { + FxDailyBar { + session_date, + open, + high, + low, + close, + } + } + + fn flat(session_date: i32, rate: f64) -> FxDailyBar { + bar(session_date, rate, rate, rate, rate) + } + + fn assert_invariants(build: &Fx1dBuild) { + let s = &build.stats; + assert_eq!( + s.eod.rows_in, + s.eod.rows_kept + + s.eod.dropped_invalid_ohlc + + s.eod.dropped_inconsistent_ohlc + + s.eod.duplicate_collapsed + + s.eod.duplicate_conflict_dropped, + "eod accounting invariant failed: {s:?}" + ); + assert_eq!( + s.te.rows_in, + s.te.rows_kept + + s.te.dropped_invalid_ohlc + + s.te.dropped_inconsistent_ohlc + + s.te.duplicate_collapsed + + s.te.duplicate_conflict_dropped, + "te accounting invariant failed: {s:?}" + ); + assert_eq!( + s.rows_out, + s.eod.rows_kept + s.te.rows_kept - s.te_superseded_by_eod, + "merge accounting invariant failed: {s:?}" + ); + assert_eq!( + s.rows_out, + s.eod_rows_out + s.te_rows_out, + "source split accounting invariant failed: {s:?}" + ); + assert_eq!(s.rows_out, build.rows.len()); + assert_eq!( + s.overlap_within_tolerance + s.overlap_mismatched, + s.overlap_checked, + "overlap tolerance accounting invariant failed: {s:?}" + ); + assert_eq!( + s.overlap_checked, s.te_superseded_by_eod, + "overlap_checked != te_superseded_by_eod: {s:?}" + ); + + for pair in build.rows.windows(2) { + assert!( + pair[0].session_date < pair[1].session_date, + "rows not strictly ascending: {} >= {}", + pair[0].session_date, + pair[1].session_date + ); + } + for row in &build.rows { + assert_eq!(row.pair, FX_PAIR_USDCAD); + } + } + + #[test] + fn empty_inputs_return_empty_rows_and_zeroed_stats() { + let built = build_fx_1d(&[], &[]); + assert!(built.rows.is_empty()); + assert_eq!(built.stats, Fx1dStats::default()); + assert_invariants(&built); + } + + #[test] + fn source_strings_and_display_match_contract() { + assert_eq!(FxSource::EodCadForex.as_str(), "eod_cad_forex"); + assert_eq!(FxSource::TeUsdCad.as_str(), "te_usdcad"); + assert_eq!(format!("{}", FxSource::EodCadForex), "eod_cad_forex"); + assert_eq!(format!("{}", FxSource::TeUsdCad), "te_usdcad"); + } + + #[test] + fn eod_wins_on_overlap_and_te_fills_interior_gaps_and_tail() { + let d1 = day(2025, 1, 2); + let d2 = day(2025, 1, 3); + let d3 = day(2025, 1, 6); + let d4 = day(2026, 1, 2); + + let eod = [ + bar(d1, 1.430, 1.440, 1.425, 1.435), + // d2 missing in EOD -> TE should fill + bar(d3, 1.436, 1.442, 1.430, 1.438), + ]; + let te = [ + bar(d1, 1.431, 1.441, 1.426, 1.436), // overlaps d1 -> EOD wins + bar(d2, 1.434, 1.439, 1.431, 1.437), // interior gap -> TE fills + bar(d4, 1.380, 1.390, 1.375, 1.385), // post-EOD tail -> TE fills + ]; + + let built = build_fx_1d(&eod, &te); + assert_invariants(&built); + assert_eq!(built.rows.len(), 4); + assert_eq!(built.stats.eod_rows_out, 2); + assert_eq!(built.stats.te_rows_out, 2); + assert_eq!(built.stats.te_superseded_by_eod, 1); + assert_eq!(built.stats.overlap_checked, 1); + assert_eq!(built.stats.overlap_within_tolerance, 1); + assert_eq!(built.stats.overlap_mismatched, 0); + + // d1: bitwise-preserved EOD OHLC + assert_eq!(built.rows[0].session_date, d1); + assert_eq!(built.rows[0].source, FxSource::EodCadForex); + assert_eq!(built.rows[0].open.to_bits(), eod[0].open.to_bits()); + assert_eq!(built.rows[0].high.to_bits(), eod[0].high.to_bits()); + assert_eq!(built.rows[0].low.to_bits(), eod[0].low.to_bits()); + assert_eq!(built.rows[0].close.to_bits(), eod[0].close.to_bits()); + + // d2: TE interior gap fill + assert_eq!(built.rows[1].session_date, d2); + assert_eq!(built.rows[1].source, FxSource::TeUsdCad); + assert_eq!(built.rows[1].close.to_bits(), te[1].close.to_bits()); + + // d3: EOD only + assert_eq!(built.rows[2].session_date, d3); + assert_eq!(built.rows[2].source, FxSource::EodCadForex); + + // d4: TE tail fill + assert_eq!(built.rows[3].session_date, d4); + assert_eq!(built.rows[3].source, FxSource::TeUsdCad); + } + + #[test] + fn filters_bad_rows_in_strict_priority_order_without_panicking() { + let base = day(2024, 5, 1); + let eod = [ + // Invalid OHLC (also inconsistent to prove strict priority) + bar(base, f64::NAN, 1.0, 2.0, 1.5), + bar(base + 1, 1.3, f64::INFINITY, 1.2, 1.25), + bar(base + 2, 1.3, 1.4, f64::NEG_INFINITY, 1.25), + bar(base + 3, 1.3, 1.4, 1.2, 0.0), + bar(base + 4, -0.0, 1.4, 1.2, 1.3), + bar(base + 5, 1.3, 1.4, 1.2, -1.2), + // Inconsistent OHLC + bar(base + 6, 1.3, 1.2, 1.4, 1.3), // high < low + bar(base + 7, 1.1, 1.4, 1.2, 1.3), // open < low + bar(base + 8, 1.5, 1.4, 1.2, 1.3), // open > high + bar(base + 9, 1.3, 1.4, 1.2, 1.1), // close < low + bar(base + 10, 1.3, 1.4, 1.2, 1.5), // close > high + // Valid row + bar(base + 11, 1.35, 1.38, 1.34, 1.36), + ]; + + let built = build_fx_1d(&eod, &[]); + assert_invariants(&built); + assert_eq!(built.stats.eod.rows_in, 12); + assert_eq!(built.stats.eod.dropped_invalid_ohlc, 6); + assert_eq!(built.stats.eod.dropped_inconsistent_ohlc, 5); + assert_eq!(built.stats.eod.rows_kept, 1); + assert_eq!(built.rows.len(), 1); + assert_eq!(built.rows[0].session_date, base + 11); + } + + #[test] + fn dedup_collapses_identical_drops_conflicting_and_allows_te_fallback() { + let d1 = day(2024, 6, 1); + let d2 = day(2024, 6, 2); + let d3 = day(2024, 6, 3); + + let eod = [ + // Identical triple -> collapses to 1 + flat(d1, 1.35), + flat(d1, 1.35), + flat(d1, 1.35), + // Conflicting duplicate group in EOD -> dropped entirely; TE on d2 fills it + flat(d2, 1.36), + flat(d2, 1.37), + // Valid + invalid on same date -> invalid filtered early, valid survives + flat(d3, 1.38), + bar(d3, f64::NAN, 1.39, 1.37, 1.38), + ]; + let te = [ + flat(d2, 1.365), + // Conflicting duplicate in TE on d1 -> dropped before merge, no overlap counted + flat(d1, 1.35), + flat(d1, 1.355), + ]; + + let built = build_fx_1d(&eod, &te); + assert_invariants(&built); + assert_eq!(built.stats.eod.duplicate_collapsed, 2); + assert_eq!(built.stats.eod.duplicate_conflict_dropped, 2); + assert_eq!(built.stats.eod.dropped_invalid_ohlc, 1); + assert_eq!(built.stats.eod.rows_kept, 2); + assert_eq!(built.stats.te.duplicate_conflict_dropped, 2); + assert_eq!(built.stats.te.rows_kept, 1); + assert_eq!(built.stats.overlap_checked, 0); + assert_eq!(built.rows.len(), 3); + assert_eq!(built.rows[0].source, FxSource::EodCadForex); + assert_eq!(built.rows[1].session_date, d2); + assert_eq!(built.rows[1].source, FxSource::TeUsdCad); + assert_eq!(built.rows[1].close.to_bits(), 1.365_f64.to_bits()); + assert_eq!(built.rows[2].source, FxSource::EodCadForex); + } + + #[test] + fn overlap_crosscheck_exact_one_percent_boundary_and_read_only() { + let base = day(2024, 7, 1); + // Use exact integers so relative difference at 1% has zero binary rounding error. + let eod = [ + flat(base, 100.0), // te = 101.0 -> rel = 0.01 (within) + flat(base + 1, 100.0), // te = 99.0 -> rel = 0.01 (within) + flat(base + 2, 100.0), // te = 101.01 -> rel = 0.0101 (mismatched) + flat(base + 3, 100.0), // te = 150.0 -> rel = 0.50 (mismatched, never mutates EOD) + ]; + let te = [ + flat(base, 101.0), + flat(base + 1, 99.0), + flat(base + 2, 101.01), + flat(base + 3, 150.0), + ]; + + let built = build_fx_1d(&eod, &te); + assert_invariants(&built); + assert_eq!(built.stats.overlap_checked, 4); + assert_eq!(built.stats.overlap_within_tolerance, 2); + assert_eq!(built.stats.overlap_mismatched, 2); + assert_eq!(built.stats.max_overlap_rel, 0.5); + + for (row, orig) in built.rows.iter().zip(&eod) { + assert_eq!(row.source, FxSource::EodCadForex); + assert_eq!(row.close.to_bits(), orig.close.to_bits()); + } + } + + #[test] + fn overlap_crosscheck_decimal_usdcad_one_percent_boundary_is_rounding_aware() { + let base = day(2025, 4, 1); + // Decimal USD/CAD pairs at exact ±1% (including 1.4000 vs 1.4140 where raw f64 division + // produces 0.010000000000000009) and just outside ±1%. + let eod = [ + flat(base, 1.4000), // te = 1.4140 (+1.0000%, within) + flat(base + 1, 1.4000), // te = 1.3860 (-1.0000%, within) + flat(base + 2, 1.3500), // te = 1.3635 (+1.0000%, within) + flat(base + 3, 1.3500), // te = 1.3365 (-1.0000%, within) + flat(base + 4, 1.3700), // te = 1.3837 (+1.0000%, within) + flat(base + 5, 1.3700), // te = 1.3563 (-1.0000%, within) + flat(base + 6, 1.4000), // te = 1.4141 (+1.0071%, mismatched) + flat(base + 7, 1.4000), // te = 1.3859 (-1.0071%, mismatched) + flat(base + 8, 1.4000), // te = 1.4140001 (+1.000007%, mismatched) + ]; + let te = [ + flat(base, 1.4140), + flat(base + 1, 1.3860), + flat(base + 2, 1.3635), + flat(base + 3, 1.3365), + flat(base + 4, 1.3837), + flat(base + 5, 1.3563), + flat(base + 6, 1.4141), + flat(base + 7, 1.3859), + flat(base + 8, 1.4140001), + ]; + + let built = build_fx_1d(&eod, &te); + assert_invariants(&built); + assert_eq!(built.stats.overlap_checked, 9); + assert_eq!(built.stats.overlap_within_tolerance, 6); + assert_eq!(built.stats.overlap_mismatched, 3); + + // max_overlap_rel retains the raw calculated relative difference. + let expected_max = (1.4000_f64 - 1.4141_f64).abs() / 1.4000_f64; + assert_eq!(built.stats.max_overlap_rel.to_bits(), expected_max.to_bits()); + + // Exact 1.4000 vs 1.4140 alone still records its calculated rel in max_overlap_rel. + let single = build_fx_1d(&[flat(base, 1.4000)], &[flat(base, 1.4140)]); + assert_invariants(&single); + assert_eq!(single.stats.overlap_within_tolerance, 1); + assert_eq!(single.stats.overlap_mismatched, 0); + assert_eq!( + single.stats.max_overlap_rel.to_bits(), + ((1.4000_f64 - 1.4140_f64).abs() / 1.4000_f64).to_bits() + ); + } + + #[test] + fn lookup_on_or_before_covers_exact_carry_forward_stale_and_no_lookahead() { + let fri = day(2025, 1, 3); + let sat = day(2025, 1, 4); + let sun = day(2025, 1, 5); + let mon = day(2025, 1, 6); + let next_mon = day(2025, 1, 13); + + // Empty slice -> None + assert_eq!(fx_rate_on_or_before(&[], fri, 5), None); + + let built = build_fx_1d(&[flat(fri, 1.44), flat(next_mon, 1.45)], &[]); + let rows = &built.rows; + + // Before first row -> None (never looks ahead to Friday) + assert_eq!(fx_rate_on_or_before(rows, fri - 1, 30), None); + + // Exact hit works even with max_stale_days == 0 + assert_eq!(fx_rate_on_or_before(rows, fri, 0), Some(&rows[0])); + assert_eq!(fx_rate_on_or_before(rows, next_mon, 0), Some(&rows[1])); + + // Weekend carry-forward + assert_eq!(fx_rate_on_or_before(rows, sat, 2), Some(&rows[0])); + assert_eq!(fx_rate_on_or_before(rows, sun, 2), Some(&rows[0])); + // Monday is 3 days after Friday: None when max_stale_days == 2, Some when == 3 + assert_eq!(fx_rate_on_or_before(rows, mon, 2), None); + assert_eq!(fx_rate_on_or_before(rows, mon, 3), Some(&rows[0])); + + // Stale gap between two rows returns None, never looks ahead to next_mon + assert_eq!(fx_rate_on_or_before(rows, next_mon - 1, 3), None); + + // Pre-1970 negative dates and extreme i32 boundaries do not overflow + let pre = build_fx_1d(&[flat(i32::MIN, 1.05)], &[]); + assert_eq!(fx_rate_on_or_before(&pre.rows, i32::MIN, 0), Some(&pre.rows[0])); + assert_eq!(fx_rate_on_or_before(&pre.rows, i32::MAX, 10), None); + assert_eq!(fx_rate_on_or_before(&pre.rows, i32::MIN + 5, 5), Some(&pre.rows[0])); + assert_eq!(fx_rate_on_or_before(&pre.rows, i32::MIN + 6, 5), None); + } +} diff --git a/tools/curate-etl/src/lib.rs b/tools/curate-etl/src/lib.rs index bcc7d62e..6efd8878 100644 --- a/tools/curate-etl/src/lib.rs +++ b/tools/curate-etl/src/lib.rs @@ -5,6 +5,11 @@ pub mod bars; pub mod bench; pub mod cli; pub mod corporate_actions; +pub mod events; +pub mod fx; +pub mod parquet_bars; +pub mod provider_mapping; +pub mod shorts; pub mod split; pub use adj::{ @@ -20,6 +25,34 @@ pub use corporate_actions::{ CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent, KnownAtSource, SplitActionEvent, }; +pub use events::{ + build_events, classify_form_type, encode_earnings_payload_json, encode_filing_payload_json, + is_periodic_financial_report, normalize_announce_time, parse_filing_timefiled, + partition_year_utc, EventRow, EventsBuild, EventsStats, FilingFormGroup, FilingTimeError, + ParsedFilingTime, QmEarning, QmFiling, EARNINGS_FALLBACK_HOUR_ET, EARNINGS_FALLBACK_MINUTE_ET, + EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, + KNOWN_AT_SOURCE_STATUTORY_LAG, +}; +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 parquet_bars::{ + bars_1d_parquet_schema, write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions, + Bars1dWriteStats, ParquetBarsError, RollbackFailure, DEFAULT_ROW_GROUP_ROWS, + DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, +}; +pub use provider_mapping::{ + MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow, + ProviderMappingTable, +}; +pub use shorts::{ + add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, + is_canadian_business_day, CeoShortReport, ShortRow, ShortsBuild, ShortsError, ShortsStats, + MAX_SUPPORTED_DATE, MAX_SUPPORTED_YEAR, MIN_SUPPORTED_DATE, MIN_SUPPORTED_YEAR, + SHORTS_DISSEMINATION_HOUR_ET, SHORTS_DISSEMINATION_MINUTE_ET, SHORTS_LAG_BUSINESS_DAYS, + SHORTS_SOURCE_CEO, +}; pub use split::{ unadjust_ohlcv, unadjust_price, unadjust_volume, ymd_to_epoch_days, OhlcvBar, SplitEntry, SplitError, SplitEvent, SplitTable, diff --git a/tools/curate-etl/src/main.rs b/tools/curate-etl/src/main.rs index 804ffbdc..3441e023 100644 --- a/tools/curate-etl/src/main.rs +++ b/tools/curate-etl/src/main.rs @@ -4,7 +4,9 @@ use std::env; use std::process::ExitCode; use curate_etl::bench::{ - run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_split_benchmark, + run_adj_benchmark, run_bars_benchmark, run_corporate_actions_benchmark, run_events_benchmark, + run_fx_benchmark, run_parquet_bars_benchmark, run_provider_mapping_benchmark, + run_shorts_benchmark, run_split_benchmark, }; use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction}; @@ -160,6 +162,169 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Ok(CliAction::BenchFx(rows)) => { + let report = run_fx_benchmark(rows); + println!("curate-etl bench-fx"); + println!( + " input: rows={} eod_rows={} te_rows={}", + report.rows, report.eod_rows_in, report.te_rows_in + ); + println!( + " build: rows_out={} eod_out={} te_out={} elapsed={:.3} ms throughput={:.0} rows/s latency={:.2} ns/row", + report.rows_out, + report.stats.eod_rows_out, + report.stats.te_rows_out, + report.build_elapsed_ms, + report.build_rows_per_sec, + report.build_ns_per_row + ); + println!( + " lookup: lookups={} hits={} elapsed={:.2} ms throughput={:.0} lookups/s latency={:.2} ns/lookup checksum=0x{:016x}", + report.lookups, + report.lookup_hits, + report.lookup_elapsed_ms, + report.lookups_per_sec, + report.ns_per_lookup, + report.checksum + ); + println!( + " stats: eod_invalid={} eod_inconsistent={} eod_dup_collapsed={} eod_dup_conflict={} te_invalid={} te_inconsistent={} te_dup_collapsed={} te_dup_conflict={} te_superseded={} overlap_checked={} within_tol={} mismatched={} max_overlap_rel={:.6}", + report.stats.eod.dropped_invalid_ohlc, + report.stats.eod.dropped_inconsistent_ohlc, + report.stats.eod.duplicate_collapsed, + report.stats.eod.duplicate_conflict_dropped, + report.stats.te.dropped_invalid_ohlc, + report.stats.te.dropped_inconsistent_ohlc, + report.stats.te.duplicate_collapsed, + report.stats.te.duplicate_conflict_dropped, + report.stats.te_superseded_by_eod, + report.stats.overlap_checked, + report.stats.overlap_within_tolerance, + report.stats.overlap_mismatched, + report.stats.max_overlap_rel + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchShorts(rows)) => { + let report = match run_shorts_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: shorts benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-shorts"); + println!(" input: rows={} keys={}", report.rows, report.key_count); + println!( + " build: rows_out={} keys_out={} elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", + report.rows_out, + report.keys_out, + report.build_elapsed_ms, + report.rows_per_sec, + report.ns_per_row, + report.checksum + ); + println!( + " stats: invalid_shares={} nulled_net_change={} nulled_pct_float={} dup_collapsed={} dup_conflict={}", + report.stats.dropped_invalid_shares_short, + report.stats.nulled_invalid_net_change, + report.stats.nulled_invalid_pct_float, + report.stats.duplicate_collapsed, + report.stats.duplicate_conflict_dropped + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchEvents(rows)) => { + let report = run_events_benchmark(rows); + println!("curate-etl bench-events"); + println!( + " input: rows={} filings={} earnings={} keys={}", + report.rows, report.filings_in, report.earnings_in, report.key_count + ); + println!( + " build: rows_out={} filings_out={} earnings_out={} keys_out={} elapsed={:.2} ms throughput={:.0} rows/s latency={:.2} ns/row checksum=0x{:016x}", + report.rows_out, + report.stats.filings_out, + report.stats.earnings_out, + report.keys_out, + report.build_elapsed_ms, + report.rows_per_sec, + report.ns_per_row, + report.checksum + ); + println!( + " stats: malformed_ts={} unknown_zone={} invalid_dt={} filing_dup={} linked={} lagged_1605={} earnings_oor={} earnings_dup={} earnings_conflict={}", + report.stats.filings_skipped_malformed_timestamp, + report.stats.filings_skipped_unknown_zone, + report.stats.filings_skipped_invalid_date_time, + report.stats.filings_duplicate_collapsed, + report.stats.earnings_linked_to_filing, + report.stats.earnings_lagged_1605, + report.stats.earnings_skipped_out_of_range, + report.stats.earnings_duplicate_collapsed, + report.stats.earnings_duplicate_conflict_dropped + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchProviderMapping(lookups)) => { + let report = match run_provider_mapping_benchmark(lookups) { + Ok(report) => report, + Err(err) => { + eprintln!("error: provider_mapping benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-provider-mapping"); + println!( + " table: keys={} ranges={} multi_range_keys={} build={:.2} ms throughput={:.0} rows/s", + report.key_count, + report.range_count, + report.multi_range_keys, + report.build_elapsed_ms, + report.build_rows_per_sec + ); + println!( + " lookup: lookups={} hits={} misses={} elapsed={:.2} ms throughput={:.0} lookups/s latency={:.2} ns/lookup checksum=0x{:016x}", + report.lookups, + report.hits, + report.misses, + report.lookup_elapsed_ms, + report.lookups_per_sec, + report.ns_per_lookup, + report.checksum + ); + ExitCode::SUCCESS + } + Ok(CliAction::BenchParquetBars(rows)) => { + let report = match run_parquet_bars_benchmark(rows) { + Ok(report) => report, + Err(err) => { + eprintln!("error: parquet bars benchmark failed: {err}"); + return ExitCode::FAILURE; + } + }; + println!("curate-etl bench-parquet-bars"); + println!( + " input: rows={} listings={} raw_row_bytes={}", + report.rows, report.listing_count, report.raw_row_bytes + ); + println!( + " output: files={} row_groups={} bytes={} read_back_rows={}", + report.files_written, + report.row_groups_written, + report.bytes_written, + report.read_back_rows + ); + println!( + " perf: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s size={:.2} bytes/row compression={:.2}x", + report.elapsed_ms, + report.rows_per_sec, + report.mb_per_sec, + report.bytes_per_row, + report.compression_ratio + ); + ExitCode::SUCCESS + } Err(msg) => { eprintln!("error: {msg}"); eprintln!("{}", format_usage_stderr(NAME)); diff --git a/tools/curate-etl/src/parquet_bars.rs b/tools/curate-etl/src/parquet_bars.rs new file mode 100644 index 00000000..16c8833e --- /dev/null +++ b/tools/curate-etl/src/parquet_bars.rs @@ -0,0 +1,2386 @@ +//! Streaming, atomic, year-partitioned Zstd Parquet writer for `bars_1d`. +//! +//! Writes `bars_1d/year=YYYY/part.parquet` files matching the 12-column contract schema in +//! `design/DATA-CONTRACTS.md` (§3A): +//! +//! 1. `listing_id` (`INT32`, `REQUIRED`) +//! 2. `ts` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) +//! 3. `session_date` (`INT32`, `REQUIRED`, `DATE`) +//! 4. `open` (`DOUBLE`, `REQUIRED`) +//! 5. `high` (`DOUBLE`, `REQUIRED`) +//! 6. `low` (`DOUBLE`, `REQUIRED`) +//! 7. `close` (`DOUBLE`, `REQUIRED`) +//! 8. `volume` (`DOUBLE`, `REQUIRED`) +//! 9. `vwap` (`DOUBLE`, `OPTIONAL`) +//! 10. `currency` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 11. `source` (`BYTE_ARRAY`, `REQUIRED`, `STRING`) +//! 12. `known_at` (`INT64`, `REQUIRED`, `TIMESTAMP(MICROS, isAdjustedToUTC=true)`) + +use std::borrow::{Borrow, Cow}; +use std::cmp::Ordering; +use std::collections::{BTreeMap, HashMap}; +use std::error::Error; +use std::fmt; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::thread; +use std::time::{Duration, Instant}; + +use parquet::basic::{Compression, LogicalType, Repetition, TimeUnit, Type as PhysicalType, ZstdLevel}; +use parquet::column::writer::ColumnWriter; +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::shorts::epoch_days_to_ymd; + +/// Default maximum number of rows buffered per Parquet row group. +pub const DEFAULT_ROW_GROUP_ROWS: usize = 1_000_000; + +/// Default Zstd compression level for `bars_1d` Parquet files. +pub const DEFAULT_ZSTD_LEVEL: i32 = 3; + +/// Minimum allowed calendar year for `session_date` partitioning. +pub const MIN_PARQUET_YEAR: i32 = 1900; + +/// Maximum allowed calendar year for `session_date` partitioning. +pub const MAX_PARQUET_YEAR: i32 = 2200; + +const STRING_WRITE_BATCH_ROWS: usize = 4_096; +const FILE_BUF_CAPACITY_BYTES: usize = 64 * 1024; +const LINEAR_INTERN_LIMIT: usize = 8; +const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30); + +/// Single `bars_1d` row matching the `design/DATA-CONTRACTS.md` Parquet schema. +#[derive(Debug, Clone, PartialEq)] +pub struct Bars1dParquetRow { + pub listing_id: i32, + pub ts_micros: i64, + pub session_date: i32, + pub open: f64, + pub high: f64, + pub low: f64, + pub close: f64, + pub volume: f64, + pub vwap: Option, + pub currency: Cow<'static, str>, + pub source: Cow<'static, str>, + pub known_at_micros: i64, +} + +/// Configuration for [`write_bars_1d_dataset`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Bars1dWriteOptions { + pub row_group_rows: usize, + pub zstd_level: i32, +} + +impl Default for Bars1dWriteOptions { + fn default() -> Self { + Self { + row_group_rows: DEFAULT_ROW_GROUP_ROWS, + zstd_level: DEFAULT_ZSTD_LEVEL, + } + } +} + +/// Accounting summary returned by [`write_bars_1d_dataset`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Bars1dWriteStats { + pub rows_written: usize, + pub files_written: usize, + pub row_groups_written: usize, + pub bytes_written: u64, + pub rows_by_year: BTreeMap, +} + +/// Single failure encountered while rolling back a partial publication. +#[derive(Debug)] +pub struct RollbackFailure { + pub final_path: PathBuf, + pub backup_path: Option, + pub source: io::Error, +} + +impl fmt::Display for RollbackFailure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.backup_path { + Some(bak) => write!( + f, + "partition '{}' (backup '{}'): {}", + self.final_path.display(), + bak.display(), + self.source + ), + None => write!( + f, + "partition '{}': {}", + self.final_path.display(), + self.source + ), + } + } +} + +/// Typed error returned by [`write_bars_1d_dataset`]. +#[derive(Debug)] +pub enum ParquetBarsError { + InvalidRowGroupRows, + InvalidZstdLevel { + level: i32, + }, + UnsortedInput { + prev_listing_id: i32, + prev_session_date: i32, + listing_id: i32, + session_date: i32, + }, + DuplicateKey { + listing_id: i32, + session_date: i32, + }, + SessionYearOutOfRange { + listing_id: i32, + session_date: i32, + year: i32, + min_year: i32, + max_year: i32, + }, + 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 ParquetBarsError { + 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::UnsortedInput { + prev_listing_id, + prev_session_date, + listing_id, + session_date, + } => write!( + f, + "unsorted input: ({listing_id}, {session_date}) follows ({prev_listing_id}, {prev_session_date})" + ), + Self::DuplicateKey { + listing_id, + session_date, + } => write!( + f, + "duplicate (listing_id, session_date) key: ({listing_id}, {session_date})" + ), + Self::SessionYearOutOfRange { + listing_id, + session_date, + year, + min_year, + max_year, + } => write!( + f, + "session_date {session_date} (year {year}) for listing_id {listing_id} is outside allowed range {min_year}..={max_year}" + ), + 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 ParquetBarsError { + 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, + } + } +} + +/// Builds the exact 12-column Parquet schema for `bars_1d` per `design/DATA-CONTRACTS.md`. +pub fn bars_1d_parquet_schema() -> Result { + let fields: Vec = vec![ + Arc::new( + Type::primitive_type_builder("listing_id", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("ts", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("session_date", PhysicalType::INT32) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::Date)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("open", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("high", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("low", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("close", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("volume", PhysicalType::DOUBLE) + .with_repetition(Repetition::REQUIRED) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("vwap", PhysicalType::DOUBLE) + .with_repetition(Repetition::OPTIONAL) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("currency", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("source", PhysicalType::BYTE_ARRAY) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::String)) + .build()?, + ), + Arc::new( + Type::primitive_type_builder("known_at", PhysicalType::INT64) + .with_repetition(Repetition::REQUIRED) + .with_logical_type(Some(LogicalType::timestamp(true, TimeUnit::MICROS))) + .build()?, + ), + ]; + + Ok(Arc::new( + Type::group_type_builder("bars_1d") + .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("currency"), true) + .set_column_dictionary_enabled(ColumnPath::from("source"), true) + .set_created_by(format!("curate-etl {}", env!("CARGO_PKG_VERSION"))) + .build(), + ) +} + +#[derive(Default)] +struct StringInterner { + values: Vec, + index: HashMap, +} + +impl StringInterner { + fn intern(&mut self, s: &str) -> u32 { + if self.values.len() <= LINEAR_INTERN_LIMIT { + let bytes = s.as_bytes(); + for (idx, existing) in self.values.iter().enumerate() { + if existing.data() == bytes { + return idx as u32; + } + } + let id = self.values.len() as u32; + self.values.push(ByteArray::from(s)); + if self.values.len() > LINEAR_INTERN_LIMIT { + self.index.reserve(self.values.len()); + for (i, val) in self.values.iter().enumerate() { + if let Ok(text) = std::str::from_utf8(val.data()) { + self.index.insert(text.to_owned(), i as u32); + } + } + } + return id; + } + + if let Some(&id) = self.index.get(s) { + return id; + } + let id = self.values.len() as u32; + self.values.push(ByteArray::from(s)); + self.index.insert(s.to_owned(), id); + id + } + + #[inline] + fn get(&self, id: u32) -> &ByteArray { + &self.values[id as usize] + } + + fn clear(&mut self) { + self.values.clear(); + self.index.clear(); + } +} + +#[derive(Default)] +struct RowGroupBuffer { + listing_id: Vec, + ts_micros: Vec, + session_date: Vec, + open: Vec, + high: Vec, + low: Vec, + close: Vec, + volume: Vec, + vwap_values: Vec, + vwap_def_levels: Vec, + currency_ids: Vec, + currency_interner: StringInterner, + source_ids: Vec, + source_interner: StringInterner, + known_at_micros: Vec, +} + +impl RowGroupBuffer { + #[inline] + fn len(&self) -> usize { + self.listing_id.len() + } + + fn push(&mut self, row: &Bars1dParquetRow) { + self.listing_id.push(row.listing_id); + self.ts_micros.push(row.ts_micros); + self.session_date.push(row.session_date); + self.open.push(row.open); + self.high.push(row.high); + self.low.push(row.low); + self.close.push(row.close); + self.volume.push(row.volume); + match row.vwap { + Some(v) => { + self.vwap_values.push(v); + self.vwap_def_levels.push(1); + } + None => { + self.vwap_def_levels.push(0); + } + } + let currency_id = self.currency_interner.intern(row.currency.as_ref()); + self.currency_ids.push(currency_id); + let source_id = self.source_interner.intern(row.source.as_ref()); + self.source_ids.push(source_id); + self.known_at_micros.push(row.known_at_micros); + } + + fn clear(&mut self) { + self.listing_id.clear(); + self.ts_micros.clear(); + self.session_date.clear(); + self.open.clear(); + self.high.clear(); + self.low.clear(); + self.close.clear(); + self.volume.clear(); + self.vwap_values.clear(); + self.vwap_def_levels.clear(); + self.currency_ids.clear(); + self.currency_interner.clear(); + self.source_ids.clear(); + self.source_interner.clear(); + self.known_at_micros.clear(); + } +} + +static DATASET_LOCKS: OnceLock>>>> = OnceLock::new(); +static WRITE_RUN_SEQ: AtomicU64 = AtomicU64::new(0); + +fn dataset_mutex(bars_dir: &Path) -> Arc> { + let key = fs::canonicalize(bars_dir).unwrap_or_else(|_| bars_dir.to_path_buf()); + let map_mutex = DATASET_LOCKS.get_or_init(|| Mutex::new(HashMap::new())); + let mut map = map_mutex.lock().unwrap_or_else(|err| err.into_inner()); + map.entry(key) + .or_insert_with(|| Arc::new(Mutex::new(()))) + .clone() +} + +struct DatasetFileLock { + path: PathBuf, +} + +impl DatasetFileLock { + fn acquire_with_timeout(bars_dir: &Path, timeout: Duration) -> Result { + let lock_path = bars_dir.join(".write.lock"); + let start = Instant::now(); + let mut backoff_ms = 2u64; + loop { + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&lock_path) + { + Ok(mut file) => { + let _ = writeln!(file, "{}", std::process::id()); + let _ = file.sync_all(); + return Ok(Self { path: lock_path }); + } + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => { + let elapsed = start.elapsed(); + if elapsed >= timeout { + return Err(ParquetBarsError::LockTimeout { + path: lock_path, + waited: elapsed, + }); + } + let remaining = timeout.saturating_sub(elapsed); + thread::sleep(Duration::from_millis(backoff_ms).min(remaining)); + backoff_ms = (backoff_ms * 2).min(25); + } + Err(source) => { + return Err(ParquetBarsError::Io { + path: lock_path, + source, + }); + } + } + } + } +} + +impl Drop for DatasetFileLock { + fn drop(&mut self) { + let _ = fs::remove_file(&self.path); + } +} + +fn next_run_id() -> String { + let seq = WRITE_RUN_SEQ.fetch_add(1, AtomicOrdering::Relaxed); + format!("{}-{seq}", std::process::id()) +} + +fn create_exclusive_tmp_file( + year_dir: &Path, + run_id: &str, +) -> Result<(PathBuf, File), ParquetBarsError> { + for attempt in 0..1024u32 { + let file_name = if attempt == 0 { + format!("part.parquet.{run_id}.tmp") + } else { + format!("part.parquet.{run_id}.{attempt}.tmp") + }; + let tmp_path = year_dir.join(file_name); + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path) + { + Ok(file) => return Ok((tmp_path, file)), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(source) => { + return Err(ParquetBarsError::Io { + path: tmp_path, + source, + }); + } + } + } + Err(ParquetBarsError::Io { + path: year_dir.join(format!("part.parquet.{run_id}.tmp")), + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique staging file names", + ), + }) +} + +fn is_hard_link_unsupported(err: &io::Error) -> bool { + matches!( + err.kind(), + io::ErrorKind::Unsupported | io::ErrorKind::PermissionDenied + ) +} + +fn copy_to_exclusive_backup(src: &Path, dst: &Path) -> io::Result<()> { + let mut dst_file = OpenOptions::new().write(true).create_new(true).open(dst)?; + let copy_res = (|| -> io::Result<()> { + let mut src_file = File::open(src)?; + io::copy(&mut src_file, &mut dst_file)?; + dst_file.sync_all()?; + Ok(()) + })(); + if let Err(err) = copy_res { + drop(dst_file); + let _ = fs::remove_file(dst); + return Err(err); + } + Ok(()) +} + +/// Creates a per-run rollback backup of `final_path` while keeping `final_path` intact on disk. +/// Uses an atomic hard link in the same directory when supported, falling back to an exclusive +/// file copy so readers never observe a missing `part.parquet` before replacement. +fn create_backup_preserving_live( + final_path: &Path, + run_id: &str, +) -> Result { + let parent = final_path.parent().unwrap_or_else(|| Path::new(".")); + for attempt in 0..1024u32 { + let file_name = if attempt == 0 { + format!("part.parquet.{run_id}.bak") + } else { + format!("part.parquet.{run_id}.{attempt}.bak") + }; + let bak_path = parent.join(file_name); + match fs::hard_link(final_path, &bak_path) { + Ok(()) => return Ok(bak_path), + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(err) if is_hard_link_unsupported(&err) => { + match copy_to_exclusive_backup(final_path, &bak_path) { + Ok(()) => return Ok(bak_path), + Err(copy_err) if copy_err.kind() == io::ErrorKind::AlreadyExists => continue, + Err(source) => { + return Err(ParquetBarsError::Io { + path: bak_path, + source, + }); + } + } + } + Err(source) => { + return Err(ParquetBarsError::Io { + path: bak_path, + source, + }); + } + } + } + Err(ParquetBarsError::Io { + path: parent.join(format!("part.parquet.{run_id}.bak")), + source: io::Error::new( + io::ErrorKind::AlreadyExists, + "exhausted unique backup file names", + ), + }) +} + +struct YearWriter { + tmp_path: PathBuf, + final_path: PathBuf, + writer: SerializedFileWriter>, + buf: RowGroupBuffer, + rows_written: usize, + row_groups_written: usize, +} + +impl YearWriter { + fn open( + bars_dir: &Path, + year: i32, + run_id: &str, + schema: &TypePtr, + props: &WriterPropertiesPtr, + owned_tmp_paths: &mut Vec, + ) -> Result { + let year_dir = bars_dir.join(format!("year={year:04}")); + fs::create_dir_all(&year_dir).map_err(|source| ParquetBarsError::Io { + path: year_dir.clone(), + source, + })?; + + let (tmp_path, file) = create_exclusive_tmp_file(&year_dir, run_id)?; + owned_tmp_paths.push(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| ParquetBarsError::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<(), ParquetBarsError> { + let row_count = self.buf.len(); + if row_count == 0 { + return Ok(()); + } + + let map_pq = |source: ParquetError| ParquetBarsError::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, &self.tmp_path)?; + // 2. ts (INT64, REQUIRED) + write_i64_col(&mut rg_writer, &self.buf.ts_micros, &self.tmp_path)?; + // 3. session_date (INT32, REQUIRED) + write_i32_col(&mut rg_writer, &self.buf.session_date, &self.tmp_path)?; + // 4. open (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.open, None, &self.tmp_path)?; + // 5. high (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.high, None, &self.tmp_path)?; + // 6. low (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.low, None, &self.tmp_path)?; + // 7. close (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.close, None, &self.tmp_path)?; + // 8. volume (DOUBLE, REQUIRED) + write_f64_col(&mut rg_writer, &self.buf.volume, None, &self.tmp_path)?; + // 9. vwap (DOUBLE, OPTIONAL) + write_f64_col( + &mut rg_writer, + &self.buf.vwap_values, + Some(&self.buf.vwap_def_levels), + &self.tmp_path, + )?; + // 10. currency (BYTE_ARRAY, REQUIRED) + write_interned_str_col( + &mut rg_writer, + &self.buf.currency_ids, + &self.buf.currency_interner, + scratch, + &self.tmp_path, + )?; + // 11. source (BYTE_ARRAY, REQUIRED) + write_interned_str_col( + &mut rg_writer, + &self.buf.source_ids, + &self.buf.source_interner, + scratch, + &self.tmp_path, + )?; + // 12. known_at (INT64, REQUIRED) + write_i64_col(&mut rg_writer, &self.buf.known_at_micros, &self.tmp_path)?; + + 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| ParquetBarsError::Parquet { + path: self.tmp_path.clone(), + source, + })?; + buf_writer.flush().map_err(|source| ParquetBarsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let file = buf_writer + .into_inner() + .map_err(|err| ParquetBarsError::Io { + path: self.tmp_path.clone(), + source: err.into_error(), + })?; + file.sync_all().map_err(|source| ParquetBarsError::Io { + path: self.tmp_path.clone(), + source, + })?; + let bytes = file + .metadata() + .map_err(|source| ParquetBarsError::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 next_column<'a>( + rg_writer: &'a mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, + path: &Path, +) -> Result, ParquetBarsError> { + match rg_writer.next_column() { + Ok(Some(col)) => Ok(col), + Ok(None) => Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source: ParquetError::General("unexpected end of Parquet schema columns".to_string()), + }), + Err(source) => Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + }), + } +} + +fn write_i32_col( + rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, + values: &[i32], + path: &Path, +) -> Result<(), ParquetBarsError> { + let mut col = next_column(rg_writer, path)?; + match col.untyped() { + ColumnWriter::Int32ColumnWriter(typed) => { + typed + .write_batch(values, None, None) + .map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + })?; + } + _ => { + return Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source: ParquetError::General("expected INT32 column writer".to_string()), + }); + } + } + col.close().map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + }) +} + +fn write_i64_col( + rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, + values: &[i64], + path: &Path, +) -> Result<(), ParquetBarsError> { + let mut col = next_column(rg_writer, path)?; + match col.untyped() { + ColumnWriter::Int64ColumnWriter(typed) => { + typed + .write_batch(values, None, None) + .map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + })?; + } + _ => { + return Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source: ParquetError::General("expected INT64 column writer".to_string()), + }); + } + } + col.close().map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + }) +} + +fn write_f64_col( + rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, + values: &[f64], + def_levels: Option<&[i16]>, + path: &Path, +) -> Result<(), ParquetBarsError> { + let mut col = next_column(rg_writer, path)?; + match col.untyped() { + ColumnWriter::DoubleColumnWriter(typed) => { + typed + .write_batch(values, def_levels, None) + .map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + })?; + } + _ => { + return Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source: ParquetError::General("expected DOUBLE column writer".to_string()), + }); + } + } + col.close().map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + }) +} + +fn write_interned_str_col( + rg_writer: &mut parquet::file::writer::SerializedRowGroupWriter<'_, BufWriter>, + ids: &[u32], + interner: &StringInterner, + scratch: &mut Vec, + path: &Path, +) -> Result<(), ParquetBarsError> { + let mut col = next_column(rg_writer, path)?; + match col.untyped() { + ColumnWriter::ByteArrayColumnWriter(typed) => { + for chunk in ids.chunks(STRING_WRITE_BATCH_ROWS) { + scratch.clear(); + for &id in chunk { + scratch.push(interner.get(id).clone()); + } + typed + .write_batch(scratch, None, None) + .map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + })?; + } + } + _ => { + return Err(ParquetBarsError::Parquet { + path: path.to_path_buf(), + source: ParquetError::General("expected BYTE_ARRAY column writer".to_string()), + }); + } + } + col.close().map_err(|source| ParquetBarsError::Parquet { + path: path.to_path_buf(), + source, + }) +} + +fn cleanup_owned_files(owned_paths: &[PathBuf]) { + for path in owned_paths { + let _ = fs::remove_file(path); + } +} + +struct PublishedPartition { + final_path: PathBuf, + backup_path: Option, +} + +fn rollback_published(published: &[PublishedPartition]) -> Vec { + let mut failures = Vec::new(); + for part in published.iter().rev() { + match &part.backup_path { + Some(bak) => { + if let Err(source) = fs::rename(bak, &part.final_path) { + failures.push(RollbackFailure { + final_path: part.final_path.clone(), + backup_path: Some(bak.clone()), + source, + }); + } + } + None => { + if let Err(source) = fs::remove_file(&part.final_path) { + failures.push(RollbackFailure { + final_path: part.final_path.clone(), + backup_path: None, + source, + }); + } + } + } + } + failures +} + +fn finish_with_rollback( + cause: ParquetBarsError, + published: &[PublishedPartition], + extra_failure: Option, + owned_tmp_paths: &[PathBuf], +) -> ParquetBarsError { + let mut failures = Vec::new(); + if let Some(failure) = extra_failure { + failures.push(failure); + } + failures.extend(rollback_published(published)); + cleanup_owned_files(owned_tmp_paths); + if failures.is_empty() { + cause + } else { + ParquetBarsError::RollbackFailed { + cause: Box::new(cause), + failures, + } + } +} + +/// Streams strictly ascending `(listing_id, session_date)` rows into year-partitioned Zstd +/// Parquet files at `/bars_1d/year=YYYY/part.parquet`. +/// +/// # Concurrency & Atomicity +/// Concurrent writers targeting the same `/bars_1d` 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. During publication, pre-existing `part.parquet` +/// files are backed up in place (via hard link, or exclusive copy fallback) so the live path +/// remains readable until replaced by a single atomic `rename`; on any error, all open writers +/// are dropped, replaced partitions are restored from backup, newly published partitions are +/// removed (with any rollback failures reported alongside the original error), and only staging +/// files owned by the current run are unlinked. +pub fn write_bars_1d_dataset( + out_dir: P, + rows: I, + options: Bars1dWriteOptions, +) -> Result +where + P: AsRef, + I: IntoIterator, + R: Borrow, +{ + write_bars_1d_dataset_with_hooks( + out_dir, + rows, + options, + DEFAULT_LOCK_TIMEOUT, + |_, _, _| {}, + ) +} + +fn write_bars_1d_dataset_with_hooks( + out_dir: P, + rows: I, + options: Bars1dWriteOptions, + 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(ParquetBarsError::InvalidRowGroupRows); + } + let zstd_level = ZstdLevel::try_new(options.zstd_level).map_err(|_| { + ParquetBarsError::InvalidZstdLevel { + level: options.zstd_level, + } + })?; + + let mut row_iter = rows.into_iter(); + let Some(first_item) = row_iter.next() else { + return Ok(Bars1dWriteStats::default()); + }; + { + let first_row = first_item.borrow(); + let (first_year, _, _) = epoch_days_to_ymd(first_row.session_date); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&first_year) { + return Err(ParquetBarsError::SessionYearOutOfRange { + listing_id: first_row.listing_id, + session_date: first_row.session_date, + year: first_year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + } + + let out_dir = out_dir.as_ref(); + let bars_dir = out_dir.join("bars_1d"); + let schema = bars_1d_parquet_schema().map_err(|source| ParquetBarsError::Parquet { + path: bars_dir.clone(), + source, + })?; + let props = build_writer_properties(zstd_level); + + fs::create_dir_all(&bars_dir).map_err(|source| ParquetBarsError::Io { + path: bars_dir.clone(), + source, + })?; + + // Serialize writers targeting the same dataset directory across threads and processes. + // Drop order guarantees `.write.lock` is removed while `_in_process_guard` is still held, + // and only after all staging/publication/rollback work has finished. + let dataset_mu = dataset_mutex(&bars_dir); + let _in_process_guard = dataset_mu.lock().unwrap_or_else(|err| err.into_inner()); + let _file_lock = DatasetFileLock::acquire_with_timeout(&bars_dir, lock_timeout)?; + + let run_id = next_run_id(); + let mut writers: BTreeMap = BTreeMap::new(); + let mut owned_tmp_paths: Vec = Vec::new(); + let mut scratch: Vec = Vec::with_capacity(STRING_WRITE_BATCH_ROWS); + + let write_result: Result, ParquetBarsError> = (|| { + let mut prev_key: Option<(i32, i32)> = None; + + for item in std::iter::once(first_item).chain(row_iter) { + let row = item.borrow(); + if let Some((prev_listing_id, prev_session_date)) = prev_key { + match (row.listing_id, row.session_date).cmp(&(prev_listing_id, prev_session_date)) + { + Ordering::Equal => { + return Err(ParquetBarsError::DuplicateKey { + listing_id: row.listing_id, + session_date: row.session_date, + }); + } + Ordering::Less => { + return Err(ParquetBarsError::UnsortedInput { + prev_listing_id, + prev_session_date, + listing_id: row.listing_id, + session_date: row.session_date, + }); + } + Ordering::Greater => {} + } + } + prev_key = Some((row.listing_id, row.session_date)); + + let (year, _, _) = epoch_days_to_ymd(row.session_date); + if !(MIN_PARQUET_YEAR..=MAX_PARQUET_YEAR).contains(&year) { + return Err(ParquetBarsError::SessionYearOutOfRange { + listing_id: row.listing_id, + session_date: row.session_date, + year, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + }); + } + + 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( + &bars_dir, + year, + &run_id, + &schema, + &props, + &mut owned_tmp_paths, + )?; + entry.insert(opened) + } + }; + + yw.buf.push(row); + if yw.buf.len() == options.row_group_rows { + yw.flush_row_group(&mut scratch)?; + } + } + + 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)); + } + Ok(synced) + })(); + + let synced_files = match write_result { + Ok(files) => files, + Err(err) => { + // Drop all open writers before unlinking temporary files owned by this run. + drop(writers); + cleanup_owned_files(&owned_tmp_paths); + return Err(err); + } + }; + + let mut stats = Bars1dWriteStats::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, &published, None, &owned_tmp_paths)); + } + } + } + // 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 = ParquetBarsError::Io { + path: file.final_path, + source, + }; + return Err(finish_with_rollback(err, &published, None, &owned_tmp_paths)); + } + }; + + on_after_backup(year, &file.final_path, backup_path.as_deref()); + + if let Err(source) = fs::rename(&file.tmp_path, &file.final_path) { + // `file.final_path` was never moved during backup creation, so it remains intact; + // only remove the backup created for this partition before rolling back earlier ones. + 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 = ParquetBarsError::Io { + path: file.final_path, + source, + }; + return Err(finish_with_rollback( + err, + &published, + extra_failure, + &owned_tmp_paths, + )); + } + + 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)] +mod tests { + use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering}; + + use parquet::basic::ConvertedType; + use parquet::column::reader::ColumnReader; + use parquet::file::reader::{FileReader, SerializedFileReader}; + + use super::*; + use crate::split::ymd_to_epoch_days; + + static TEMP_DIR_SEQ: AtomicU64 = AtomicU64::new(0); + + pub(super) struct TempDirGuard { + path: PathBuf, + } + + impl TempDirGuard { + pub(super) 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-test-{label}-{pid}-{seq}")); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create test temp dir"); + Self { path } + } + + pub(super) fn path(&self) -> &Path { + &self.path + } + } + + impl Drop for TempDirGuard { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + #[allow(clippy::too_many_arguments)] + pub(super) fn make_row( + listing_id: i32, + year: i32, + month: u32, + day: u32, + close: f64, + volume: f64, + vwap: Option, + currency: &'static str, + source: &'static str, + ) -> Bars1dParquetRow { + let session_date = ymd_to_epoch_days(year, month, day).expect("valid date"); + let ts_micros = i64::from(session_date) * 86_400_000_000 + 21 * 3_600_000_000; + let known_at_micros = ts_micros + 900_000_000; + Bars1dParquetRow { + listing_id, + ts_micros, + session_date, + open: close - 0.5, + high: close + 1.25, + low: close - 1.0, + close, + volume, + vwap, + currency: Cow::Borrowed(currency), + source: Cow::Borrowed(source), + known_at_micros, + } + } + + pub(super) 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 metadata = reader.metadata(); + let mut out = Vec::new(); + + for rg_idx in 0..metadata.num_row_groups() { + let rg_reader = reader.get_row_group(rg_idx).expect("row group reader"); + let num_rows = metadata.row_group(rg_idx).num_rows() as usize; + + let listing_id = read_i32_col(rg_reader.get_column_reader(0).unwrap(), num_rows); + let ts_micros = read_i64_col(rg_reader.get_column_reader(1).unwrap(), num_rows); + let session_date = read_i32_col(rg_reader.get_column_reader(2).unwrap(), num_rows); + let open = read_req_f64_col(rg_reader.get_column_reader(3).unwrap(), num_rows); + let high = read_req_f64_col(rg_reader.get_column_reader(4).unwrap(), num_rows); + let low = read_req_f64_col(rg_reader.get_column_reader(5).unwrap(), num_rows); + let close = read_req_f64_col(rg_reader.get_column_reader(6).unwrap(), num_rows); + let volume = read_req_f64_col(rg_reader.get_column_reader(7).unwrap(), num_rows); + let vwap = read_opt_f64_col(rg_reader.get_column_reader(8).unwrap(), num_rows); + let currency = read_str_col(rg_reader.get_column_reader(9).unwrap(), num_rows); + let source = read_str_col(rg_reader.get_column_reader(10).unwrap(), num_rows); + let known_at_micros = read_i64_col(rg_reader.get_column_reader(11).unwrap(), num_rows); + + for i in 0..num_rows { + out.push(Bars1dParquetRow { + listing_id: listing_id[i], + ts_micros: ts_micros[i], + session_date: session_date[i], + open: open[i], + high: high[i], + low: low[i], + close: close[i], + volume: volume[i], + vwap: vwap[i], + currency: Cow::Owned(currency[i].clone()), + source: Cow::Owned(source[i].clone()), + known_at_micros: known_at_micros[i], + }); + } + } + out + } + + fn read_i32_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int32ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int32ColumnReader"), + } + values + } + + fn read_i64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::Int64ColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected Int64ColumnReader"), + } + values + } + + fn read_req_f64_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + values + } + + fn read_opt_f64_col(reader: ColumnReader, expected: usize) -> Vec> { + let mut raw_values = Vec::with_capacity(expected); + let mut def_levels = Vec::with_capacity(expected); + match reader { + ColumnReader::DoubleColumnReader(mut r) => { + let (records, _, levels) = r + .read_records(expected, Some(&mut def_levels), None, &mut raw_values) + .unwrap(); + assert_eq!(records, expected); + assert_eq!(levels, expected); + } + _ => panic!("expected DoubleColumnReader"), + } + let mut out = Vec::with_capacity(expected); + let mut val_idx = 0usize; + for lvl in def_levels { + if lvl == 1 { + out.push(Some(raw_values[val_idx])); + val_idx += 1; + } else { + out.push(None); + } + } + assert_eq!(val_idx, raw_values.len()); + out + } + + fn read_str_col(reader: ColumnReader, expected: usize) -> Vec { + let mut values = Vec::with_capacity(expected); + match reader { + ColumnReader::ByteArrayColumnReader(mut r) => { + let (records, _, _) = r.read_records(expected, None, None, &mut values).unwrap(); + assert_eq!(records, expected); + } + _ => panic!("expected ByteArrayColumnReader"), + } + values + .into_iter() + .map(|ba| String::from_utf8(ba.data().to_vec()).expect("valid utf8")) + .collect() + } + + pub(super) fn assert_row_bitwise_eq(actual: &Bars1dParquetRow, expected: &Bars1dParquetRow) { + assert_eq!(actual.listing_id, expected.listing_id); + assert_eq!(actual.ts_micros, expected.ts_micros); + assert_eq!(actual.session_date, expected.session_date); + 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()); + assert_eq!( + actual.vwap.map(f64::to_bits), + expected.vwap.map(f64::to_bits) + ); + assert_eq!(actual.currency, expected.currency); + assert_eq!(actual.source, expected.source); + assert_eq!(actual.known_at_micros, expected.known_at_micros); + } + + #[test] + fn round_trip_three_years_preserves_bitwise_values_and_order() { + let tmp = TempDirGuard::new("round-trip"); + let rows = vec![ + make_row(1, 2022, 6, 15, 100.25, 0.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 3, 10, 112.50, 1_234_567.0, Some(112.42), "USD", "eod_unadj"), + make_row(1, 2024, 11, 1, 145.75, 987_654.0, Some(145.10), "USD", "qm_raw"), + make_row(2, 2022, 12, 30, 12.10, 50_000.0, Some(12.05), "CAD", "eod_unadj"), + make_row(2, 2024, 1, 2, 15.80, 0.0, None, "CAD", "eod_unadj"), + make_row(7, 2023, 7, 4, 42.00, 10_500.0, None, "USD", "ib_live"), + ]; + + let stats = + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, rows.len()); + assert_eq!(stats.files_written, 3); + assert_eq!(stats.row_groups_written, 3); + assert!(stats.bytes_written > 0); + assert_eq!(stats.rows_by_year.get(&2022), Some(&2)); + assert_eq!(stats.rows_by_year.get(&2023), Some(&2)); + assert_eq!(stats.rows_by_year.get(&2024), Some(&2)); + + for year in [2022, 2023, 2024] { + let path = tmp + .path() + .join(format!("bars_1d/year={year:04}/part.parquet")); + assert!(path.exists(), "expected {}", path.display()); + assert!( + !tmp.path() + .join(format!("bars_1d/year={year:04}/part.parquet.tmp")) + .exists() + ); + + let expected_year_rows: Vec<&Bars1dParquetRow> = rows + .iter() + .filter(|r| epoch_days_to_ymd(r.session_date).0 == year) + .collect(); + let actual_year_rows = read_parquet_rows(&path); + assert_eq!(actual_year_rows.len(), expected_year_rows.len()); + for (actual, expected) in actual_year_rows.iter().zip(expected_year_rows.iter()) { + assert_row_bitwise_eq(actual, expected); + assert!(actual.volume.is_sign_positive()); + assert!(actual.currency.is_ascii()); + assert!(actual.source.is_ascii()); + } + } + } + + #[test] + fn metadata_matches_contract_schema_and_zstd_compression() { + let tmp = TempDirGuard::new("schema"); + let rows = vec![ + make_row(10, 2024, 5, 20, 55.0, 250_000.0, Some(54.8), "USD", "eod_unadj"), + make_row(10, 2024, 5, 21, 56.0, 300_000.0, None, "CAD", "eod_unadj"), + ]; + + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + + let path = tmp.path().join("bars_1d/year=2024/part.parquet"); + let file = File::open(&path).unwrap(); + let reader = SerializedFileReader::new(file).unwrap(); + let file_meta = reader.metadata().file_metadata(); + let schema = file_meta.schema_descr(); + + assert_eq!(schema.name(), "bars_1d"); + assert_eq!(schema.num_columns(), 12); + + let expected: [(&str, PhysicalType, Repetition, Option, ConvertedType); 12] = [ + ( + "listing_id", + PhysicalType::INT32, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "ts", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ( + "session_date", + PhysicalType::INT32, + Repetition::REQUIRED, + Some(LogicalType::Date), + ConvertedType::DATE, + ), + ( + "open", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "high", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "low", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "close", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "volume", + PhysicalType::DOUBLE, + Repetition::REQUIRED, + None, + ConvertedType::NONE, + ), + ( + "vwap", + PhysicalType::DOUBLE, + Repetition::OPTIONAL, + None, + ConvertedType::NONE, + ), + ( + "currency", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "source", + PhysicalType::BYTE_ARRAY, + Repetition::REQUIRED, + Some(LogicalType::String), + ConvertedType::UTF8, + ), + ( + "known_at", + PhysicalType::INT64, + Repetition::REQUIRED, + Some(LogicalType::timestamp(true, TimeUnit::MICROS)), + ConvertedType::TIMESTAMP_MICROS, + ), + ]; + + for (idx, (name, phys, rep, logical, converted)) in expected.iter().enumerate() { + let col = schema.column(idx); + let field = col.self_type(); + assert_eq!(col.name(), *name, "column {idx} name mismatch"); + assert_eq!(col.physical_type(), *phys, "column {name} physical type"); + assert_eq!( + field.get_basic_info().repetition(), + *rep, + "column {name} repetition" + ); + assert_eq!( + field.get_basic_info().logical_type_ref(), + logical.as_ref(), + "column {name} logical type" + ); + assert_eq!( + field.get_basic_info().converted_type(), + *converted, + "column {name} converted type" + ); + } + + assert_eq!(reader.metadata().num_row_groups(), 1); + let rg = reader.metadata().row_group(0); + for col_idx in 0..12 { + let chunk = rg.column(col_idx); + assert!( + matches!(chunk.compression(), Compression::ZSTD(_)), + "column {col_idx} must use ZSTD compression, got {:?}", + chunk.compression() + ); + } + } + + #[test] + fn partitioning_splits_dec31_and_jan01_and_omits_empty_years() { + let tmp = TempDirGuard::new("partition"); + let rows = vec![ + make_row(1, 2020, 12, 31, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2021, 1, 1, 10.5, 200.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 6, 1, 12.0, 300.0, None, "USD", "eod_unadj"), + ]; + + let stats = + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.files_written, 3); + assert!(tmp.path().join("bars_1d/year=2020/part.parquet").exists()); + assert!(tmp.path().join("bars_1d/year=2021/part.parquet").exists()); + assert!(!tmp.path().join("bars_1d/year=2022").exists()); + assert!(tmp.path().join("bars_1d/year=2023/part.parquet").exists()); + + assert_eq!( + read_parquet_rows(&tmp.path().join("bars_1d/year=2020/part.parquet")).len(), + 1 + ); + assert_eq!( + read_parquet_rows(&tmp.path().join("bars_1d/year=2021/part.parquet")).len(), + 1 + ); + assert_eq!( + read_parquet_rows(&tmp.path().join("bars_1d/year=2023/part.parquet")).len(), + 1 + ); + } + + #[test] + fn row_groups_split_exact_sizes() { + let tmp = TempDirGuard::new("row-groups"); + let base_date = ymd_to_epoch_days(2024, 1, 2).unwrap(); + let mut rows = Vec::with_capacity(2_500); + for listing_id in 1..=25 { + for day_offset in 0..100 { + let session_date = base_date + day_offset; + let ts_micros = i64::from(session_date) * 86_400_000_000; + rows.push(Bars1dParquetRow { + listing_id, + ts_micros, + session_date, + open: 20.0, + high: 21.0, + low: 19.5, + close: 20.5, + volume: 10_000.0, + vwap: Some(20.25), + currency: Cow::Borrowed("USD"), + source: Cow::Borrowed("eod_unadj"), + known_at_micros: ts_micros, + }); + } + } + + let options = Bars1dWriteOptions { + row_group_rows: 1_000, + zstd_level: DEFAULT_ZSTD_LEVEL, + }; + let stats = write_bars_1d_dataset(tmp.path(), &rows, options).unwrap(); + assert_eq!(stats.rows_written, 2_500); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.row_groups_written, 3); + + let file = File::open(tmp.path().join("bars_1d/year=2024/part.parquet")).unwrap(); + let reader = SerializedFileReader::new(file).unwrap(); + assert_eq!(reader.metadata().num_row_groups(), 3); + assert_eq!(reader.metadata().row_group(0).num_rows(), 1_000); + assert_eq!(reader.metadata().row_group(1).num_rows(), 1_000); + assert_eq!(reader.metadata().row_group(2).num_rows(), 500); + } + + #[test] + fn empty_input_returns_zero_stats_and_creates_nothing() { + let tmp = TempDirGuard::new("empty"); + let empty: Vec = Vec::new(); + let stats = + write_bars_1d_dataset(tmp.path(), &empty, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats, Bars1dWriteStats::default()); + assert!(!tmp.path().join("bars_1d").exists()); + } + + #[test] + fn writing_same_rows_twice_is_byte_identical() { + let tmp_a = TempDirGuard::new("det-a"); + let tmp_b = TempDirGuard::new("det-b"); + let rows = vec![ + make_row(1, 2023, 2, 1, 10.0, 1_000.0, Some(10.0), "USD", "eod_unadj"), + make_row(1, 2024, 2, 1, 11.0, 2_000.0, None, "USD", "eod_unadj"), + make_row(2, 2023, 2, 1, 20.0, 3_000.0, Some(19.9), "CAD", "qm_raw"), + make_row(2, 2024, 2, 1, 21.0, 4_000.0, None, "CAD", "qm_raw"), + ]; + + let stats_a = + write_bars_1d_dataset(tmp_a.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + let stats_b = + write_bars_1d_dataset(tmp_b.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats_a, stats_b); + + for year in [2023, 2024] { + let bytes_a = + fs::read(tmp_a.path().join(format!("bars_1d/year={year:04}/part.parquet"))) + .unwrap(); + let bytes_b = + fs::read(tmp_b.path().join(format!("bars_1d/year={year:04}/part.parquet"))) + .unwrap(); + assert_eq!(bytes_a, bytes_b, "year {year} parquet bytes must match"); + } + } + + #[test] + fn failure_modes_return_typed_errors_and_preserve_existing_files() { + let tmp = TempDirGuard::new("failures"); + + // Seed a valid existing 2024 partition. + let initial = vec![make_row( + 1, + 2024, + 1, + 2, + 100.0, + 5_000.0, + Some(99.5), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap(); + let existing_path = tmp.path().join("bars_1d/year=2024/part.parquet"); + let existing_tmp = tmp.path().join("bars_1d/year=2024/part.parquet.tmp"); + let original_bytes = fs::read(&existing_path).unwrap(); + + // 1. Invalid row_group_rows = 0 + let err = write_bars_1d_dataset( + tmp.path(), + &initial, + Bars1dWriteOptions { + row_group_rows: 0, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::InvalidRowGroupRows)); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 2. Invalid Zstd level + let err = write_bars_1d_dataset( + tmp.path(), + &initial, + Bars1dWriteOptions { + row_group_rows: 100, + zstd_level: 99, + }, + ) + .unwrap_err(); + assert!(matches!( + err, + ParquetBarsError::InvalidZstdLevel { level: 99 } + )); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 3. Unsorted input (after writing a valid row into 2024) + let unsorted = vec![ + make_row(2, 2024, 5, 1, 50.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 5, 2, 51.0, 200.0, None, "USD", "eod_unadj"), + ]; + let err = write_bars_1d_dataset(tmp.path(), &unsorted, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!(matches!( + err, + ParquetBarsError::UnsortedInput { + prev_listing_id: 2, + listing_id: 1, + .. + } + )); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 4. Duplicate (listing_id, session_date) + let dup = vec![ + make_row(1, 2024, 6, 3, 50.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 6, 3, 50.0, 100.0, None, "USD", "eod_unadj"), + ]; + let err = + write_bars_1d_dataset(tmp.path(), &dup, Bars1dWriteOptions::default()).unwrap_err(); + assert!(matches!( + err, + ParquetBarsError::DuplicateKey { listing_id: 1, .. } + )); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 5. Session year out of range (< 1900 and > 2200) + let too_old = vec![ + make_row(1, 2024, 1, 2, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(2, 1899, 12, 31, 10.0, 100.0, None, "USD", "eod_unadj"), + ]; + let err = write_bars_1d_dataset(tmp.path(), &too_old, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!(matches!( + err, + ParquetBarsError::SessionYearOutOfRange { + listing_id: 2, + year: 1899, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + )); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + let too_new = vec![make_row( + 3, + 2201, + 1, + 1, + 10.0, + 100.0, + None, + "USD", + "eod_unadj", + )]; + let err = write_bars_1d_dataset(tmp.path(), &too_new, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!(matches!( + err, + ParquetBarsError::SessionYearOutOfRange { + listing_id: 3, + year: 2201, + .. + } + )); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 6. Unwritable out_dir (path is an existing regular file) + let blocker_file = tmp.path().join("not-a-dir"); + fs::write(&blocker_file, b"file-content").unwrap(); + let err = + write_bars_1d_dataset(&blocker_file, &initial, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::Io { .. })); + assert_eq!(fs::read(&blocker_file).unwrap(), b"file-content"); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + + // 7. Mid-stream failure after flushing a full row group across multiple years + let multi_year_fail = vec![ + make_row(1, 2023, 6, 1, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 6, 1, 11.0, 200.0, None, "USD", "eod_unadj"), + make_row(2, 2024, 6, 1, 12.0, 300.0, None, "USD", "eod_unadj"), + // Out-of-order after year=2024 already flushed a 2-row group to part.parquet.tmp + make_row(2, 2023, 6, 1, 13.0, 400.0, None, "USD", "eod_unadj"), + ]; + let err = write_bars_1d_dataset( + tmp.path(), + &multi_year_fail, + Bars1dWriteOptions { + row_group_rows: 2, + zstd_level: DEFAULT_ZSTD_LEVEL, + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::UnsortedInput { .. })); + assert!(!tmp.path().join("bars_1d/year=2023/part.parquet.tmp").exists()); + assert!(!tmp.path().join("bars_1d/year=2023/part.parquet").exists()); + assert!(!existing_tmp.exists()); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + assert_no_transient_files(&tmp.path().join("bars_1d")); + } + + pub(super) fn assert_no_transient_files(bars_dir: &Path) { + if !bars_dir.exists() { + return; + } + assert!( + !bars_dir.join(".write.lock").exists(), + "stale .write.lock left in {}", + bars_dir.display() + ); + for entry in fs::read_dir(bars_dir).expect("read bars_dir") { + let entry = entry.expect("bars_dir entry"); + let path = entry.path(); + if path.is_dir() { + for sub in fs::read_dir(&path).expect("read year dir") { + let sub = sub.expect("year dir entry"); + let name = sub.file_name(); + let name_str = name.to_string_lossy(); + assert!( + !name_str.ends_with(".tmp") && !name_str.ends_with(".bak"), + "stale transient file left behind: {}", + sub.path().display() + ); + } + } + } + } + + #[test] + fn publication_rename_failure_rolls_back_replaced_and_new_partitions() { + let tmp = TempDirGuard::new("rename-rollback"); + + // Seed an existing 2023 partition. + let initial_2023 = vec![make_row( + 1, + 2023, + 5, + 10, + 75.0, + 10_000.0, + Some(74.8), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial_2023, Bars1dWriteOptions::default()).unwrap(); + let path_2023 = tmp.path().join("bars_1d/year=2023/part.parquet"); + let original_2023_bytes = fs::read(&path_2023).unwrap(); + + // Occupy 2024's final path with a directory so the third partition's rename fails + // after 2022 (new) and 2023 (replaced) have already been renamed into place. + let blocker_2024 = tmp.path().join("bars_1d/year=2024/part.parquet"); + fs::create_dir_all(&blocker_2024).unwrap(); + + let refresh = vec![ + make_row(1, 2022, 6, 1, 50.0, 1_000.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 6, 1, 99.0, 2_000.0, Some(98.5), "USD", "eod_unadj"), + make_row(1, 2024, 6, 1, 120.0, 3_000.0, None, "USD", "eod_unadj"), + ]; + + let err = write_bars_1d_dataset(tmp.path(), &refresh, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!( + matches!(&err, ParquetBarsError::Io { path, .. } if path == &blocker_2024), + "expected Io error at {}, got {err:?}", + blocker_2024.display() + ); + + // Newly published 2022 partition must be removed on rollback. + assert!( + !tmp.path().join("bars_1d/year=2022/part.parquet").exists(), + "newly published 2022 partition must be rolled back" + ); + // Existing 2023 partition must be restored byte-for-byte from backup. + assert_eq!( + fs::read(&path_2023).unwrap(), + original_2023_bytes, + "existing 2023 partition must be restored byte-identical" + ); + // Occupying directory at 2024 must remain untouched. + assert!(blocker_2024.is_dir()); + assert_no_transient_files(&tmp.path().join("bars_1d")); + } + + #[test] + fn overlapping_writers_serialize_without_corruption_or_mixed_generations() { + use std::sync::mpsc; + + let tmp = TempDirGuard::new("overlap"); + let out_dir = tmp.path().to_path_buf(); + + let rows_a = vec![ + make_row(1, 2023, 3, 1, 100.0, 1_000.0, Some(100.0), "USD", "eod_unadj"), + make_row(1, 2024, 3, 1, 101.0, 1_100.0, Some(101.0), "USD", "eod_unadj"), + make_row(2, 2023, 3, 1, 102.0, 1_200.0, None, "CAD", "eod_unadj"), + make_row(2, 2024, 3, 1, 103.0, 1_300.0, None, "CAD", "eod_unadj"), + ]; + let rows_b = vec![ + make_row(1, 2023, 4, 1, 200.0, 2_000.0, Some(200.0), "USD", "qm_raw"), + make_row(1, 2024, 4, 1, 201.0, 2_100.0, Some(201.0), "USD", "qm_raw"), + make_row(2, 2023, 4, 1, 202.0, 2_200.0, None, "CAD", "qm_raw"), + make_row(2, 2024, 4, 1, 203.0, 2_300.0, None, "CAD", "qm_raw"), + ]; + + struct SignalingIter { + rows: std::vec::IntoIter, + seen: usize, + on_second: Option>, + on_end: Option>, + } + + impl Iterator for SignalingIter { + type Item = Bars1dParquetRow; + fn next(&mut self) -> Option { + self.seen += 1; + if self.seen == 2 { + if let Some(cb) = self.on_second.take() { + cb(); + } + } + let item = self.rows.next(); + if item.is_none() { + if let Some(cb) = self.on_end.take() { + cb(); + } + } + item + } + } + + let events = Arc::new(Mutex::new(Vec::<&'static str>::new())); + let (t1_locked_tx, t1_locked_rx) = mpsc::channel::<()>(); + let (t2_started_tx, t2_started_rx) = mpsc::channel::<()>(); + + let out_dir_1 = out_dir.clone(); + let events_1 = Arc::clone(&events); + let events_1_end = Arc::clone(&events); + let rows_a_clone = rows_a.clone(); + let handle_1 = thread::spawn(move || { + let iter = SignalingIter { + rows: rows_a_clone.into_iter(), + seen: 0, + on_second: Some(Box::new(move || { + events_1.lock().unwrap().push("t1_row2"); + let _ = t1_locked_tx.send(()); + // Wait briefly for thread 2 to enter write_bars_1d_dataset and block on lock. + let _ = t2_started_rx.recv_timeout(Duration::from_secs(2)); + thread::sleep(Duration::from_millis(30)); + })), + on_end: Some(Box::new(move || { + events_1_end.lock().unwrap().push("t1_iter_end"); + })), + }; + write_bars_1d_dataset(&out_dir_1, iter, Bars1dWriteOptions::default()) + }); + + let out_dir_2 = out_dir.clone(); + let events_2 = Arc::clone(&events); + let rows_b_clone = rows_b.clone(); + let handle_2 = thread::spawn(move || { + t1_locked_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + let _ = t2_started_tx.send(()); + let iter = SignalingIter { + rows: rows_b_clone.into_iter(), + seen: 0, + on_second: Some(Box::new(move || { + events_2.lock().unwrap().push("t2_row2"); + })), + on_end: None, + }; + write_bars_1d_dataset(&out_dir_2, iter, Bars1dWriteOptions::default()) + }); + + let stats_1 = handle_1.join().unwrap().unwrap(); + let stats_2 = handle_2.join().unwrap().unwrap(); + assert_eq!(stats_1.rows_written, rows_a.len()); + assert_eq!(stats_2.rows_written, rows_b.len()); + + // Thread 1 must have finished its entire stream before Thread 2 could pull row 2 under the lock. + let recorded = events.lock().unwrap(); + let pos_t1_end = recorded + .iter() + .position(|&e| e == "t1_iter_end") + .expect("t1_iter_end recorded"); + let pos_t2_row2 = recorded + .iter() + .position(|&e| e == "t2_row2") + .expect("t2_row2 recorded"); + assert!( + pos_t1_end < pos_t2_row2, + "expected strict serialization, got events: {recorded:?}" + ); + + // Final on-disk partitions must match Thread 2 across all years (no mixed generations). + for year in [2023, 2024] { + let actual = read_parquet_rows( + &out_dir.join(format!("bars_1d/year={year:04}/part.parquet")), + ); + let expected: Vec<&Bars1dParquetRow> = rows_b + .iter() + .filter(|r| epoch_days_to_ymd(r.session_date).0 == year) + .collect(); + assert_eq!(actual.len(), expected.len()); + for (a, e) in actual.iter().zip(expected.iter()) { + assert_row_bitwise_eq(a, e); + } + } + assert_no_transient_files(&out_dir.join("bars_1d")); + } + + #[test] + fn exclusive_staging_and_cleanup_preserve_unowned_tmp_files() { + let tmp = TempDirGuard::new("unowned-tmp"); + let year_dir = tmp.path().join("bars_1d/year=2024"); + fs::create_dir_all(&year_dir).unwrap(); + + let foreign_tmp_1 = year_dir.join("part.parquet.tmp"); + let foreign_tmp_2 = year_dir.join("part.parquet.foreign.tmp"); + fs::write(&foreign_tmp_1, b"foreign-staging-1").unwrap(); + fs::write(&foreign_tmp_2, b"foreign-staging-2").unwrap(); + + // Failing run must clean up only its own staging file and never touch unowned .tmp files. + let unsorted = vec![ + make_row(2, 2024, 5, 1, 50.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 5, 2, 51.0, 200.0, None, "USD", "eod_unadj"), + ]; + let err = write_bars_1d_dataset(tmp.path(), &unsorted, Bars1dWriteOptions::default()) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::UnsortedInput { .. })); + assert_eq!(fs::read(&foreign_tmp_1).unwrap(), b"foreign-staging-1"); + assert_eq!(fs::read(&foreign_tmp_2).unwrap(), b"foreign-staging-2"); + + // Succeeding run must also preserve unowned .tmp files and leave only part.parquet + foreign files. + let valid = vec![make_row( + 1, + 2024, + 5, + 1, + 50.0, + 100.0, + None, + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &valid, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(fs::read(&foreign_tmp_1).unwrap(), b"foreign-staging-1"); + assert_eq!(fs::read(&foreign_tmp_2).unwrap(), b"foreign-staging-2"); + assert_eq!( + read_parquet_rows(&year_dir.join("part.parquet")).len(), + 1 + ); + } + + #[test] + fn string_interner_handles_more_than_linear_limit_distinct_values() { + let tmp = TempDirGuard::new("many-strings"); + let currencies = [ + "USD", "CAD", "EUR", "GBP", "JPY", "CHF", "AUD", "NZD", "SEK", "NOK", "HKD", "SGD", + ]; + let mut rows = Vec::with_capacity(currencies.len() * 2); + for (i, &ccy) in currencies.iter().enumerate() { + rows.push(make_row( + (i + 1) as i32, + 2024, + 3, + 1, + 10.0 + i as f64, + 1_000.0, + None, + ccy, + "eod_unadj", + )); + rows.push(make_row( + (i + 1) as i32, + 2024, + 3, + 2, + 11.0 + i as f64, + 2_000.0, + Some(10.5 + i as f64), + ccy, + "qm_raw", + )); + } + + let stats = + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, rows.len()); + let read_back = read_parquet_rows(&tmp.path().join("bars_1d/year=2024/part.parquet")); + assert_eq!(read_back.len(), rows.len()); + for (actual, expected) in read_back.iter().zip(rows.iter()) { + assert_row_bitwise_eq(actual, expected); + } + } + + #[test] + fn existing_partition_remains_readable_between_backup_and_replacement() { + let tmp = TempDirGuard::new("live-readable"); + + let initial = vec![make_row( + 1, + 2023, + 5, + 10, + 75.0, + 10_000.0, + Some(74.8), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap(); + let path_2023 = tmp.path().join("bars_1d/year=2023/part.parquet"); + let original_bytes = fs::read(&path_2023).unwrap(); + + let refresh = vec![ + make_row(1, 2023, 6, 1, 99.0, 20_000.0, Some(98.5), "USD", "eod_unadj"), + make_row(2, 2023, 6, 2, 101.0, 30_000.0, None, "CAD", "qm_raw"), + ]; + + let mut observed_mid_publish = false; + let stats = write_bars_1d_dataset_with_hooks( + tmp.path(), + &refresh, + Bars1dWriteOptions::default(), + DEFAULT_LOCK_TIMEOUT, + |year, final_path, backup_path| { + assert_eq!(year, 2023); + let bak = backup_path.expect("backup must be created for existing partition"); + assert!(bak.exists(), "backup must exist before replacement"); + assert!( + final_path.exists(), + "live partition must remain present after backup creation" + ); + assert_eq!( + fs::read(final_path).expect("read live partition before rename"), + original_bytes + ); + let live_rows = read_parquet_rows(final_path); + assert_eq!(live_rows.len(), initial.len()); + assert_row_bitwise_eq(&live_rows[0], &initial[0]); + observed_mid_publish = true; + }, + ) + .unwrap(); + + assert!(observed_mid_publish, "on_after_backup hook must run"); + assert_eq!(stats.rows_written, refresh.len()); + let updated_rows = read_parquet_rows(&path_2023); + assert_eq!(updated_rows.len(), refresh.len()); + for (actual, expected) in updated_rows.iter().zip(refresh.iter()) { + assert_row_bitwise_eq(actual, expected); + } + assert_no_transient_files(&tmp.path().join("bars_1d")); + } + + #[test] + fn abandoned_write_lock_times_out_with_actionable_error() { + let tmp = TempDirGuard::new("abandoned-lock"); + + let initial = vec![make_row( + 1, + 2024, + 1, + 2, + 100.0, + 5_000.0, + Some(99.5), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap(); + let existing_path = tmp.path().join("bars_1d/year=2024/part.parquet"); + let original_bytes = fs::read(&existing_path).unwrap(); + + // Simulate a crashed writer that left `.write.lock` behind. + let lock_path = tmp.path().join("bars_1d/.write.lock"); + fs::write(&lock_path, b"999999\n").unwrap(); + + let timeout = Duration::from_millis(40); + let refresh = vec![make_row( + 1, + 2024, + 2, + 1, + 105.0, + 6_000.0, + None, + "USD", + "eod_unadj", + )]; + let err = write_bars_1d_dataset_with_hooks( + tmp.path(), + &refresh, + Bars1dWriteOptions::default(), + timeout, + |_, _, _| {}, + ) + .unwrap_err(); + + match &err { + ParquetBarsError::LockTimeout { path, waited } => { + assert_eq!(path, &lock_path); + assert!(*waited >= timeout); + } + other => panic!("expected LockTimeout, got {other:?}"), + } + let msg = err.to_string(); + assert!( + msg.contains(&lock_path.display().to_string()), + "LockTimeout message must include lock path, got: {msg}" + ); + // Abandoned lock is not unowned-deleted, and existing partition is untouched. + assert_eq!(fs::read(&lock_path).unwrap(), b"999999\n"); + assert_eq!(fs::read(&existing_path).unwrap(), original_bytes); + // Clean up simulated lock so assert_no_transient_files checks for stray .tmp/.bak. + fs::remove_file(&lock_path).unwrap(); + assert_no_transient_files(&tmp.path().join("bars_1d")); + } + + #[test] + fn rollback_failure_reports_original_error_and_partition_backup_paths() { + let tmp = TempDirGuard::new("rollback-failure"); + + let initial_2023 = vec![make_row( + 1, + 2023, + 5, + 10, + 75.0, + 10_000.0, + Some(74.8), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial_2023, Bars1dWriteOptions::default()).unwrap(); + let path_2023 = tmp.path().join("bars_1d/year=2023/part.parquet"); + let original_2023_bytes = fs::read(&path_2023).unwrap(); + + // Block 2024 publication with a directory so 2024 rename fails after 2023 is replaced. + let blocker_2024 = tmp.path().join("bars_1d/year=2024/part.parquet"); + fs::create_dir_all(&blocker_2024).unwrap(); + + let refresh = vec![ + make_row(1, 2023, 6, 1, 99.0, 2_000.0, Some(98.5), "USD", "eod_unadj"), + make_row(1, 2024, 6, 1, 120.0, 3_000.0, None, "USD", "eod_unadj"), + ]; + + let mut captured_2023_backup: Option = None; + let path_2023_for_hook = path_2023.clone(); + let err = write_bars_1d_dataset_with_hooks( + tmp.path(), + &refresh, + Bars1dWriteOptions::default(), + DEFAULT_LOCK_TIMEOUT, + |year, _final_path, backup_path| { + if year == 2023 { + captured_2023_backup = backup_path.map(Path::to_path_buf); + } else if year == 2024 { + // Replace already-published 2023 file with a directory so rollback's + // `fs::rename(bak, path_2023)` deterministically fails. + fs::remove_file(&path_2023_for_hook).unwrap(); + fs::create_dir(&path_2023_for_hook).unwrap(); + } + }, + ) + .unwrap_err(); + + let expected_bak = captured_2023_backup.expect("2023 backup path recorded"); + match &err { + ParquetBarsError::RollbackFailed { cause, failures } => { + assert!( + matches!(cause.as_ref(), ParquetBarsError::Io { path, .. } if path == &blocker_2024), + "expected original cause at {}, got {cause:?}", + blocker_2024.display() + ); + assert_eq!(failures.len(), 1); + assert_eq!(failures[0].final_path, path_2023); + assert_eq!(failures[0].backup_path.as_deref(), Some(expected_bak.as_path())); + } + other => panic!("expected RollbackFailed, got {other:?}"), + } + + let msg = err.to_string(); + assert!(msg.contains(&blocker_2024.display().to_string()), "{msg}"); + assert!(msg.contains(&path_2023.display().to_string()), "{msg}"); + assert!(msg.contains(&expected_bak.display().to_string()), "{msg}"); + assert!(err.source().is_some()); + // Original backup remains intact on disk for operator recovery. + assert_eq!(fs::read(&expected_bak).unwrap(), original_2023_bytes); + } +} + +#[cfg(test)] +#[path = "parquet_bars_tests.rs"] +mod edge_case_tests; diff --git a/tools/curate-etl/src/parquet_bars_tests.rs b/tools/curate-etl/src/parquet_bars_tests.rs new file mode 100644 index 00000000..53c42789 --- /dev/null +++ b/tools/curate-etl/src/parquet_bars_tests.rs @@ -0,0 +1,886 @@ +use std::borrow::Cow; +use std::fs::{self, File}; +use std::time::Duration; + +use parquet::basic::Encoding; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +use super::tests::{ + assert_no_transient_files, assert_row_bitwise_eq, make_row, read_parquet_rows, TempDirGuard, +}; +use super::{ + write_bars_1d_dataset, write_bars_1d_dataset_with_hooks, Bars1dParquetRow, Bars1dWriteOptions, + ParquetBarsError, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR, +}; +use crate::split::ymd_to_epoch_days; + +#[test] +fn year_bounds_accept_1900_pre_1970_and_2200_bitwise() { + let tmp = TempDirGuard::new("year-bounds-ok"); + let rows = vec![ + make_row(1, 1900, 1, 1, 10.5, 100.0, Some(10.25), "USD", "eod_unadj"), + make_row(1, 1969, 12, 31, 20.0, 200.0, None, "USD", "eod_unadj"), + make_row(1, 2200, 12, 31, 30.75, 300.0, Some(30.5), "CAD", "eod_unadj"), + ]; + assert!(rows[0].session_date < 0); + assert!(rows[1].session_date < 0); + + let stats = + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.files_written, 3); + + for (year, expected) in [(1900, &rows[0]), (1969, &rows[1]), (2200, &rows[2])] { + let path = tmp.path().join(format!("bars_1d/year={year}/part.parquet")); + let actual = read_parquet_rows(&path); + assert_eq!(actual.len(), 1); + assert_row_bitwise_eq(&actual[0], expected); + } + assert_no_transient_files(&tmp.path().join("bars_1d")); +} + +#[test] +fn first_row_year_1899_rejected_before_creating_partition_files() { + let tmp = TempDirGuard::new("year-1899-reject"); + let rows = vec![make_row( + 1, + 1899, + 12, + 31, + 10.0, + 100.0, + None, + "USD", + "eod_unadj", + )]; + + let err = + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap_err(); + assert!( + matches!( + err, + ParquetBarsError::SessionYearOutOfRange { + listing_id: 1, + year: 1899, + min_year: MIN_PARQUET_YEAR, + max_year: MAX_PARQUET_YEAR, + .. + } + ), + "expected SessionYearOutOfRange for 1899, got {err:?}" + ); + + let bars_dir = tmp.path().join("bars_1d"); + assert!(!bars_dir.join("year=1899").exists()); + assert_no_transient_files(&bars_dir); +} + +#[test] +fn zstd_level_boundaries_accept_1_and_22_and_reject_23_without_disk_writes() { + let tmp = TempDirGuard::new("zstd-bounds"); + let rows = vec![make_row( + 1, + 2024, + 3, + 15, + 100.0, + 5_000.0, + Some(99.75), + "USD", + "eod_unadj", + )]; + + let out_bad = tmp.path().join("bad-23"); + let err = write_bars_1d_dataset( + &out_bad, + &rows, + Bars1dWriteOptions { + zstd_level: 23, + ..Bars1dWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::InvalidZstdLevel { level: 23 })); + assert!(!out_bad.exists(), "invalid option must not create output dir"); + + for level in [1, 22] { + let out_ok = tmp.path().join(format!("lvl-{level}")); + let stats = write_bars_1d_dataset( + &out_ok, + &rows, + Bars1dWriteOptions { + zstd_level: level, + ..Bars1dWriteOptions::default() + }, + ) + .unwrap(); + assert_eq!(stats.rows_written, 1); + let actual = read_parquet_rows(&out_ok.join("bars_1d/year=2024/part.parquet")); + assert_eq!(actual.len(), 1); + assert_row_bitwise_eq(&actual[0], &rows[0]); + } +} + +#[test] +fn different_zstd_levels_change_file_bytes_but_preserve_values() { + let tmp = TempDirGuard::new("zstd-diff-levels"); + let mut rows = Vec::with_capacity(200); + let base_day = ymd_to_epoch_days(2024, 1, 2).unwrap(); + for i in 0..200_i32 { + let session_date = base_day + i; + let ts_micros = i64::from(session_date) * 86_400_000_000; + let close = 50.0 + f64::from(i) * 0.13; + rows.push(Bars1dParquetRow { + listing_id: 1, + ts_micros, + session_date, + open: close - 0.25, + high: close + 0.5, + low: close - 0.5, + close, + volume: 10_000.0 + f64::from(i) * 37.0, + vwap: if i % 3 == 0 { None } else { Some(close - 0.05) }, + currency: Cow::Borrowed("USD"), + source: Cow::Borrowed("eod_unadj"), + known_at_micros: ts_micros + 900_000_000, + }); + } + + let out_low = tmp.path().join("lvl-1"); + let out_high = tmp.path().join("lvl-19"); + write_bars_1d_dataset( + &out_low, + &rows, + Bars1dWriteOptions { + zstd_level: 1, + ..Bars1dWriteOptions::default() + }, + ) + .unwrap(); + write_bars_1d_dataset( + &out_high, + &rows, + Bars1dWriteOptions { + zstd_level: 19, + ..Bars1dWriteOptions::default() + }, + ) + .unwrap(); + + let p_low = out_low.join("bars_1d/year=2024/part.parquet"); + let p_high = out_high.join("bars_1d/year=2024/part.parquet"); + assert_ne!(fs::read(&p_low).unwrap(), fs::read(&p_high).unwrap()); + + let actual_low = read_parquet_rows(&p_low); + let actual_high = read_parquet_rows(&p_high); + assert_eq!(actual_low.len(), rows.len()); + assert_eq!(actual_high.len(), rows.len()); + for i in 0..rows.len() { + assert_row_bitwise_eq(&actual_low[i], &rows[i]); + assert_row_bitwise_eq(&actual_high[i], &rows[i]); + } +} + +#[test] +fn exact_multiple_row_groups_and_row_group_size_one_leave_no_empty_groups() { + let tmp = TempDirGuard::new("rg-exact-and-one"); + let base_day = ymd_to_epoch_days(2024, 1, 2).unwrap(); + let rows: Vec = (0..12_i32) + .map(|i| { + let session_date = base_day + i; + let ts_micros = i64::from(session_date) * 86_400_000_000; + Bars1dParquetRow { + listing_id: 1, + ts_micros, + session_date, + open: 10.0, + high: 11.0, + low: 9.0, + close: 10.5 + f64::from(i), + volume: 100.0, + vwap: Some(10.25), + currency: Cow::Borrowed("USD"), + source: Cow::Borrowed("eod_unadj"), + known_at_micros: ts_micros + 1_000, + } + }) + .collect(); + + // Exact multiple: 12 rows / 4 per row group => 3 groups of 4, no trailing empty group. + let out_mult = tmp.path().join("mult"); + let stats_mult = write_bars_1d_dataset( + &out_mult, + &rows, + Bars1dWriteOptions { + row_group_rows: 4, + ..Bars1dWriteOptions::default() + }, + ) + .unwrap(); + assert_eq!(stats_mult.row_groups_written, 3); + let reader = SerializedFileReader::new( + File::open(out_mult.join("bars_1d/year=2024/part.parquet")).unwrap(), + ) + .unwrap(); + let rg_sizes: Vec = (0..reader.metadata().num_row_groups()) + .map(|i| reader.metadata().row_group(i).num_rows()) + .collect(); + assert_eq!(rg_sizes, vec![4, 4, 4]); + + // Minimum row group size: 1 row per group. + let out_one = tmp.path().join("one"); + let stats_one = write_bars_1d_dataset( + &out_one, + &rows[..5], + Bars1dWriteOptions { + row_group_rows: 1, + ..Bars1dWriteOptions::default() + }, + ) + .unwrap(); + assert_eq!(stats_one.row_groups_written, 5); + let p_one = out_one.join("bars_1d/year=2024/part.parquet"); + let reader_one = SerializedFileReader::new(File::open(&p_one).unwrap()).unwrap(); + let rg_one_sizes: Vec = (0..reader_one.metadata().num_row_groups()) + .map(|i| reader_one.metadata().row_group(i).num_rows()) + .collect(); + assert_eq!(rg_one_sizes, vec![1, 1, 1, 1, 1]); + let actual_one = read_parquet_rows(&p_one); + for (a, e) in actual_one.iter().zip(&rows[..5]) { + assert_row_bitwise_eq(a, e); + } +} + +#[test] +fn interleaved_years_across_listings_maintain_independent_row_group_buffers() { + let tmp = TempDirGuard::new("interleaved-years"); + // 5 listings each with a 2023 row and a 2024 row (strictly ascending by (listing_id, session_date)). + let mut rows = Vec::new(); + for listing_id in 1..=5_i32 { + rows.push(make_row( + listing_id, + 2023, + 6, + 15, + 100.0 + f64::from(listing_id), + 1_000.0, + Some(100.0), + "USD", + "eod_unadj", + )); + rows.push(make_row( + listing_id, + 2024, + 6, + 15, + 200.0 + f64::from(listing_id), + 2_000.0, + None, + "CAD", + "qm_raw", + )); + } + + let stats = write_bars_1d_dataset( + tmp.path(), + &rows, + Bars1dWriteOptions { + row_group_rows: 2, + ..Bars1dWriteOptions::default() + }, + ) + .unwrap(); + // 5 rows per year with row_group_rows=2 => 3 row groups per year (2, 2, 1) => 6 total. + assert_eq!(stats.files_written, 2); + assert_eq!(stats.row_groups_written, 6); + + for year in [2023, 2024] { + let path = tmp.path().join(format!("bars_1d/year={year}/part.parquet")); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let sizes: Vec = (0..reader.metadata().num_row_groups()) + .map(|i| reader.metadata().row_group(i).num_rows()) + .collect(); + assert_eq!(sizes, vec![2, 2, 1]); + let actual = read_parquet_rows(&path); + let expected_ids: Vec = actual.iter().map(|r| r.listing_id).collect(); + assert_eq!(expected_ids, vec![1, 2, 3, 4, 5]); + } +} + +#[test] +fn backwards_date_within_same_listing_returns_unsorted_input_naming_both_rows() { + let tmp = TempDirGuard::new("backwards-date"); + let first = make_row(7, 2024, 5, 10, 50.0, 100.0, None, "USD", "eod_unadj"); + let second = make_row(7, 2024, 5, 9, 49.0, 100.0, None, "USD", "eod_unadj"); + let d1 = first.session_date; + let d2 = second.session_date; + + let err = write_bars_1d_dataset(tmp.path(), &[first, second], Bars1dWriteOptions::default()) + .unwrap_err(); + assert!( + matches!( + err, + ParquetBarsError::UnsortedInput { + prev_listing_id: 7, + prev_session_date, + listing_id: 7, + session_date, + } if prev_session_date == d1 && session_date == d2 + ), + "expected UnsortedInput naming both rows, got {err:?}" + ); + assert_no_transient_files(&tmp.path().join("bars_1d")); +} + +#[test] +fn negative_listing_ids_sort_and_round_trip_correctly() { + let tmp = TempDirGuard::new("negative-listings"); + let rows = vec![ + make_row(-100, 2024, 1, 2, 10.0, 50.0, None, "USD", "eod_unadj"), + make_row(-1, 2024, 1, 2, 20.0, 60.0, Some(19.9), "USD", "eod_unadj"), + make_row(0, 2024, 1, 2, 30.0, 70.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 1, 2, 40.0, 80.0, Some(39.8), "USD", "eod_unadj"), + ]; + + let stats = + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 4); + let actual = read_parquet_rows(&tmp.path().join("bars_1d/year=2024/part.parquet")); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } +} + +#[test] +fn special_ieee754_floats_and_all_none_or_all_some_vwap_round_trip_bitwise() { + let tmp = TempDirGuard::new("special-floats"); + let base_day = ymd_to_epoch_days(2024, 2, 1).unwrap(); + let payload_nan = f64::from_bits(0x7ff8_0000_0000_0042); + let subnormal = f64::MIN_POSITIVE / 2.0; + assert!(subnormal.is_subnormal()); + + // Row group 1 (2 rows): all-None vwap, special IEEE-754 bit patterns. + // Row group 2 (2 rows): all-Some vwap, including payload NaN and -0.0. + let rows = vec![ + Bars1dParquetRow { + listing_id: 1, + ts_micros: i64::from(base_day) * 86_400_000_000, + session_date: base_day, + open: -0.0, + high: f64::INFINITY, + low: f64::NEG_INFINITY, + close: subnormal, + volume: -0.0, + vwap: None, + currency: Cow::Borrowed("USD"), + source: Cow::Borrowed("eod_unadj"), + known_at_micros: i64::from(base_day) * 86_400_000_000 + 1, + }, + Bars1dParquetRow { + listing_id: 1, + ts_micros: i64::from(base_day + 1) * 86_400_000_000, + session_date: base_day + 1, + open: payload_nan, + high: -subnormal, + low: 0.0, + close: 1.0, + volume: subnormal, + vwap: None, + currency: Cow::Borrowed("USD"), + source: Cow::Borrowed("eod_unadj"), + known_at_micros: i64::from(base_day + 1) * 86_400_000_000 + 1, + }, + Bars1dParquetRow { + listing_id: 1, + ts_micros: i64::from(base_day + 2) * 86_400_000_000, + session_date: base_day + 2, + open: 10.0, + high: 11.0, + low: 9.0, + close: 10.5, + volume: 100.0, + vwap: Some(payload_nan), + currency: Cow::Borrowed("USD"), + source: Cow::Borrowed("eod_unadj"), + known_at_micros: i64::from(base_day + 2) * 86_400_000_000 + 1, + }, + Bars1dParquetRow { + listing_id: 1, + ts_micros: i64::from(base_day + 3) * 86_400_000_000, + session_date: base_day + 3, + open: 10.0, + high: 11.0, + low: 9.0, + close: 10.5, + volume: 100.0, + vwap: Some(-0.0), + currency: Cow::Borrowed("USD"), + source: Cow::Borrowed("eod_unadj"), + known_at_micros: i64::from(base_day + 3) * 86_400_000_000 + 1, + }, + ]; + + write_bars_1d_dataset( + tmp.path(), + &rows, + Bars1dWriteOptions { + row_group_rows: 2, + ..Bars1dWriteOptions::default() + }, + ) + .unwrap(); + + let actual = read_parquet_rows(&tmp.path().join("bars_1d/year=2024/part.parquet")); + assert_eq!(actual.len(), rows.len()); + for (a, e) in actual.iter().zip(&rows) { + assert_row_bitwise_eq(a, e); + } +} + +#[test] +fn owned_empty_and_many_distinct_strings_round_trip_when_passed_by_value() { + let tmp = TempDirGuard::new("owned-strings-by-value"); + let base_day = ymd_to_epoch_days(2024, 4, 1).unwrap(); + let expected: Vec = (0..12_i32) + .map(|i| { + let session_date = base_day + i; + let ts_micros = i64::from(session_date) * 86_400_000_000; + let currency = if i == 0 { + Cow::Owned(String::new()) + } else { + Cow::Owned(format!("CUR{i:02}")) + }; + let source = if i == 1 { + Cow::Owned(String::new()) + } else { + Cow::Owned(format!("src_{i:02}")) + }; + Bars1dParquetRow { + listing_id: 1, + ts_micros, + session_date, + open: 10.0, + high: 11.0, + low: 9.0, + close: 10.5, + volume: 500.0, + vwap: Some(10.25), + currency, + source, + known_at_micros: ts_micros + 60_000_000, + } + }) + .collect(); + + // Pass owned Vec by value (not &[...]). + let stats = write_bars_1d_dataset( + tmp.path(), + expected.clone(), + Bars1dWriteOptions::default(), + ) + .unwrap(); + assert_eq!(stats.rows_written, expected.len()); + + let actual = read_parquet_rows(&tmp.path().join("bars_1d/year=2024/part.parquet")); + assert_eq!(actual.len(), expected.len()); + for (a, e) in actual.iter().zip(&expected) { + assert_row_bitwise_eq(a, e); + } +} + +#[test] +fn currency_and_source_columns_use_dictionary_encoding() { + let tmp = TempDirGuard::new("dict-encoding"); + let base_day = ymd_to_epoch_days(2024, 1, 2).unwrap(); + let rows: Vec = (0..100_i32) + .map(|i| { + let session_date = base_day + i; + let ts_micros = i64::from(session_date) * 86_400_000_000; + Bars1dParquetRow { + listing_id: 1, + ts_micros, + session_date, + open: 10.0, + high: 11.0, + low: 9.0, + close: 10.5, + volume: 1_000.0, + vwap: None, + currency: Cow::Borrowed(if i % 2 == 0 { "USD" } else { "CAD" }), + source: Cow::Borrowed(if i % 3 == 0 { "eod_unadj" } else { "qm_raw" }), + known_at_micros: ts_micros + 900_000_000, + } + }) + .collect(); + + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + let path = tmp.path().join("bars_1d/year=2024/part.parquet"); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + let rg = reader.metadata().row_group(0); + + for (col_idx, name) in [(9, "currency"), (10, "source")] { + let col = rg.column(col_idx); + assert_eq!(col.column_descr().name(), name); + assert!( + col.dictionary_page_offset().is_some(), + "expected dictionary page for column {name}" + ); + let has_dict_encoding = col + .encodings() + .any(|enc| matches!(enc, Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY)); + assert!( + has_dict_encoding, + "expected dictionary encoding on column {name}, got {:?}", + col.encodings().collect::>() + ); + } +} + +#[test] +fn stats_bytes_written_and_rows_by_year_match_disk_files_and_footers() { + let tmp = TempDirGuard::new("stats-match-disk"); + let rows = vec![ + make_row(1, 2022, 3, 1, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 3, 1, 20.0, 200.0, Some(19.5), "USD", "eod_unadj"), + make_row(1, 2023, 3, 2, 21.0, 210.0, Some(20.5), "USD", "eod_unadj"), + make_row(2, 2024, 7, 1, 30.0, 300.0, None, "CAD", "qm_raw"), + make_row(2, 2024, 7, 2, 31.0, 310.0, None, "CAD", "qm_raw"), + make_row(2, 2024, 7, 3, 32.0, 320.0, None, "CAD", "qm_raw"), + ]; + + let stats = + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, rows.len()); + assert_eq!( + stats.rows_by_year.values().copied().sum::(), + stats.rows_written + ); + + let mut disk_bytes = 0_u64; + for (&year, &expected_count) in &stats.rows_by_year { + let path = tmp.path().join(format!("bars_1d/year={year}/part.parquet")); + disk_bytes += fs::metadata(&path).unwrap().len(); + let reader = SerializedFileReader::new(File::open(&path).unwrap()).unwrap(); + assert_eq!( + reader.metadata().file_metadata().num_rows() as usize, + expected_count + ); + } + assert_eq!(stats.bytes_written, disk_bytes); +} + +#[test] +fn rewriting_single_year_replaces_target_leaves_other_years_untouched_and_cleans_transients() { + let tmp = TempDirGuard::new("rewrite-single-year"); + let initial = vec![ + make_row(1, 2023, 4, 1, 50.0, 1_000.0, Some(49.9), "USD", "eod_unadj"), + make_row(1, 2024, 4, 1, 60.0, 2_000.0, None, "USD", "eod_unadj"), + ]; + write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap(); + + let path_2023 = tmp.path().join("bars_1d/year=2023/part.parquet"); + let path_2024 = tmp.path().join("bars_1d/year=2024/part.parquet"); + let orig_2023_bytes = fs::read(&path_2023).unwrap(); + + // Rewrite only 2024 with new data. + let updated_2024 = vec![ + make_row(1, 2024, 4, 1, 65.0, 3_000.0, Some(64.5), "USD", "eod_unadj"), + make_row(1, 2024, 4, 2, 66.0, 3_500.0, Some(65.5), "USD", "eod_unadj"), + ]; + let stats = + write_bars_1d_dataset(tmp.path(), &updated_2024, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.files_written, 1); + assert_eq!(stats.rows_written, 2); + + assert_eq!(fs::read(&path_2023).unwrap(), orig_2023_bytes); + let actual_2024 = read_parquet_rows(&path_2024); + assert_eq!(actual_2024.len(), updated_2024.len()); + for (a, e) in actual_2024.iter().zip(&updated_2024) { + assert_row_bitwise_eq(a, e); + } + assert_no_transient_files(&tmp.path().join("bars_1d")); +} + +#[test] +fn failed_run_releases_write_lock_so_next_run_succeeds_within_50ms() { + let tmp = TempDirGuard::new("lock-release-after-err"); + let bad_rows = vec![ + make_row(2, 2024, 1, 2, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2024, 1, 2, 10.0, 100.0, None, "USD", "eod_unadj"), + ]; + let err = + write_bars_1d_dataset(tmp.path(), &bad_rows, Bars1dWriteOptions::default()).unwrap_err(); + assert!(matches!(err, ParquetBarsError::UnsortedInput { .. })); + + let good_rows = vec![make_row( + 1, + 2024, + 1, + 2, + 10.0, + 100.0, + None, + "USD", + "eod_unadj", + )]; + let stats = write_bars_1d_dataset_with_hooks( + tmp.path(), + &good_rows, + Bars1dWriteOptions::default(), + Duration::from_millis(50), + |_, _, _| {}, + ) + .unwrap(); + assert_eq!(stats.rows_written, 1); + assert_no_transient_files(&tmp.path().join("bars_1d")); +} + +#[test] +fn error_after_30_flushed_row_groups_leaves_no_partial_files() { + let tmp = TempDirGuard::new("err-after-30-rgs"); + let base_day = ymd_to_epoch_days(2024, 1, 2).unwrap(); + let mut rows: Vec = (0..60_i32) + .map(|i| { + let session_date = base_day + i; + let ts_micros = i64::from(session_date) * 86_400_000_000; + Bars1dParquetRow { + listing_id: 1, + ts_micros, + session_date, + open: 10.0, + high: 11.0, + low: 9.0, + close: 10.5, + volume: 100.0, + vwap: None, + currency: Cow::Borrowed("USD"), + source: Cow::Borrowed("eod_unadj"), + known_at_micros: ts_micros + 1_000, + } + }) + .collect(); + // 60 rows with row_group_rows=2 flushes 30 row groups before hitting this duplicate key. + rows.push(rows[59].clone()); + + let err = write_bars_1d_dataset( + tmp.path(), + &rows, + Bars1dWriteOptions { + row_group_rows: 2, + ..Bars1dWriteOptions::default() + }, + ) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::DuplicateKey { listing_id: 1, .. })); + + let final_path = tmp.path().join("bars_1d/year=2024/part.parquet"); + assert!(!final_path.exists(), "partial part.parquet must not be published"); + assert_no_transient_files(&tmp.path().join("bars_1d")); +} + +#[test] +fn bars_1d_path_occupied_by_regular_file_returns_io_error_and_leaves_file_untouched() { + let tmp = TempDirGuard::new("bars-1d-is-file"); + let bars_path = tmp.path().join("bars_1d"); + let sentinel = b"not-a-directory"; + fs::write(&bars_path, sentinel).unwrap(); + + let rows = vec![make_row( + 1, + 2024, + 1, + 2, + 10.0, + 100.0, + Some(10.0), + "USD", + "eod_unadj", + )]; + let err = + write_bars_1d_dataset(tmp.path(), &rows, Bars1dWriteOptions::default()).unwrap_err(); + assert!( + matches!(err, ParquetBarsError::Io { ref path, .. } if path == &bars_path), + "expected Io error for bars_1d path, got {err:?}" + ); + assert!(bars_path.is_file()); + assert_eq!(fs::read(&bars_path).unwrap(), sentinel); + let entries: Vec<_> = fs::read_dir(tmp.path()) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(entries, vec![std::ffi::OsString::from("bars_1d")]); +} + +#[test] +fn blocked_year_dir_partway_through_preserves_prior_year_cleans_staging_and_releases_lock() { + let tmp = TempDirGuard::new("blocked-year-dir"); + let initial = vec![make_row( + 1, + 2024, + 6, + 15, + 100.0, + 1_000.0, + Some(99.5), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap(); + + let path_2024 = tmp.path().join("bars_1d/year=2024/part.parquet"); + let orig_2024_bytes = fs::read(&path_2024).unwrap(); + + // Block year=2025 with a regular file so staging fails partway through after 2024 opens. + let blocked_2025 = tmp.path().join("bars_1d/year=2025"); + fs::write(&blocked_2025, b"blocker").unwrap(); + + let refresh = vec![ + make_row(1, 2024, 6, 15, 110.0, 2_000.0, Some(109.5), "USD", "eod_unadj"), + make_row(1, 2025, 1, 2, 120.0, 3_000.0, Some(119.5), "USD", "eod_unadj"), + ]; + let err = + write_bars_1d_dataset(tmp.path(), &refresh, Bars1dWriteOptions::default()).unwrap_err(); + assert!( + matches!(err, ParquetBarsError::Io { ref path, .. } if path == &blocked_2025), + "expected Io error naming year=2025, got {err:?}" + ); + + assert_eq!(fs::read(&path_2024).unwrap(), orig_2024_bytes); + assert_no_transient_files(&tmp.path().join("bars_1d")); + + // Lock must be released so a subsequent valid write succeeds immediately. + let follow_up = vec![make_row( + 1, + 2024, + 6, + 16, + 111.0, + 2_100.0, + None, + "USD", + "eod_unadj", + )]; + let stats = write_bars_1d_dataset_with_hooks( + tmp.path(), + &follow_up, + Bars1dWriteOptions::default(), + Duration::from_millis(50), + |_, _, _| {}, + ) + .unwrap(); + assert_eq!(stats.rows_written, 1); + assert_no_transient_files(&tmp.path().join("bars_1d")); +} + +#[test] +fn multi_year_refresh_replaces_existing_adds_new_preserves_untouched_and_leaves_only_part_parquet() { + let tmp = TempDirGuard::new("multi-year-refresh"); + let initial = vec![ + make_row(1, 2022, 5, 1, 10.0, 100.0, None, "USD", "eod_unadj"), + make_row(1, 2023, 5, 1, 20.0, 200.0, Some(19.9), "USD", "eod_unadj"), + make_row(1, 2024, 5, 1, 30.0, 300.0, None, "USD", "eod_unadj"), + ]; + write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap(); + + let path_2022 = tmp.path().join("bars_1d/year=2022/part.parquet"); + let orig_2022_bytes = fs::read(&path_2022).unwrap(); + + let refresh = vec![ + make_row(1, 2023, 5, 1, 25.0, 250.0, Some(24.5), "USD", "eod_unadj"), + make_row(1, 2023, 5, 2, 26.0, 260.0, Some(25.5), "USD", "eod_unadj"), + make_row(1, 2024, 5, 1, 35.0, 350.0, Some(34.5), "CAD", "qm_raw"), + make_row(1, 2025, 1, 2, 40.0, 400.0, None, "USD", "eod_unadj"), + make_row(2, 2025, 1, 2, 41.0, 410.0, Some(40.5), "USD", "eod_unadj"), + make_row(3, 2025, 1, 2, 42.0, 420.0, None, "CAD", "qm_raw"), + ]; + let stats = + write_bars_1d_dataset(tmp.path(), &refresh, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.files_written, 3); + assert_eq!(stats.rows_written, 6); + assert_eq!(stats.rows_by_year.get(&2023), Some(&2)); + assert_eq!(stats.rows_by_year.get(&2024), Some(&1)); + assert_eq!(stats.rows_by_year.get(&2025), Some(&3)); + assert_eq!(stats.rows_by_year.get(&2022), None); + + assert_eq!(fs::read(&path_2022).unwrap(), orig_2022_bytes); + assert_eq!( + read_parquet_rows(&tmp.path().join("bars_1d/year=2023/part.parquet")).len(), + 2 + ); + assert_eq!( + read_parquet_rows(&tmp.path().join("bars_1d/year=2024/part.parquet")).len(), + 1 + ); + assert_eq!( + read_parquet_rows(&tmp.path().join("bars_1d/year=2025/part.parquet")).len(), + 3 + ); + + let bars_dir = tmp.path().join("bars_1d"); + assert_no_transient_files(&bars_dir); + for year in [2022, 2023, 2024, 2025] { + let year_dir = bars_dir.join(format!("year={year}")); + let entries: Vec<_> = fs::read_dir(&year_dir) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!( + entries, + vec![std::ffi::OsString::from("part.parquet")], + "year={year} should contain only part.parquet" + ); + } +} + +#[test] +fn active_external_write_lock_times_out_without_deleting_lock_or_modifying_existing_partition() { + let tmp = TempDirGuard::new("external-lock-held"); + let initial = vec![make_row( + 1, + 2024, + 3, + 10, + 50.0, + 500.0, + Some(49.5), + "USD", + "eod_unadj", + )]; + write_bars_1d_dataset(tmp.path(), &initial, Bars1dWriteOptions::default()).unwrap(); + + let path_2024 = tmp.path().join("bars_1d/year=2024/part.parquet"); + let orig_2024_bytes = fs::read(&path_2024).unwrap(); + + let lock_path = tmp.path().join("bars_1d/.write.lock"); + let lock_contents = b"pid=999999\n"; + fs::write(&lock_path, lock_contents).unwrap(); + + let updated = vec![make_row( + 1, + 2024, + 3, + 10, + 99.0, + 999.0, + Some(98.5), + "USD", + "eod_unadj", + )]; + let err = write_bars_1d_dataset_with_hooks( + tmp.path(), + &updated, + Bars1dWriteOptions::default(), + Duration::from_millis(60), + |_, _, _| {}, + ) + .unwrap_err(); + assert!( + matches!(err, ParquetBarsError::LockTimeout { ref path, .. } if path == &lock_path), + "expected LockTimeout naming lock path, got {err:?}" + ); + + assert!(lock_path.exists(), "must not delete another writer's lock"); + assert_eq!(fs::read(&lock_path).unwrap(), lock_contents); + assert_eq!(fs::read(&path_2024).unwrap(), orig_2024_bytes); +} diff --git a/tools/curate-etl/src/provider_mapping.rs b/tools/curate-etl/src/provider_mapping.rs new file mode 100644 index 00000000..c8a7a38e --- /dev/null +++ b/tools/curate-etl/src/provider_mapping.rs @@ -0,0 +1,1055 @@ +//! Pure in-RAM `provider_mapping` lookup table mapping `(source, source_id, bar_date)` to a +//! permanent `listing_id` over inclusive date ranges. +//! +//! Mirrors `provider_mapping` in `database/postgres/init/34-security-master.sql`: +//! - `valid_from` and `valid_to` are UTC Gregorian epoch days (same convention as +//! [`crate::split::ymd_to_epoch_days`]). +//! - `valid_to` is **inclusive**; `None` denotes an open-ended active range. +//! - Primary key is `(source, source_id, valid_from)`: every duplicate `(source, source_id, +//! valid_from)`—including bitwise-identical duplicate rows—is rejected with +//! [`ProviderMappingError::DuplicateValidFrom`]. +//! - Source and `source_id` strings are stored and matched **verbatim** (never trimmed or +//! case-folded), while empty or whitespace-only strings are rejected. + +use std::collections::HashMap; +use std::error::Error; +use std::fmt; + +/// A single raw `provider_mapping` row used to build a [`ProviderMappingTable`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProviderMappingRow { + /// Provider source identifier (e.g. `"eod"`, `"qm"`, `"ib"`, `"ceo"`). + pub source: String, + /// Provider-native security identifier (stored and matched verbatim, never trimmed). + pub source_id: String, + /// Inclusive start date as days since `1970-01-01` (UTC Gregorian). + pub valid_from: i32, + /// Inclusive end date as days since `1970-01-01`, or `None` for open-ended ranges. + pub valid_to: Option, + /// Permanent positive security master `listing_id`. + pub listing_id: i32, +} + +/// A validated, non-overlapping inclusive date range in [`ProviderMappingTable`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MappingRange { + /// Inclusive start date as days since `1970-01-01`. + pub valid_from: i32, + /// Inclusive end date as days since `1970-01-01`, or `None` for open-ended ranges. + pub valid_to: Option, + /// Permanent positive security master `listing_id`. + pub listing_id: i32, +} + +impl MappingRange { + /// Returns `true` if `bar_date` falls within `[valid_from, valid_to]` (or `[valid_from, +inf)` + /// when `valid_to` is `None`). + #[inline] + pub fn contains(&self, bar_date: i32) -> bool { + bar_date >= self.valid_from && self.valid_to.is_none_or(|to| bar_date <= to) + } +} + +/// Typed errors returned while building a [`ProviderMappingTable`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProviderMappingError { + /// `source` was empty or contained only whitespace. + EmptySource, + /// `source_id` was empty or contained only whitespace. + EmptySourceId { source: String }, + /// `listing_id` was `<= 0`. + InvalidListingId { + source: String, + source_id: String, + listing_id: i32, + }, + /// `valid_to < valid_from`. + InvalidRange { + source: String, + source_id: String, + valid_from: i32, + valid_to: i32, + }, + /// Duplicate `(source, source_id, valid_from)` primary key (including identical duplicate rows). + DuplicateValidFrom { + source: String, + source_id: String, + valid_from: i32, + }, + /// Two inclusive ranges for the same `(source, source_id)` intersect, or an open-ended range + /// is followed by a later range. + OverlappingRanges { + source: String, + source_id: String, + first_valid_from: i32, + first_valid_to: Option, + second_valid_from: i32, + second_valid_to: Option, + }, +} + +impl fmt::Display for ProviderMappingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptySource => write!(f, "provider_mapping source must not be empty or blank"), + Self::EmptySourceId { source } => { + write!( + f, + "provider_mapping source_id for source '{source}' must not be empty or blank" + ) + } + Self::InvalidListingId { + source, + source_id, + listing_id, + } => write!( + f, + "invalid listing_id {listing_id} for ({source}, {source_id}): must be > 0" + ), + Self::InvalidRange { + source, + source_id, + valid_from, + valid_to, + } => write!( + f, + "invalid date range [{valid_from}, {valid_to}] for ({source}, {source_id}): valid_to < valid_from" + ), + Self::DuplicateValidFrom { + source, + source_id, + valid_from, + } => write!( + f, + "duplicate primary key ({source}, {source_id}, valid_from={valid_from})" + ), + Self::OverlappingRanges { + source, + source_id, + first_valid_from, + first_valid_to, + second_valid_from, + second_valid_to, + } => write!( + f, + "overlapping date ranges [{first_valid_from}, {first_valid_to:?}] and [{second_valid_from}, {second_valid_to:?}] for ({source}, {source_id})" + ), + } + } +} + +impl Error for ProviderMappingError {} + +type SourceIndex = HashMap; +type SourceGroupedRows = HashMap>; + +/// Zero-allocation in-RAM `provider_mapping` lookup table. +/// +/// All [`MappingRange`] entries are packed into a single contiguous `Vec` arena +/// indexed by a source-partitioned map (`by_source` sorted by `source`, each mapping `source_id` +/// to `(start, len)` in `ranges`). Lookups perform zero heap allocations: one tiny source scan +/// (or binary search for `> 8` sources), one `HashMap::get(source_id)` probe, and one binary +/// search over the key's contiguous range slice. +#[derive(Debug, Clone, Default)] +pub struct ProviderMappingTable { + ranges: Vec, + by_source: Vec<(String, SourceIndex)>, + key_count: usize, +} + +impl ProviderMappingTable { + /// Builds a [`ProviderMappingTable`] from an arbitrary (possibly unsorted) stream of + /// [`ProviderMappingRow`]s. + /// + /// - Rejects empty or whitespace-only `source` / `source_id` without trimming stored values. + /// - Rejects `listing_id <= 0` with [`ProviderMappingError::InvalidListingId`]. + /// - Rejects `valid_to < valid_from` with [`ProviderMappingError::InvalidRange`]. + /// - Rejects every duplicate `(source, source_id, valid_from)`—including bitwise-identical + /// duplicate rows—with [`ProviderMappingError::DuplicateValidFrom`], matching the PostgreSQL + /// `PRIMARY KEY (source, source_id, valid_from)` constraint. + /// - Rejects intersecting inclusive ranges (including an open-ended range followed by a later + /// range) with [`ProviderMappingError::OverlappingRanges`]. Adjacent ranges (`valid_to = d`, + /// next `valid_from = d + 1`) are accepted. + /// - Deterministic for any permutation of input rows (both valid builds and typed validation + /// errors). + pub fn from_rows(rows: I) -> Result + where + I: IntoIterator, + { + let mut grouped: HashMap = HashMap::new(); + let mut total_rows = 0usize; + let mut row_error: Option = None; + + for row in rows { + if let Some(err) = validate_row(&row) { + if matches!(err, ProviderMappingError::EmptySource) { + return Err(err); + } + match &row_error { + None => row_error = Some(err), + Some(current) if cmp_row_error(&err, current).is_lt() => { + row_error = Some(err); + } + Some(_) => {} + } + continue; + } + + if row_error.is_some() { + continue; + } + + grouped + .entry(row.source) + .or_default() + .entry(row.source_id) + .or_default() + .push(MappingRange { + valid_from: row.valid_from, + valid_to: row.valid_to, + listing_id: row.listing_id, + }); + total_rows += 1; + } + + if let Some(err) = row_error { + return Err(err); + } + + let mut sources: Vec<(String, SourceGroupedRows)> = grouped.into_iter().collect(); + sources.sort_unstable_by(|a, b| a.0.cmp(&b.0)); + + let mut ranges = Vec::with_capacity(total_rows); + let mut by_source = Vec::with_capacity(sources.len()); + let mut key_count = 0usize; + + for (source, source_map) in sources { + let mut entries: Vec<(String, Vec)> = source_map.into_iter().collect(); + entries.sort_unstable_by(|a, b| a.0.cmp(&b.0)); + + let mut index = HashMap::with_capacity(entries.len()); + for (source_id, mut key_ranges) in entries { + key_ranges.sort_unstable_by(|a, b| { + a.valid_from + .cmp(&b.valid_from) + .then_with(|| valid_to_sort_key(a.valid_to).cmp(&valid_to_sort_key(b.valid_to))) + .then_with(|| a.listing_id.cmp(&b.listing_id)) + }); + + for pair in key_ranges.windows(2) { + let prev = pair[0]; + let curr = pair[1]; + if prev.valid_from == curr.valid_from { + return Err(ProviderMappingError::DuplicateValidFrom { + source, + source_id, + valid_from: curr.valid_from, + }); + } + let overlaps = match prev.valid_to { + None => true, + Some(prev_to) => prev_to >= curr.valid_from, + }; + if overlaps { + return Err(ProviderMappingError::OverlappingRanges { + source, + source_id, + first_valid_from: prev.valid_from, + first_valid_to: prev.valid_to, + second_valid_from: curr.valid_from, + second_valid_to: curr.valid_to, + }); + } + } + + let start = ranges.len(); + let count = key_ranges.len(); + ranges.extend_from_slice(&key_ranges); + index.insert(source_id, (start, count)); + key_count += 1; + } + + by_source.push((source, index)); + } + + ranges.shrink_to_fit(); + Ok(Self { + ranges, + by_source, + key_count, + }) + } + + /// Number of distinct `(source, source_id)` keys in the table. + #[inline] + pub fn len(&self) -> usize { + self.key_count + } + + /// Returns `true` if the table contains no keys. + #[inline] + pub fn is_empty(&self) -> bool { + self.key_count == 0 + } + + /// Total number of [`MappingRange`] rows stored across all keys. + #[inline] + pub fn range_count(&self) -> usize { + self.ranges.len() + } + + /// Returns the sorted, non-overlapping [`MappingRange`] slice for `(source, source_id)` + /// (empty slice if absent). Performs zero heap allocations. + #[inline] + pub fn ranges_for(&self, source: &str, source_id: &str) -> &[MappingRange] { + let map = if self.by_source.len() <= 8 { + self.by_source + .iter() + .find(|(s, _)| s.as_str() == source) + .map(|(_, m)| m) + } else { + self.by_source + .binary_search_by(|(s, _)| s.as_str().cmp(source)) + .ok() + .and_then(|idx| self.by_source.get(idx).map(|(_, m)| m)) + }; + + let Some(map) = map else { + return &[]; + }; + let Some(&(start, len)) = map.get(source_id) else { + return &[]; + }; + self.ranges.get(start..start + len).unwrap_or(&[]) + } + + /// Resolves `(source, source_id, bar_date)` to its permanent `listing_id`, or `None` if + /// `(source, source_id)` is unknown or `bar_date` does not fall inside any inclusive range. + /// + /// Performs zero heap allocations. + #[inline] + pub fn resolve(&self, source: &str, source_id: &str, bar_date: i32) -> Option { + let slice = self.ranges_for(source, source_id); + let idx = slice.partition_point(|r| r.valid_from <= bar_date); + if idx == 0 { + return None; + } + let candidate = &slice[idx - 1]; + candidate.contains(bar_date).then_some(candidate.listing_id) + } + + /// Creates a [`ProviderMappingCursor`] positioned over the ranges for `(source, source_id)` + /// for amortised O(1) resolution of ascending `bar_date` streams. + #[inline] + pub fn cursor_for(&self, source: &str, source_id: &str) -> ProviderMappingCursor<'_> { + ProviderMappingCursor::new(self.ranges_for(source, source_id)) + } +} + +/// Stateful per-key cursor for resolving sorted (ascending) `bar_date` streams in amortised O(1). +/// +/// If a caller probes an out-of-order (earlier) `bar_date`, the cursor automatically repositions +/// via binary search so results always match [`ProviderMappingTable::resolve`] exactly. +#[derive(Debug, Clone, Copy)] +pub struct ProviderMappingCursor<'a> { + ranges: &'a [MappingRange], + idx: usize, + last_date: i32, +} + +impl<'a> ProviderMappingCursor<'a> { + /// Creates a new cursor over a sorted, non-overlapping slice of [`MappingRange`]s (such as + /// one returned by [`ProviderMappingTable::ranges_for`]). + #[inline] + pub fn new(ranges: &'a [MappingRange]) -> Self { + Self { + ranges, + idx: 0, + last_date: i32::MIN, + } + } + + /// Returns the underlying [`MappingRange`] slice. + #[inline] + pub fn ranges(&self) -> &'a [MappingRange] { + self.ranges + } + + /// Resets the cursor back to the beginning of its range slice. + #[inline] + pub fn reset(&mut self) { + self.idx = 0; + self.last_date = i32::MIN; + } + + /// Resolves `bar_date` against the cursor's ranges. + /// + /// Runs in amortised O(1) for non-decreasing `bar_date` sequences and falls back to binary + /// search if `bar_date < last_date`. + #[inline] + pub fn resolve(&mut self, bar_date: i32) -> Option { + if bar_date < self.last_date { + self.idx = self + .ranges + .partition_point(|r| matches!(r.valid_to, Some(to) if to < bar_date)); + } else { + while let Some(range) = self.ranges.get(self.idx) { + match range.valid_to { + Some(to) if to < bar_date => self.idx += 1, + _ => break, + } + } + } + self.last_date = bar_date; + + self.ranges + .get(self.idx) + .filter(|r| bar_date >= r.valid_from) + .map(|r| r.listing_id) + } +} + +#[inline] +fn valid_to_sort_key(valid_to: Option) -> i64 { + valid_to.map_or(i64::MAX, i64::from) +} + +fn validate_row(row: &ProviderMappingRow) -> Option { + if row.source.trim().is_empty() { + return Some(ProviderMappingError::EmptySource); + } + if row.source_id.trim().is_empty() { + return Some(ProviderMappingError::EmptySourceId { + source: row.source.clone(), + }); + } + if row.listing_id <= 0 { + return Some(ProviderMappingError::InvalidListingId { + source: row.source.clone(), + source_id: row.source_id.clone(), + listing_id: row.listing_id, + }); + } + if let Some(valid_to) = row.valid_to { + if valid_to < row.valid_from { + return Some(ProviderMappingError::InvalidRange { + source: row.source.clone(), + source_id: row.source_id.clone(), + valid_from: row.valid_from, + valid_to, + }); + } + } + None +} + +fn cmp_row_error(a: &ProviderMappingError, b: &ProviderMappingError) -> std::cmp::Ordering { + use std::cmp::Ordering; + use ProviderMappingError as E; + + let rank = |err: &E| -> u8 { + match err { + E::EmptySource => 0, + E::EmptySourceId { .. } => 1, + E::InvalidListingId { .. } => 2, + E::InvalidRange { .. } => 3, + E::DuplicateValidFrom { .. } => 4, + E::OverlappingRanges { .. } => 5, + } + }; + + rank(a).cmp(&rank(b)).then_with(|| match (a, b) { + (E::EmptySource, E::EmptySource) => Ordering::Equal, + (E::EmptySourceId { source: sa }, E::EmptySourceId { source: sb }) => sa.cmp(sb), + ( + E::InvalidListingId { + source: sa, + source_id: ida, + listing_id: la, + }, + E::InvalidListingId { + source: sb, + source_id: idb, + listing_id: lb, + }, + ) => (sa, ida, la).cmp(&(sb, idb, lb)), + ( + E::InvalidRange { + source: sa, + source_id: ida, + valid_from: fa, + valid_to: ta, + }, + E::InvalidRange { + source: sb, + source_id: idb, + valid_from: fb, + valid_to: tb, + }, + ) => (sa, ida, fa, ta).cmp(&(sb, idb, fb, tb)), + _ => Ordering::Equal, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::split::ymd_to_epoch_days; + + fn 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, + } + } + + struct TestRng(u64); + + impl TestRng { + fn new(seed: u64) -> Self { + Self(seed) + } + + 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, items: &mut [T]) { + for i in (1..items.len()).rev() { + let j = (self.next_u64() % (i as u64 + 1)) as usize; + items.swap(i, j); + } + } + } + + #[test] + fn ticker_reuse_fb_us_inclusive_boundaries_and_gap() { + let d_2012_05_17 = ymd_to_epoch_days(2012, 5, 17).unwrap(); + let d_2012_05_18 = ymd_to_epoch_days(2012, 5, 18).unwrap(); + let d_2018_07_01 = ymd_to_epoch_days(2018, 7, 1).unwrap(); + let d_2022_06_08 = ymd_to_epoch_days(2022, 6, 8).unwrap(); + let d_2022_06_09 = ymd_to_epoch_days(2022, 6, 9).unwrap(); + let d_2023_06_01 = ymd_to_epoch_days(2023, 6, 1).unwrap(); + let d_2025_01_01 = ymd_to_epoch_days(2025, 1, 1).unwrap(); + let d_2025_01_02 = ymd_to_epoch_days(2025, 1, 2).unwrap(); + let d_2026_11_28 = ymd_to_epoch_days(2026, 11, 28).unwrap(); + + let table = ProviderMappingTable::from_rows([ + row("eod", "FB.US", d_2025_01_02, None, 2), + row("eod", "FB.US", d_2012_05_18, Some(d_2022_06_08), 1), + ]) + .unwrap(); + + assert_eq!(table.len(), 1); + assert!(!table.is_empty()); + assert_eq!(table.range_count(), 2); + + assert_eq!(table.resolve("eod", "FB.US", d_2012_05_17), None); + assert_eq!(table.resolve("eod", "FB.US", d_2012_05_18), Some(1)); + assert_eq!(table.resolve("eod", "FB.US", d_2018_07_01), Some(1)); + assert_eq!(table.resolve("eod", "FB.US", d_2022_06_08), Some(1)); + assert_eq!(table.resolve("eod", "FB.US", d_2022_06_09), None); + assert_eq!(table.resolve("eod", "FB.US", d_2023_06_01), None); + assert_eq!(table.resolve("eod", "FB.US", d_2025_01_01), None); + assert_eq!(table.resolve("eod", "FB.US", d_2025_01_02), Some(2)); + assert_eq!(table.resolve("eod", "FB.US", d_2026_11_28), Some(2)); + assert_eq!(table.resolve("eod", "FB.US", i32::MAX), Some(2)); + } + + #[test] + fn unknown_keys_cross_source_isolation_and_verbatim_whitespace_ids() { + let d1 = ymd_to_epoch_days(2020, 1, 2).unwrap(); + let d2 = ymd_to_epoch_days(2024, 1, 2).unwrap(); + + let table = ProviderMappingTable::from_rows([ + row("eod", "AAPL.US", d1, None, 10), + row("eod", " AAPL.US ", d1, None, 11), + row("qm", "AAPL", d1, None, 12), + ]) + .unwrap(); + + assert_eq!(table.len(), 3); + assert_eq!(table.range_count(), 3); + + // Exact matches, including verbatim whitespace preservation (no trimming/merging). + assert_eq!(table.resolve("eod", "AAPL.US", d2), Some(10)); + assert_eq!(table.resolve("eod", " AAPL.US ", d2), Some(11)); + assert_eq!(table.resolve("qm", "AAPL", d2), Some(12)); + + // Unknown source, unknown source_id, cross-source isolation, and unspaced vs spaced. + assert_eq!(table.resolve("ib", "AAPL.US", d2), None); + assert_eq!(table.resolve("eod", "MSFT.US", d2), None); + assert_eq!(table.resolve("qm", "AAPL.US", d2), None); + assert_eq!(table.resolve("eod", "AAPL", d2), None); + assert_eq!(table.resolve("eod", " AAPL.US", d2), None); + assert_eq!(table.resolve("eod", "AAPL.US ", d2), None); + assert!(table.ranges_for("ib", "AAPL.US").is_empty()); + assert!(table.ranges_for("eod", "MSFT.US").is_empty()); + } + + #[test] + fn more_than_eight_sources_uses_binary_search_path() { + let d1 = ymd_to_epoch_days(2020, 1, 1).unwrap(); + let sources = [ + "s01", "s02", "s03", "s04", "s05", "s06", "s07", "s08", "s09", "s10", + ]; + let rows: Vec<_> = sources + .iter() + .enumerate() + .map(|(i, s)| row(s, "SYM", d1, None, (i + 1) as i32)) + .collect(); + + let table = ProviderMappingTable::from_rows(rows).unwrap(); + assert_eq!(table.len(), 10); + for (i, s) in sources.iter().enumerate() { + assert_eq!(table.resolve(s, "SYM", d1), Some((i + 1) as i32)); + } + assert_eq!(table.resolve("s00", "SYM", d1), None); + assert_eq!(table.resolve("s99", "SYM", d1), None); + } + + #[test] + fn from_rows_rejects_empty_source_and_empty_source_id() { + let d1 = ymd_to_epoch_days(2020, 1, 1).unwrap(); + + for bad_source in ["", " ", "\t\n"] { + let err = ProviderMappingTable::from_rows([row(bad_source, "AAPL.US", d1, None, 1)]) + .unwrap_err(); + assert_eq!(err, ProviderMappingError::EmptySource); + assert!(!err.to_string().is_empty()); + } + + for bad_id in ["", " ", "\t\r\n"] { + let err = + ProviderMappingTable::from_rows([row("eod", bad_id, d1, None, 1)]).unwrap_err(); + assert_eq!( + err, + ProviderMappingError::EmptySourceId { + source: "eod".to_string() + } + ); + assert!(err.to_string().contains("eod")); + } + } + + #[test] + fn from_rows_rejects_invalid_listing_id_and_invalid_range() { + let d1 = ymd_to_epoch_days(2020, 1, 2).unwrap(); + let d0 = d1 - 1; + + for bad_id in [0, -1, i32::MIN] { + let err = ProviderMappingTable::from_rows([row("eod", "AAPL.US", d1, None, bad_id)]) + .unwrap_err(); + assert_eq!( + err, + ProviderMappingError::InvalidListingId { + source: "eod".to_string(), + source_id: "AAPL.US".to_string(), + listing_id: bad_id, + } + ); + assert!(err.to_string().contains("listing_id")); + } + + let err = ProviderMappingTable::from_rows([row("eod", "AAPL.US", d1, Some(d0), 1)]) + .unwrap_err(); + assert_eq!( + err, + ProviderMappingError::InvalidRange { + source: "eod".to_string(), + source_id: "AAPL.US".to_string(), + valid_from: d1, + valid_to: d0, + } + ); + assert!(err.to_string().contains("valid_to < valid_from")); + } + + #[test] + fn from_rows_rejects_duplicate_valid_from_including_exact_duplicates() { + let d1 = ymd_to_epoch_days(2020, 1, 2).unwrap(); + let d2 = ymd_to_epoch_days(2022, 1, 2).unwrap(); + + // Bitwise-identical duplicate row is rejected (matches Postgres PK). + let exact_dup = ProviderMappingTable::from_rows([ + row("eod", "AAPL.US", d1, Some(d2), 1), + row("eod", "AAPL.US", d1, Some(d2), 1), + ]) + .unwrap_err(); + assert_eq!( + exact_dup, + ProviderMappingError::DuplicateValidFrom { + source: "eod".to_string(), + source_id: "AAPL.US".to_string(), + valid_from: d1, + } + ); + assert!(exact_dup.to_string().contains("duplicate primary key")); + + // Same valid_from with different listing_id / valid_to is also rejected. + let diff_dup = ProviderMappingTable::from_rows([ + row("eod", "AAPL.US", d1, Some(d2), 1), + row("eod", "AAPL.US", d1, None, 2), + ]) + .unwrap_err(); + assert_eq!( + diff_dup, + ProviderMappingError::DuplicateValidFrom { + source: "eod".to_string(), + source_id: "AAPL.US".to_string(), + valid_from: d1, + } + ); + } + + #[test] + fn from_rows_rejects_overlapping_ranges_and_open_ended_followed_by_later() { + let d1 = ymd_to_epoch_days(2020, 1, 1).unwrap(); + let d2 = ymd_to_epoch_days(2021, 1, 1).unwrap(); + let d3 = ymd_to_epoch_days(2022, 1, 1).unwrap(); + + // Touching endpoint (valid_to == next valid_from) is an overlap because valid_to is inclusive. + let touching = ProviderMappingTable::from_rows([ + row("eod", "FB.US", d1, Some(d2), 1), + row("eod", "FB.US", d2, Some(d3), 2), + ]) + .unwrap_err(); + assert_eq!( + touching, + ProviderMappingError::OverlappingRanges { + source: "eod".to_string(), + source_id: "FB.US".to_string(), + first_valid_from: d1, + first_valid_to: Some(d2), + second_valid_from: d2, + second_valid_to: Some(d3), + } + ); + assert!(touching.to_string().contains("overlapping")); + + // Interior overlap. + let interior = ProviderMappingTable::from_rows([ + row("eod", "FB.US", d1, Some(d3), 1), + row("eod", "FB.US", d2, None, 2), + ]) + .unwrap_err(); + assert!(matches!( + interior, + ProviderMappingError::OverlappingRanges { .. } + )); + + // Open-ended row followed by a later row. + let open_then_later = ProviderMappingTable::from_rows([ + row("eod", "FB.US", d2, Some(d3), 2), + row("eod", "FB.US", d1, None, 1), + ]) + .unwrap_err(); + assert_eq!( + open_then_later, + ProviderMappingError::OverlappingRanges { + source: "eod".to_string(), + source_id: "FB.US".to_string(), + first_valid_from: d1, + first_valid_to: None, + second_valid_from: d2, + second_valid_to: Some(d3), + } + ); + } + + #[test] + fn adjacent_ranges_and_i32_extremes_do_not_overflow() { + let d = ymd_to_epoch_days(2022, 6, 8).unwrap(); + + let table = ProviderMappingTable::from_rows([ + row("eod", "ADJ.US", d - 100, Some(d), 1), + row("eod", "ADJ.US", d + 1, Some(d + 1), 2), // single-day range + row("eod", "ADJ.US", d + 2, None, 3), + row("eod", "EXTREME.US", i32::MIN, Some(i32::MIN), 10), + row("eod", "EXTREME.US", i32::MIN + 1, Some(i32::MAX - 1), 11), + row("eod", "EXTREME.US", i32::MAX, Some(i32::MAX), 12), + ]) + .unwrap(); + + assert_eq!(table.resolve("eod", "ADJ.US", d), Some(1)); + assert_eq!(table.resolve("eod", "ADJ.US", d + 1), Some(2)); + assert_eq!(table.resolve("eod", "ADJ.US", d + 2), Some(3)); + + assert_eq!(table.resolve("eod", "EXTREME.US", i32::MIN), Some(10)); + assert_eq!(table.resolve("eod", "EXTREME.US", i32::MIN + 1), Some(11)); + assert_eq!(table.resolve("eod", "EXTREME.US", 0), Some(11)); + assert_eq!(table.resolve("eod", "EXTREME.US", i32::MAX - 1), Some(11)); + assert_eq!(table.resolve("eod", "EXTREME.US", i32::MAX), Some(12)); + + // Verify valid_to == Some(i32::MAX) with a second overlapping row doesn't overflow. + let err = ProviderMappingTable::from_rows([ + row("eod", "MAXOVF", 0, Some(i32::MAX), 1), + row("eod", "MAXOVF", i32::MAX, Some(i32::MAX), 2), + ]) + .unwrap_err(); + assert!(matches!( + err, + ProviderMappingError::OverlappingRanges { .. } + )); + } + + #[test] + fn empty_table_and_permutation_invariance() { + let empty = ProviderMappingTable::from_rows(std::iter::empty()).unwrap(); + assert!(empty.is_empty()); + assert_eq!(empty.len(), 0); + assert_eq!(empty.range_count(), 0); + assert_eq!(empty.resolve("eod", "AAPL.US", 19_000), None); + assert!(empty.ranges_for("eod", "AAPL.US").is_empty()); + let mut cursor = empty.cursor_for("eod", "AAPL.US"); + assert_eq!(cursor.resolve(19_000), None); + + let base_rows = vec![ + row("eod", "FB.US", 15_000, Some(18_000), 1), + row("eod", "FB.US", 19_000, None, 2), + row("qm", "FB", 15_000, Some(18_000), 1), + row("ib", "107113386", 15_000, Some(16_000), 1), + row("ib", "107113386", 16_001, Some(17_500), 3), + row("ib", "107113386", 18_500, Some(19_500), 4), + row("ceo", "SHOP", 16_500, None, 5), + ]; + + let baseline = ProviderMappingTable::from_rows(base_rows.clone()).unwrap(); + let mut rng = TestRng::new(0xDEAD_BEEF_CAFE_0001); + let probe_keys = [ + ("eod", "FB.US"), + ("qm", "FB"), + ("ib", "107113386"), + ("ceo", "SHOP"), + ("eod", "MISSING"), + ]; + let probe_dates = [ + 14_999, 15_000, 16_000, 16_001, 17_500, 17_501, 18_000, 18_001, 18_500, 19_000, 19_500, + 19_501, 25_000, + ]; + + for _ in 0..8 { + let mut shuffled = base_rows.clone(); + rng.shuffle(&mut shuffled); + let candidate = ProviderMappingTable::from_rows(shuffled).unwrap(); + assert_eq!(candidate.len(), baseline.len()); + assert_eq!(candidate.range_count(), baseline.range_count()); + for &(src, id) in &probe_keys { + assert_eq!( + candidate.ranges_for(src, id), + baseline.ranges_for(src, id), + "ranges_for mismatch for ({src}, {id})" + ); + for &d in &probe_dates { + assert_eq!( + candidate.resolve(src, id, d), + baseline.resolve(src, id, d), + "resolve mismatch for ({src}, {id}, {d})" + ); + } + } + } + } + + #[test] + fn cursor_matches_resolve_exhaustively_on_fixed_seed_table() { + let mut rng = TestRng::new(0x570C_4B07_C045_0001); + let sources = ["eod", "qm", "ib", "ceo"]; + let mut rows = Vec::new(); + let mut keys = Vec::new(); + let mut next_listing_id = 1i32; + + for k in 0..100usize { + let src = sources[k % sources.len()]; + let id = format!("KEY{k:03}"); + keys.push((src, id.clone())); + + let range_count = match k % 5 { + 0 => 3, + 1 => 2, + _ => 1, + }; + let mut cur_start = 10_000 + (rng.next_u64() % 500) as i32; + for r in 0..range_count { + let is_last = r + 1 == range_count; + let open_ended = is_last && (k % 2 == 0); + let len = (rng.next_u64() % 200) as i32; + let valid_to = if open_ended { + None + } else { + Some(cur_start + len) + }; + rows.push(row(src, &id, cur_start, valid_to, next_listing_id)); + next_listing_id += 1; + // Mix adjacent (gap=1) and interior-gap (gap>1) transitions. + let gap = if r % 2 == 0 { + 1 + } else { + 2 + (rng.next_u64() % 50) as i32 + }; + cur_start = cur_start + len + gap; + } + } + + rng.shuffle(&mut rows); + let table = ProviderMappingTable::from_rows(rows).unwrap(); + + for (src, id) in &keys { + let mut cursor = table.cursor_for(src, id); + assert_eq!(cursor.ranges(), table.ranges_for(src, id)); + + // Strictly ascending with repeated dates, pre-first, interior gaps, and post-last. + for d in (9_990..=11_500).step_by(3) { + let expected = table.resolve(src, id, d); + assert_eq!( + cursor.resolve(d), + expected, + "ascending mismatch for ({src}, {id}, {d})" + ); + // Repeated same date. + assert_eq!( + cursor.resolve(d), + expected, + "repeat mismatch for ({src}, {id}, {d})" + ); + } + + // Out-of-order fallback + reset. + for &d in &[11_400, 10_000, 10_500, 9_995, 10_250, 11_500] { + assert_eq!( + cursor.resolve(d), + table.resolve(src, id, d), + "out-of-order mismatch for ({src}, {id}, {d})" + ); + } + cursor.reset(); + for d in [9_990, 10_100, 10_300, 10_600, 11_500] { + assert_eq!(cursor.resolve(d), table.resolve(src, id, d)); + } + } + } + + #[test] + fn from_rows_returns_identical_typed_error_across_permutations_of_mixed_invalid_batch() { + let d1 = ymd_to_epoch_days(2020, 1, 2).unwrap(); + let d2 = ymd_to_epoch_days(2022, 6, 8).unwrap(); + + // Mixed-invalid batch: whitespace-only source_id on `eod` + invalid range on `qm` + + // invalid listing_id on `ib` + valid rows + duplicate key on `ceo`. + let mixed_batch = vec![ + row("ceo", "SHOP", d1, None, 10), + row("ceo", "SHOP", d1, None, 10), + row("qm", "FB", d2, Some(d1), 2), + row("ib", "107113386", d1, None, 0), + row("eod", " ", d1, None, 1), + row("eod", "AAPL.US", d1, None, 3), + ]; + + let expected = ProviderMappingError::EmptySourceId { + source: "eod".to_string(), + }; + + let forward_err = ProviderMappingTable::from_rows(mixed_batch.clone()).unwrap_err(); + let mut reversed = mixed_batch.clone(); + reversed.reverse(); + let reversed_err = ProviderMappingTable::from_rows(reversed).unwrap_err(); + assert_eq!(forward_err, expected); + assert_eq!(reversed_err, forward_err); + + let mut rng = TestRng::new(0xBAD0_C0DE_0001_0002); + for _ in 0..8 { + let mut shuffled = mixed_batch.clone(); + rng.shuffle(&mut shuffled); + assert_eq!( + ProviderMappingTable::from_rows(shuffled).unwrap_err(), + expected + ); + } + + // Same-variant tie-breaking must also be order-independent. + let same_variant_cases: Vec<(Vec, ProviderMappingError)> = vec![ + ( + vec![ + row("qm", " ", d1, None, 1), + row("eod", "\t", d1, None, 2), + row("ib", "", d1, None, 3), + ], + ProviderMappingError::EmptySourceId { + source: "eod".to_string(), + }, + ), + ( + vec![ + row("qm", "Z", d1, None, 0), + row("eod", "A", d1, None, -1), + row("eod", "A", d1, None, -5), + ], + ProviderMappingError::InvalidListingId { + source: "eod".to_string(), + source_id: "A".to_string(), + listing_id: -5, + }, + ), + ( + vec![ + row("qm", "B", d2, Some(d1), 2), + row("eod", "A", d2, Some(d1 + 1), 1), + row("eod", "A", d2, Some(d1), 3), + ], + ProviderMappingError::InvalidRange { + source: "eod".to_string(), + source_id: "A".to_string(), + valid_from: d2, + valid_to: d1, + }, + ), + ( + vec![ + row("qm", "B", d2, Some(d1), 2), + row(" ", "A", d1, None, 1), + row("eod", " ", d1, None, 3), + ], + ProviderMappingError::EmptySource, + ), + ( + vec![ + row("a", "DUP", d1, None, 1), + row("a", "DUP", d1, None, 2), + row("z", "BAD", d2, Some(d1), 3), + ], + ProviderMappingError::InvalidRange { + source: "z".to_string(), + source_id: "BAD".to_string(), + valid_from: d2, + valid_to: d1, + }, + ), + ]; + + for (batch, expected_err) in same_variant_cases { + let mut rev = batch.clone(); + rev.reverse(); + assert_eq!( + ProviderMappingTable::from_rows(batch).unwrap_err(), + expected_err + ); + assert_eq!( + ProviderMappingTable::from_rows(rev).unwrap_err(), + expected_err + ); + } + } +} diff --git a/tools/curate-etl/src/shorts.rs b/tools/curate-etl/src/shorts.rs new file mode 100644 index 00000000..1430d032 --- /dev/null +++ b/tools/curate-etl/src/shorts.rs @@ -0,0 +1,987 @@ +//! Pure, in-memory `shorts` builder (`ceoShorts` → `+4` Canadian TSX business-day `17:00 ET` +//! `known_at`). +//! +//! Produces sorted, unique per-`(key, report_date)` rows matching `shorts/part.parquet` in +//! `design/DATA-CONTRACTS.md` (`listing_id, report_date, known_at, shares_short, net_change, +//! pct_float, source`). +//! +//! Also exposes reusable `std`-only Canadian TSX business-day calendar (`2008–2030`) and +//! `America/Toronto` ET→UTC DST conversion helpers ([`is_canadian_business_day`], +//! [`add_canadian_business_days`], [`et_to_utc_micros`], [`epoch_days_to_ymd`]) for downstream +//! builders (e.g., `events` with `16:05 ET` lag). + +use std::error::Error; +use std::fmt; +use std::sync::OnceLock; + +use crate::split::ymd_to_epoch_days; + +/// Canonical provenance label written to [`ShortRow::source`]. +pub const SHORTS_SOURCE_CEO: &str = "ceo_shorts"; + +/// Locked CIRO dissemination lag in Canadian TSX business days (`design/DATA-CONTRACTS.md` §1). +pub const SHORTS_LAG_BUSINESS_DAYS: u32 = 4; + +/// Locked CIRO dissemination wall-clock hour in `America/Toronto` (`17:00 ET`). +pub const SHORTS_DISSEMINATION_HOUR_ET: u8 = 17; + +/// Locked CIRO dissemination wall-clock minute in `America/Toronto` (`17:00 ET`). +pub const SHORTS_DISSEMINATION_MINUTE_ET: u8 = 0; + +/// First Gregorian year covered by the built-in TSX holiday & DST calendar (Family Day joined TSX +/// in 2008; North American 2nd-Sun-Mar / 1st-Sun-Nov DST rules took effect in 2007). +pub const MIN_SUPPORTED_YEAR: i32 = 2008; + +/// Last Gregorian year covered by the built-in TSX holiday & DST calendar (strictly covers +/// `2017-01-01..=2027-12-31` plus year-end `+4` business-day rollovers). +pub const MAX_SUPPORTED_YEAR: i32 = 2030; + +/// Epoch day for `2008-01-01` (inclusive lower bound of the supported calendar range). +pub const MIN_SUPPORTED_DATE: i32 = 13_879; + +/// Epoch day for `2030-12-31` (inclusive upper bound of the supported calendar range). +pub const MAX_SUPPORTED_DATE: i32 = 22_279; + +const SUPPORTED_DAY_COUNT: usize = (MAX_SUPPORTED_DATE - MIN_SUPPORTED_DATE + 1) as usize; +const SUPPORTED_YEAR_COUNT: usize = (MAX_SUPPORTED_YEAR - MIN_SUPPORTED_YEAR + 1) as usize; + +/// Typed errors returned by the Canadian calendar, ET→UTC converter, and [`build_shorts`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ShortsError { + /// A date (or a stepped business day) fell outside `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]`. + DateOutOfRange { + epoch_day: i32, + min_supported: i32, + max_supported: i32, + }, + /// Wall-clock `(hour, minute, second)` components were out of range (`0..=23`, `0..=59`, `0..=59`). + InvalidLocalTime { hour: u8, minute: u8, second: u8 }, + /// Local wall-clock time fell in the spring-forward DST gap (`02:00:00..=02:59:59` ET on the + /// 2nd Sunday of March). + NonexistentLocalTime { + epoch_day: i32, + hour: u8, + minute: u8, + second: u8, + }, + /// Local wall-clock time fell in the fall-back DST overlap (`01:00:00..=01:59:59` ET on the + /// 1st Sunday of November). + AmbiguousLocalTime { + epoch_day: i32, + hour: u8, + minute: u8, + second: u8, + }, +} + +impl fmt::Display for ShortsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + Self::DateOutOfRange { + epoch_day, + min_supported, + max_supported, + } => write!( + f, + "epoch day {epoch_day} is outside supported calendar range [{min_supported}, {max_supported}] ({MIN_SUPPORTED_YEAR}-01-01..={MAX_SUPPORTED_YEAR}-12-31)" + ), + Self::InvalidLocalTime { + hour, + minute, + second, + } => write!( + f, + "invalid local time {hour:02}:{minute:02}:{second:02} (expected 00:00:00..=23:59:59)" + ), + Self::NonexistentLocalTime { + epoch_day, + hour, + minute, + second, + } => { + let (y, m, d) = epoch_days_to_ymd(epoch_day); + write!( + f, + "nonexistent America/Toronto local time {y:04}-{m:02}-{d:02} {hour:02}:{minute:02}:{second:02} (spring-forward DST gap)" + ) + } + Self::AmbiguousLocalTime { + epoch_day, + hour, + minute, + second, + } => { + let (y, m, d) = epoch_days_to_ymd(epoch_day); + write!( + f, + "ambiguous America/Toronto local time {y:04}-{m:02}-{d:02} {hour:02}:{minute:02}:{second:02} (fall-back DST overlap)" + ) + } + } + } +} + +impl Error for ShortsError {} + +/// Converts signed days since `1970-01-01` (UTC Gregorian) back to `(year, month, day)`. +/// +/// Exact inverse of [`crate::ymd_to_epoch_days`] (Howard Hinnant's `civil_from_days`). +#[inline] +pub fn epoch_days_to_ymd(epoch_day: i32) -> (i32, u32, u32) { + let z = i64::from(epoch_day) + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; // [0, 146096] + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399] + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365] + let mp = (5 * doy + 2) / 153; // [0, 11] + let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31] + let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12] + let year = y + i64::from(m <= 2); + (year as i32, m as u32, d as u32) +} + +/// ISO-8601 weekday for an epoch day: `1 = Monday`, ..., `6 = Saturday`, `7 = Sunday`. +#[inline] +fn iso_weekday(epoch_day: i32) -> u8 { + // 1970-01-01 (epoch_day == 0) was Thursday (ISO 4). + ((i64::from(epoch_day) + 3).rem_euclid(7) + 1) as u8 +} + +/// Computes the epoch day of the `nth` occurrence (`1`-indexed) of `target_iso_weekday` +/// (`1 = Mon ..= 7 = Sun`) in `(year, month)`. +fn nth_weekday_of_month(year: i32, month: u32, target_iso_weekday: u8, nth: u32) -> i32 { + let first = ymd_to_epoch_days(year, month, 1).expect("valid first of month"); + let first_wd = iso_weekday(first); + let delta = (i32::from(target_iso_weekday) - i32::from(first_wd)).rem_euclid(7); + first + delta + (nth as i32 - 1) * 7 +} + +/// Anonymous Gregorian algorithm (Meeus/Jones/Butcher) for Easter Sunday. +fn easter_sunday_epoch_day(year: i32) -> i32 { + let a = year % 19; + let b = year / 100; + let c = year % 100; + let d = b / 4; + let e = b % 4; + let f = (b + 8) / 25; + let g = (b - f + 1) / 3; + let h = (19 * a + b - d - g + 15) % 30; + let i = c / 4; + let k = c % 4; + let l = (32 + 2 * e + 2 * i - h - k) % 7; + let m = (a + 11 * h + 22 * l) / 451; + let month = (h + l - 7 * m + 114) / 31; + let day = ((h + l - 7 * m + 114) % 31) + 1; + ymd_to_epoch_days(year, month as u32, day as u32).expect("valid Easter Sunday") +} + +/// Observes a fixed-date TSX holiday (New Year's Day / Canada Day): Saturday → Monday (`+2`), +/// Sunday → Monday (`+1`), weekday → same day. +fn observed_fixed_holiday(epoch_day: i32) -> i32 { + match iso_weekday(epoch_day) { + 6 => epoch_day + 2, + 7 => epoch_day + 1, + _ => epoch_day, + } +} + +struct CalendarTable { + /// `true` iff `MIN_SUPPORTED_DATE + idx` is a Canadian TSX business day. + is_business: Vec, + /// Per-year `(dst_start_epoch_day, dst_end_epoch_day)` for `MIN_SUPPORTED_YEAR..=MAX_SUPPORTED_YEAR`. + dst_bounds: [(i32, i32); SUPPORTED_YEAR_COUNT], +} + +impl CalendarTable { + fn build() -> Self { + let mut is_business = vec![true; SUPPORTED_DAY_COUNT]; + for (idx, flag) in is_business.iter_mut().enumerate() { + let day = MIN_SUPPORTED_DATE + idx as i32; + if iso_weekday(day) >= 6 { + *flag = false; + } + } + + let mut dst_bounds = [(0i32, 0i32); SUPPORTED_YEAR_COUNT]; + + for year in MIN_SUPPORTED_YEAR..=MAX_SUPPORTED_YEAR { + let mut mark_holiday = |day: i32| { + if (MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&day) { + is_business[(day - MIN_SUPPORTED_DATE) as usize] = false; + } + }; + + // 1. New Year's Day (Jan 1; Sat -> Mon Jan 3, Sun -> Mon Jan 2). + let jan1 = ymd_to_epoch_days(year, 1, 1).expect("valid Jan 1"); + mark_holiday(observed_fixed_holiday(jan1)); + + // 2. Family Day (3rd Monday of February, observed by TSX since 2008). + mark_holiday(nth_weekday_of_month(year, 2, 1, 3)); + + // 3. Good Friday (Easter Sunday - 2 days). + mark_holiday(easter_sunday_epoch_day(year) - 2); + + // 4. Victoria Day (Monday strictly before May 25). + let may24 = ymd_to_epoch_days(year, 5, 24).expect("valid May 24"); + let victoria = may24 - i32::from(iso_weekday(may24) - 1); + mark_holiday(victoria); + + // 5. Canada Day (Jul 1; Sat -> Mon Jul 3, Sun -> Mon Jul 2). + let jul1 = ymd_to_epoch_days(year, 7, 1).expect("valid Jul 1"); + mark_holiday(observed_fixed_holiday(jul1)); + + // 6. Civic Holiday (1st Monday of August). + mark_holiday(nth_weekday_of_month(year, 8, 1, 1)); + + // 7. Labour Day (1st Monday of September). + mark_holiday(nth_weekday_of_month(year, 9, 1, 1)); + + // 8. Thanksgiving (2nd Monday of October). + mark_holiday(nth_weekday_of_month(year, 10, 1, 2)); + + // 9. Christmas Day & Boxing Day pair (Dec 25/26 with TSX weekend observance): + // Mon–Thu -> Dec 25 & Dec 26 + // Fri -> Dec 25 (Fri) & Dec 28 (Mon) + // Sat -> Dec 27 (Mon) & Dec 28 (Tue) + // Sun -> Dec 26 (Mon) & Dec 27 (Tue) + let dec25 = ymd_to_epoch_days(year, 12, 25).expect("valid Dec 25"); + let (xmas_obs, boxing_obs) = match iso_weekday(dec25) { + 1..=4 => (dec25, dec25 + 1), + 5 => (dec25, dec25 + 3), + 6 => (dec25 + 2, dec25 + 3), + 7 => (dec25 + 1, dec25 + 2), + _ => unreachable!("iso_weekday is always in 1..=7"), + }; + mark_holiday(xmas_obs); + mark_holiday(boxing_obs); + + // America/Toronto DST: 2nd Sunday of March -> 1st Sunday of November. + let dst_start = nth_weekday_of_month(year, 3, 7, 2); + let dst_end = nth_weekday_of_month(year, 11, 7, 1); + dst_bounds[(year - MIN_SUPPORTED_YEAR) as usize] = (dst_start, dst_end); + } + + Self { + is_business, + dst_bounds, + } + } +} + +fn calendar_table() -> &'static CalendarTable { + static TABLE: OnceLock = OnceLock::new(); + TABLE.get_or_init(CalendarTable::build) +} + +#[inline] +fn check_supported_date(epoch_day: i32) -> Result<(), ShortsError> { + if (MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE).contains(&epoch_day) { + Ok(()) + } else { + Err(ShortsError::DateOutOfRange { + epoch_day, + min_supported: MIN_SUPPORTED_DATE, + max_supported: MAX_SUPPORTED_DATE, + }) + } +} + +/// Returns `Ok(true)` iff `epoch_day` is a Canadian TSX business day (weekday and not a TSX +/// holiday) within `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]` (`2008-01-01..=2030-12-31`). +/// +/// Dates outside the supported range return [`ShortsError::DateOutOfRange`]. +#[inline] +pub fn is_canadian_business_day(epoch_day: i32) -> Result { + check_supported_date(epoch_day)?; + let table = calendar_table(); + Ok(table.is_business[(epoch_day - MIN_SUPPORTED_DATE) as usize]) +} + +/// Advances `epoch_day` strictly forward by `n` Canadian TSX business days. +/// +/// - When `n == 0`, returns `Ok(epoch_day)` if `epoch_day` is within the supported range. +/// - When `epoch_day` is itself a weekend or holiday, counts strictly forward from `epoch_day` so +/// the returned date is the `n`-th business day strictly after `epoch_day`. +/// - Returns [`ShortsError::DateOutOfRange`] if `epoch_day` or any stepped day leaves +/// `[MIN_SUPPORTED_DATE, MAX_SUPPORTED_DATE]`. +#[inline] +pub fn add_canadian_business_days(epoch_day: i32, n: u32) -> Result { + check_supported_date(epoch_day)?; + if n == 0 { + return Ok(epoch_day); + } + + let table = calendar_table(); + let mut cur = epoch_day; + let mut remaining = n; + while remaining > 0 { + if cur >= MAX_SUPPORTED_DATE { + return Err(ShortsError::DateOutOfRange { + epoch_day: cur.saturating_add(1), + min_supported: MIN_SUPPORTED_DATE, + max_supported: MAX_SUPPORTED_DATE, + }); + } + cur += 1; + if table.is_business[(cur - MIN_SUPPORTED_DATE) as usize] { + remaining -= 1; + } + } + Ok(cur) +} + +/// Converts an `America/Toronto` local date and wall-clock time `(hour, minute, second)` to UTC +/// microseconds since `1970-01-01T00:00:00Z`. +/// +/// Applies North American post-2007 DST rules (2nd Sunday of March 02:00 → 1st Sunday of November +/// 02:00 = EDT `UTC-4`, otherwise EST `UTC-5`) over `2008-01-01..=2030-12-31`. +/// +/// Rejects: +/// - out-of-range dates ([`ShortsError::DateOutOfRange`]), +/// - invalid clock components ([`ShortsError::InvalidLocalTime`]), +/// - spring-forward nonexistent times `02:00:00..=02:59:59` ([`ShortsError::NonexistentLocalTime`]), +/// - fall-back ambiguous times `01:00:00..=01:59:59` ([`ShortsError::AmbiguousLocalTime`]). +#[inline] +pub fn et_to_utc_micros( + epoch_day: i32, + hour: u8, + minute: u8, + second: u8, +) -> Result { + if hour > 23 || minute > 59 || second > 59 { + return Err(ShortsError::InvalidLocalTime { + hour, + minute, + second, + }); + } + check_supported_date(epoch_day)?; + + let (year, _, _) = epoch_days_to_ymd(epoch_day); + let (dst_start, dst_end) = calendar_table().dst_bounds[(year - MIN_SUPPORTED_YEAR) as usize]; + + let is_edt = if epoch_day == dst_start { + if hour == 2 { + return Err(ShortsError::NonexistentLocalTime { + epoch_day, + hour, + minute, + second, + }); + } + hour >= 3 + } else if epoch_day == dst_end { + if hour == 1 { + return Err(ShortsError::AmbiguousLocalTime { + epoch_day, + hour, + minute, + second, + }); + } + hour == 0 + } else { + epoch_day > dst_start && epoch_day < dst_end + }; + + let offset_hours: i64 = if is_edt { 4 } else { 5 }; + let local_secs = i64::from(hour) * 3_600 + i64::from(minute) * 60 + i64::from(second); + let utc_secs = i64::from(epoch_day) * 86_400 + local_secs + offset_hours * 3_600; + Ok(utc_secs * 1_000_000) +} + +/// A single raw `ceoShorts` short-interest report row. +#[derive(Debug, Clone, PartialEq)] +pub struct CeoShortReport { + pub key: K, + /// Report period date (15th or month-end) as days since `1970-01-01` (UTC Gregorian). + pub report_date: i32, + /// Reported short share count (must be finite and `>= 0.0`). + pub shares_short: f64, + /// Optional net change vs. prior report (non-finite values are sanitized to `None`). + pub net_change: Option, + /// Optional percent of float short passed through from caller (non-finite → `None`). + pub pct_float: Option, +} + +/// A single curated `shorts` row, sorted and unique by `(key, report_date)`. +#[derive(Debug, Clone, PartialEq)] +pub struct ShortRow { + pub key: K, + pub report_date: i32, + /// Point-in-time dissemination date (`report_date + 4` Canadian TSX business days). + pub known_at_date: i32, + /// Point-in-time UTC microseconds (`17:00:00 America/Toronto` on `known_at_date`). + pub known_at_utc_micros: i64, + pub shares_short: f64, + pub net_change: Option, + pub pct_float: Option, + pub source: &'static str, +} + +/// Summary accounting counters produced alongside [`ShortsBuild::rows`]. +/// +/// Conservation invariant: +/// `rows_in == rows_out + dropped_invalid_shares_short + duplicate_collapsed + duplicate_conflict_dropped` +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ShortsStats { + pub rows_in: usize, + pub rows_out: usize, + pub keys_out: usize, + pub dropped_invalid_shares_short: usize, + pub nulled_invalid_net_change: usize, + pub nulled_invalid_pct_float: usize, + pub duplicate_collapsed: usize, + pub duplicate_conflict_dropped: usize, +} + +/// Output of [`build_shorts`]: sorted, unique point-in-time `shorts` rows and exact stats. +#[derive(Debug, Clone, PartialEq)] +pub struct ShortsBuild { + pub rows: Vec>, + pub stats: ShortsStats, +} + +#[inline] +fn normalize_zero(v: f64) -> f64 { + if v == 0.0 { + 0.0 + } else { + v + } +} + +struct NormalizedShort { + key: K, + report_date: i32, + known_at_date: i32, + shares_short: f64, + net_change: Option, + pct_float: Option, +} + +impl NormalizedShort { + #[inline] + fn values_bit_eq(&self, other: &Self) -> bool { + self.shares_short.to_bits() == other.shares_short.to_bits() + && self.net_change.map(f64::to_bits) == other.net_change.map(f64::to_bits) + && self.pct_float.map(f64::to_bits) == other.pct_float.map(f64::to_bits) + } +} + +/// Builds sorted, unique point-in-time `shorts` rows from raw `ceoShorts` report rows. +/// +/// - Validates `report_date + 4` Canadian TSX business days on every input row first so any +/// out-of-range date returns [`ShortsError::DateOutOfRange`] deterministically regardless of row +/// order or bad numeric fields. +/// - Drops non-finite or negative `shares_short` (`dropped_invalid_shares_short`) without aborting +/// and without incrementing optional-field null counters. +/// - Sanitizes non-finite `net_change` / `pct_float` to `None` (`nulled_invalid_net_change` / +/// `nulled_invalid_pct_float`) and normalizes `-0.0` to `0.0` before deduplication. +/// - Collapses bitwise-identical duplicates on `(key, report_date)` (`duplicate_collapsed`) and +/// drops conflicting duplicate groups entirely (`duplicate_conflict_dropped`). +/// - Stamps `known_at_utc_micros = 17:00 America/Toronto` on `known_at_date` and +/// `source = "ceo_shorts"`. +/// - Any permutation of `rows` yields bitwise-identical `rows` and `stats`. +pub fn build_shorts(rows: I) -> Result, ShortsError> +where + K: Ord + Clone, + I: IntoIterator>, +{ + let iter = rows.into_iter(); + let (lower, _) = iter.size_hint(); + let mut stats = ShortsStats::default(); + let mut valid: Vec> = Vec::with_capacity(lower); + + for row in iter { + stats.rows_in += 1; + + let known_at_date = add_canadian_business_days(row.report_date, SHORTS_LAG_BUSINESS_DAYS)?; + + if !row.shares_short.is_finite() || row.shares_short < 0.0 { + stats.dropped_invalid_shares_short += 1; + continue; + } + let shares_short = normalize_zero(row.shares_short); + + let net_change = match row.net_change { + Some(v) if v.is_finite() => Some(normalize_zero(v)), + Some(_) => { + stats.nulled_invalid_net_change += 1; + None + } + None => None, + }; + + let pct_float = match row.pct_float { + Some(v) if v.is_finite() => Some(normalize_zero(v)), + Some(_) => { + stats.nulled_invalid_pct_float += 1; + None + } + None => None, + }; + + valid.push(NormalizedShort { + key: row.key, + report_date: row.report_date, + known_at_date, + shares_short, + net_change, + pct_float, + }); + } + + valid.sort_unstable_by(|a, b| { + a.key + .cmp(&b.key) + .then_with(|| a.report_date.cmp(&b.report_date)) + }); + + let mut out: Vec> = Vec::with_capacity(valid.len()); + let len = valid.len(); + let mut read_idx = 0usize; + + while read_idx < len { + let mut group_end = read_idx + 1; + while group_end < len + && valid[group_end].key == valid[read_idx].key + && valid[group_end].report_date == valid[read_idx].report_date + { + group_end += 1; + } + + let group_len = group_end - read_idx; + let first = &valid[read_idx]; + let all_identical = valid[read_idx + 1..group_end] + .iter() + .all(|other| first.values_bit_eq(other)); + + if all_identical { + stats.duplicate_collapsed += group_len - 1; + let known_at_utc_micros = et_to_utc_micros( + first.known_at_date, + SHORTS_DISSEMINATION_HOUR_ET, + SHORTS_DISSEMINATION_MINUTE_ET, + 0, + )?; + if out.last().is_none_or(|prev| prev.key != first.key) { + stats.keys_out += 1; + } + out.push(ShortRow { + key: first.key.clone(), + report_date: first.report_date, + known_at_date: first.known_at_date, + known_at_utc_micros, + shares_short: first.shares_short, + net_change: first.net_change, + pct_float: first.pct_float, + source: SHORTS_SOURCE_CEO, + }); + } else { + stats.duplicate_conflict_dropped += group_len; + } + + read_idx = group_end; + } + + stats.rows_out = out.len(); + + Ok(ShortsBuild { rows: out, stats }) +} + +#[cfg(test)] +mod tests { + use super::*; + + 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 report( + key: &str, + report_date: i32, + shares_short: f64, + net_change: Option, + pct_float: Option, + ) -> CeoShortReport { + CeoShortReport { + key: key.to_string(), + report_date, + shares_short, + net_change, + pct_float, + } + } + + fn assert_invariants(build: &ShortsBuild) { + let s = &build.stats; + assert_eq!( + s.rows_in, + s.rows_out + + s.dropped_invalid_shares_short + + s.duplicate_collapsed + + s.duplicate_conflict_dropped, + "accounting invariant failed: {s:?}" + ); + assert_eq!(s.rows_out, build.rows.len()); + for pair in build.rows.windows(2) { + assert!( + (&pair[0].key, pair[0].report_date) < (&pair[1].key, pair[1].report_date), + "rows must be strictly sorted by (key, report_date)" + ); + } + for row in &build.rows { + assert!( + row.known_at_date > row.report_date, + "look-ahead violation: known_at_date {} <= report_date {}", + row.known_at_date, + row.report_date + ); + assert_eq!(row.source, SHORTS_SOURCE_CEO); + } + } + + #[test] + fn supported_date_bounds_match_calendar_constants() { + assert_eq!(day(MIN_SUPPORTED_YEAR, 1, 1), MIN_SUPPORTED_DATE); + assert_eq!(day(MAX_SUPPORTED_YEAR, 12, 31), MAX_SUPPORTED_DATE); + assert_eq!(epoch_days_to_ymd(MIN_SUPPORTED_DATE), (2008, 1, 1)); + assert_eq!(epoch_days_to_ymd(MAX_SUPPORTED_DATE), (2030, 12, 31)); + assert_eq!(epoch_days_to_ymd(0), (1970, 1, 1)); + assert_eq!(epoch_days_to_ymd(-1), (1969, 12, 31)); + } + + #[test] + fn epoch_days_to_ymd_round_trips_every_supported_day() { + for d in MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE { + let (y, m, dom) = epoch_days_to_ymd(d); + assert_eq!(ymd_to_epoch_days(y, m, dom).unwrap(), d); + } + } + + #[test] + fn pinned_tsx_holidays_and_observances_are_non_business_days() { + let holidays = [ + // Pinned acceptance criteria dates + (2024, 3, 29), // Good Friday + (2023, 7, 3), // Canada Day observed (Jul 1 Sat) + (2022, 12, 26), // Christmas observed (Dec 25 Sun) + (2022, 12, 27), // Boxing Day observed (Dec 25 Sun) + (2021, 2, 15), // Family Day + (2024, 5, 20), // Victoria Day + (2024, 8, 5), // Civic Holiday + (2024, 10, 14), // Thanksgiving + // New Year's Day weekday + Sat/Sun observances + (2024, 1, 1), // Mon + (2022, 1, 3), // Jan 1 Sat -> Mon Jan 3 + (2023, 1, 2), // Jan 1 Sun -> Mon Jan 2 + // Christmas/Boxing Day Fri and Sat cases + (2020, 12, 25), // Fri + (2020, 12, 28), // Dec 26 Sat -> Mon Dec 28 + (2021, 12, 27), // Dec 25 Sat -> Mon Dec 27 + (2021, 12, 28), // Dec 26 Sun -> Tue Dec 28 + // Canada Day Sun observance + (2018, 7, 2), // Jul 1 Sun -> Mon Jul 2 + // Labour Day + (2024, 9, 2), // 1st Mon of Sep + // Weekend + (2024, 6, 15), // Saturday + (2024, 6, 16), // Sunday + ]; + + for (y, m, d) in holidays { + assert_eq!( + is_canadian_business_day(day(y, m, d)), + Ok(false), + "expected {y:04}-{m:02}-{d:02} to be a non-business day" + ); + } + + // Ordinary weekdays + federal holidays where TSX remains open + let business_days = [ + (2024, 6, 12), // Ordinary Wednesday + (2023, 10, 2), // National Day for Truth & Reconciliation observed (TSX open) + (2024, 9, 30), // National Day for Truth & Reconciliation (TSX open) + (2024, 11, 11), // Remembrance Day (TSX open) + (2021, 12, 24), // Christmas Eve (Fri before Sat Christmas -> TSX open) + (2021, 12, 31), // New Year's Eve (Fri before Sat New Year's -> TSX open) + ]; + + for (y, m, d) in business_days { + assert_eq!( + is_canadian_business_day(day(y, m, d)), + Ok(true), + "expected {y:04}-{m:02}-{d:02} to be a TSX business day" + ); + } + } + + #[test] + fn add_canadian_business_days_matches_pinned_plus_four_fixtures() { + assert_eq!( + add_canadian_business_days(day(2024, 3, 15), 4), + Ok(day(2024, 3, 21)) + ); + assert_eq!( + add_canadian_business_days(day(2024, 3, 28), 4), + Ok(day(2024, 4, 4)) + ); + assert_eq!( + add_canadian_business_days(day(2023, 12, 29), 4), + Ok(day(2024, 1, 5)) + ); + assert_eq!( + add_canadian_business_days(day(2023, 9, 30), 4), + Ok(day(2023, 10, 5)) + ); + // n == 0 returns input unchanged when in range (even on a weekend) + assert_eq!( + add_canadian_business_days(day(2023, 9, 30), 0), + Ok(day(2023, 9, 30)) + ); + // Year-end 2027 rollover into Jan 2028 works cleanly + assert_eq!( + add_canadian_business_days(day(2027, 12, 31), 4), + Ok(day(2028, 1, 7)) + ); + } + + #[test] + fn out_of_range_dates_return_typed_error_without_panicking() { + for bad in [ + MIN_SUPPORTED_DATE - 1, + MAX_SUPPORTED_DATE + 1, + day(2007, 12, 31), + day(2031, 1, 1), + i32::MIN, + i32::MAX, + ] { + assert!(matches!( + is_canadian_business_day(bad), + Err(ShortsError::DateOutOfRange { epoch_day, .. }) if epoch_day == bad + )); + assert!(matches!( + add_canadian_business_days(bad, 4), + Err(ShortsError::DateOutOfRange { epoch_day, .. }) if epoch_day == bad + )); + assert!(matches!( + et_to_utc_micros(bad, 17, 0, 0), + Err(ShortsError::DateOutOfRange { epoch_day, .. }) if epoch_day == bad + )); + } + + // Stepping past MAX_SUPPORTED_DATE returns DateOutOfRange + assert!(matches!( + add_canadian_business_days(day(2030, 12, 30), 4), + Err(ShortsError::DateOutOfRange { .. }) + )); + } + + #[test] + fn et_to_utc_micros_handles_edt_est_dst_boundaries_and_errors() { + // Summer (EDT UTC-4) -> 17:00 ET == 21:00 UTC + assert_eq!( + et_to_utc_micros(day(2024, 7, 15), 17, 0, 0), + Ok(utc_micros(2024, 7, 15, 21, 0, 0)) + ); + // Winter (EST UTC-5) -> 17:00 ET == 22:00 UTC + assert_eq!( + et_to_utc_micros(day(2024, 1, 15), 17, 0, 0), + Ok(utc_micros(2024, 1, 15, 22, 0, 0)) + ); + + // Both sides of March 2024 spring-forward (2nd Sun = Mar 10) + assert_eq!( + et_to_utc_micros(day(2024, 3, 9), 17, 0, 0), + Ok(utc_micros(2024, 3, 9, 22, 0, 0)) + ); + assert_eq!( + et_to_utc_micros(day(2024, 3, 10), 1, 59, 59), + Ok(utc_micros(2024, 3, 10, 6, 59, 59)) + ); + assert_eq!( + et_to_utc_micros(day(2024, 3, 10), 3, 0, 0), + Ok(utc_micros(2024, 3, 10, 7, 0, 0)) + ); + assert_eq!( + et_to_utc_micros(day(2024, 3, 10), 17, 0, 0), + Ok(utc_micros(2024, 3, 10, 21, 0, 0)) + ); + + // Both sides of November 2024 fall-back (1st Sun = Nov 3) + assert_eq!( + et_to_utc_micros(day(2024, 11, 2), 17, 0, 0), + Ok(utc_micros(2024, 11, 2, 21, 0, 0)) + ); + assert_eq!( + et_to_utc_micros(day(2024, 11, 3), 0, 30, 0), + Ok(utc_micros(2024, 11, 3, 4, 30, 0)) + ); + assert_eq!( + et_to_utc_micros(day(2024, 11, 3), 2, 0, 0), + Ok(utc_micros(2024, 11, 3, 7, 0, 0)) + ); + assert_eq!( + et_to_utc_micros(day(2024, 11, 3), 17, 0, 0), + Ok(utc_micros(2024, 11, 3, 22, 0, 0)) + ); + + // Reuse check for events 16:05 ET lag + assert_eq!( + et_to_utc_micros(day(2024, 7, 15), 16, 5, 0), + Ok(utc_micros(2024, 7, 15, 20, 5, 0)) + ); + assert_eq!( + et_to_utc_micros(day(2024, 1, 15), 16, 5, 0), + Ok(utc_micros(2024, 1, 15, 21, 5, 0)) + ); + + // Spring-forward nonexistent local time (2026-03-08 02:30) + assert_eq!( + et_to_utc_micros(day(2026, 3, 8), 2, 30, 0), + Err(ShortsError::NonexistentLocalTime { + epoch_day: day(2026, 3, 8), + hour: 2, + minute: 30, + second: 0, + }) + ); + + // Fall-back ambiguous local time (2026-11-01 01:30) + assert_eq!( + et_to_utc_micros(day(2026, 11, 1), 1, 30, 0), + Err(ShortsError::AmbiguousLocalTime { + epoch_day: day(2026, 11, 1), + hour: 1, + minute: 30, + second: 0, + }) + ); + + // Invalid clock components + assert_eq!( + et_to_utc_micros(day(2024, 6, 12), 24, 0, 0), + Err(ShortsError::InvalidLocalTime { + hour: 24, + minute: 0, + second: 0, + }) + ); + assert_eq!( + et_to_utc_micros(day(2024, 6, 12), 12, 60, 0), + Err(ShortsError::InvalidLocalTime { + hour: 12, + minute: 60, + second: 0, + }) + ); + assert_eq!( + et_to_utc_micros(day(2024, 6, 12), 12, 0, 60), + Err(ShortsError::InvalidLocalTime { + hour: 12, + minute: 0, + second: 60, + }) + ); + } + + #[test] + fn build_shorts_handles_empty_input() { + let built = build_shorts::(Vec::new()).unwrap(); + assert!(built.rows.is_empty()); + assert_eq!(built.stats, ShortsStats::default()); + assert_invariants(&built); + } + + #[test] + fn build_shorts_filters_sanitizes_dedups_and_preserves_accounting() { + let d1 = day(2024, 3, 15); + let d2 = day(2024, 3, 28); + let d3 = day(2023, 12, 29); + + let input = vec![ + // Valid row + bitwise-identical duplicate with -0.0 normalization + report("AAA.TO", d1, -0.0, Some(-0.0), Some(-0.0)), + report("AAA.TO", d1, 0.0, Some(0.0), Some(0.0)), + // Invalid shares_short with NaN optional fields: dropped before optional-field nulling + report("AAA.TO", d2, -10.0, Some(f64::NAN), Some(f64::INFINITY)), + report("AAA.TO", d2, f64::NAN, Some(1.0), None), + report("AAA.TO", d2, f64::INFINITY, None, Some(f64::NEG_INFINITY)), + // Valid row with non-finite optional fields -> nulled and counted + report( + "BBB.TO", + d2, + 125_000.0, + Some(f64::NAN), + Some(f64::INFINITY), + ), + // Conflicting duplicate group -> dropped entirely + report("CCC.TO", d3, 50_000.0, Some(1_000.0), Some(1.5)), + report("CCC.TO", d3, 50_001.0, Some(1_000.0), Some(1.5)), + ]; + + let built = build_shorts(input).unwrap(); + assert_invariants(&built); + + assert_eq!(built.stats.rows_in, 8); + assert_eq!(built.stats.rows_out, 2); + assert_eq!(built.stats.keys_out, 2); + assert_eq!(built.stats.dropped_invalid_shares_short, 3); + assert_eq!(built.stats.nulled_invalid_net_change, 1); + assert_eq!(built.stats.nulled_invalid_pct_float, 1); + assert_eq!(built.stats.duplicate_collapsed, 1); + assert_eq!(built.stats.duplicate_conflict_dropped, 2); + + assert_eq!(built.rows[0].key, "AAA.TO"); + assert_eq!(built.rows[0].report_date, d1); + assert_eq!(built.rows[0].known_at_date, day(2024, 3, 21)); + assert_eq!( + built.rows[0].known_at_utc_micros, + utc_micros(2024, 3, 21, 21, 0, 0) + ); + assert_eq!(built.rows[0].shares_short.to_bits(), 0.0_f64.to_bits()); + assert_eq!( + built.rows[0].net_change.map(f64::to_bits), + Some(0.0_f64.to_bits()) + ); + assert_eq!( + built.rows[0].pct_float.map(f64::to_bits), + Some(0.0_f64.to_bits()) + ); + + assert_eq!(built.rows[1].key, "BBB.TO"); + assert_eq!(built.rows[1].report_date, d2); + assert_eq!(built.rows[1].known_at_date, day(2024, 4, 4)); + assert_eq!( + built.rows[1].known_at_utc_micros, + utc_micros(2024, 4, 4, 21, 0, 0) + ); + assert_eq!(built.rows[1].shares_short, 125_000.0); + assert_eq!(built.rows[1].net_change, None); + assert_eq!(built.rows[1].pct_float, None); + } + + #[test] + fn build_shorts_rejects_out_of_range_date_even_on_invalid_shares_row() { + let err = build_shorts(vec![report( + "AAA.TO", + day(2007, 12, 31), + -5.0, + None, + None, + )]) + .unwrap_err(); + assert!(matches!(err, ShortsError::DateOutOfRange { .. })); + } +} diff --git a/tools/curate-etl/tests/cli.rs b/tools/curate-etl/tests/cli.rs index 8cee61fe..21a9d720 100644 --- a/tools/curate-etl/tests/cli.rs +++ b/tools/curate-etl/tests/cli.rs @@ -26,6 +26,8 @@ fn no_args_and_help_print_usage_and_succeed() { assert!(text.contains("Usage:"), "{args:?}: {text}"); assert!(text.contains("bench-split"), "{args:?}: {text}"); assert!(text.contains("bench-corporate-actions"), "{args:?}: {text}"); + assert!(text.contains("bench-fx"), "{args:?}: {text}"); + assert!(text.contains("bench-events"), "{args:?}: {text}"); } } @@ -54,6 +56,14 @@ fn invalid_invocations_exit_nonzero_with_usage_on_stderr() { &["bench-corporate-actions", "0"][..], &["bench-corporate-actions", "-5"][..], &["bench-corporate-actions", "10", "20"][..], + &["bench-fx", "abc"][..], + &["bench-fx", "0"][..], + &["bench-fx", "-5"][..], + &["bench-fx", "10", "20"][..], + &["bench-events", "abc"][..], + &["bench-events", "0"][..], + &["bench-events", "-5"][..], + &["bench-events", "10", "20"][..], &["--unknown"][..], &["export"][..], ] { @@ -126,3 +136,66 @@ fn bench_corporate_actions_small_run_is_headless_deterministic_and_reports_rates assert_eq!(checksum_a, checksum_b); assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); } + +#[test] +fn bench_fx_small_run_is_headless_deterministic_and_reports_rates() { + let a = run(&["bench-fx", "1000"]); + let b = run(&["bench-fx", "1000"]); + 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-fx"), "{text_a}"); + assert!(text_a.contains("rows=1000 "), "{text_a}"); + assert!(text_a.contains("rows_out="), "{text_a}"); + assert!(text_a.contains("rows/s"), "{text_a}"); + assert!(text_a.contains("lookups=1000000 "), "{text_a}"); + assert!(text_a.contains("lookups/s"), "{text_a}"); + assert!(text_a.contains("checksum=0x"), "{text_a}"); + assert!(text_a.contains("stats: eod_invalid="), "{text_a}"); + + let field = |s: &str, prefix: &str| { + s.split_whitespace() + .find(|t| t.starts_with(prefix)) + .map(str::to_owned) + }; + let checksum_a = field(&text_a, "checksum="); + let checksum_b = field(&text_b, "checksum="); + assert!(checksum_a.is_some(), "{text_a}"); + assert_eq!(checksum_a, checksum_b); + assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); +} + +#[test] +fn bench_events_small_run_is_headless_deterministic_and_reports_rates() { + let a = run(&["bench-events", "1000"]); + let b = run(&["bench-events", "1000"]); + 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-events"), "{text_a}"); + assert!(text_a.contains("rows=1000 "), "{text_a}"); + assert!(text_a.contains("rows_out="), "{text_a}"); + assert!(text_a.contains("rows/s"), "{text_a}"); + assert!(text_a.contains("ns/row"), "{text_a}"); + assert!(text_a.contains("checksum=0x"), "{text_a}"); + assert!(text_a.contains("stats: malformed_ts="), "{text_a}"); + + let field = |s: &str, prefix: &str| { + s.split_whitespace() + .find(|t| t.starts_with(prefix)) + .map(str::to_owned) + }; + let checksum_a = field(&text_a, "checksum="); + let checksum_b = field(&text_b, "checksum="); + assert!(checksum_a.is_some(), "{text_a}"); + assert_eq!(checksum_a, checksum_b); + assert_eq!(field(&text_a, "rows_out="), field(&text_b, "rows_out=")); +} diff --git a/tools/curate-etl/tests/events_contract.rs b/tools/curate-etl/tests/events_contract.rs new file mode 100644 index 00000000..b8cd929d --- /dev/null +++ b/tools/curate-etl/tests/events_contract.rs @@ -0,0 +1,922 @@ +//! Contract tests for the public `curate_etl` `events` builder API and CLI binary (T-77 / M1.2g). +//! +//! Uses only the crate's public surface and compiled binary (`CARGO_BIN_EXE_curate-etl`), guarding: +//! - Strict `qmFilings.timefiled` EST/EDT → UTC conversion (including pre-2008 & bad-row skips), +//! - EDGAR & SEDAR+ form-group classification, amendment handling, and periodic-report predicate, +//! - `qmEarnings` linking to same-day `8-K`/`News release` vs. conservative `16:05 ET` fallback, +//! - Strict RFC 8259 JSON payload round-trip, stable key ordering, and `consensusEps` omission, +//! - Deterministic sorting, deduplication, conflict dropping, accounting invariants, and +//! permutation invariance, +//! - `bench-events` reproducibility and CLI argument validation. + +use std::process::Command; + +use curate_etl::bench::run_events_benchmark; +use curate_etl::{ + build_events, classify_form_type, encode_earnings_payload_json, encode_filing_payload_json, + is_periodic_financial_report, normalize_announce_time, parse_filing_timefiled, + partition_year_utc, ymd_to_epoch_days, EventRow, EventsBuild, EventsStats, FilingFormGroup, + FilingTimeError, QmEarning, QmFiling, EARNINGS_FALLBACK_HOUR_ET, EARNINGS_FALLBACK_MINUTE_ET, + EVENT_KIND_EARNINGS, EVENT_KIND_FILING, KNOWN_AT_SOURCE_FILING_TIMESTAMP, + KNOWN_AT_SOURCE_STATUTORY_LAG, MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE, +}; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture 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 +} + +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 shuffle(items: &mut [T], rng: &mut Rng) { + for i in (1..items.len()).rev() { + let j = (rng.next() % (i as u64 + 1)) as usize; + items.swap(i, j); + } +} + +/// Minimal strict `std`-only RFC 8259 JSON value for contract round-trip validation. +#[derive(Debug, PartialEq)] +enum JsonVal { + Null, + Bool(bool), + Num(f64), + Str(String), + Obj(Vec<(String, JsonVal)>), +} + +struct JsonParser<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> JsonParser<'a> { + fn new(src: &'a str) -> Self { + Self { + bytes: src.as_bytes(), + pos: 0, + } + } + + fn peek(&self) -> Option { + self.bytes.get(self.pos).copied() + } + + fn parse_value(&mut self) -> Result { + match self.peek() { + Some(b'{') => self.parse_object(), + Some(b'"') => self.parse_string().map(JsonVal::Str), + Some(b't') => self.expect_lit(b"true", JsonVal::Bool(true)), + Some(b'f') => self.expect_lit(b"false", JsonVal::Bool(false)), + Some(b'n') => self.expect_lit(b"null", JsonVal::Null), + Some(b'-' | b'0'..=b'9') => self.parse_number(), + other => Err(format!("unexpected byte {other:?} at {}", self.pos)), + } + } + + fn expect_lit(&mut self, lit: &[u8], val: JsonVal) -> Result { + if self.bytes[self.pos..].starts_with(lit) { + self.pos += lit.len(); + Ok(val) + } else { + Err(format!("expected {:?} at {}", lit, self.pos)) + } + } + + fn parse_object(&mut self) -> Result { + self.pos += 1; // '{' + let mut fields = Vec::new(); + if self.peek() == Some(b'}') { + self.pos += 1; + return Ok(JsonVal::Obj(fields)); + } + loop { + let key = self.parse_string()?; + if self.peek() != Some(b':') { + return Err(format!("expected ':' at {}", self.pos)); + } + self.pos += 1; + let val = self.parse_value()?; + fields.push((key, val)); + match self.peek() { + Some(b',') => self.pos += 1, + Some(b'}') => { + self.pos += 1; + return Ok(JsonVal::Obj(fields)); + } + other => return Err(format!("expected ',' or '}}', got {other:?} at {}", self.pos)), + } + } + } + + fn parse_string(&mut self) -> Result { + if self.peek() != Some(b'"') { + return Err(format!("expected '\"' at {}", self.pos)); + } + self.pos += 1; + let mut out = String::new(); + while self.pos < self.bytes.len() { + let b = self.bytes[self.pos]; + if b == b'"' { + self.pos += 1; + return Ok(out); + } + if b < 0x20 { + return Err(format!("unescaped control byte 0x{b:02x} at {}", self.pos)); + } + if b == b'\\' { + self.pos += 1; + let esc = self.peek().ok_or("unterminated escape")?; + self.pos += 1; + match esc { + b'"' => out.push('"'), + b'\\' => out.push('\\'), + b'/' => out.push('/'), + b'b' => out.push('\x08'), + b'f' => out.push('\x0C'), + b'n' => out.push('\n'), + b'r' => out.push('\r'), + b't' => out.push('\t'), + b'u' => { + if self.pos + 4 > self.bytes.len() { + return Err("truncated \\u escape".to_string()); + } + let hex = std::str::from_utf8(&self.bytes[self.pos..self.pos + 4]) + .map_err(|_| "invalid utf-8 in \\u")?; + let code = u32::from_str_radix(hex, 16) + .map_err(|_| format!("invalid hex {hex}"))?; + self.pos += 4; + let ch = char::from_u32(code).ok_or("invalid scalar")?; + out.push(ch); + } + other => return Err(format!("invalid escape \\{}", other as char)), + } + } else { + let rest = std::str::from_utf8(&self.bytes[self.pos..]) + .map_err(|_| "invalid utf-8 in string")?; + let ch = rest.chars().next().ok_or("unexpected EOF")?; + out.push(ch); + self.pos += ch.len_utf8(); + } + } + Err("unterminated string".to_string()) + } + + fn parse_number(&mut self) -> Result { + let start = self.pos; + if self.peek() == Some(b'-') { + self.pos += 1; + } + match self.peek() { + Some(b'0') => self.pos += 1, + Some(b'1'..=b'9') => { + while matches!(self.peek(), Some(b'0'..=b'9')) { + self.pos += 1; + } + } + _ => return Err(format!("invalid number start at {}", self.pos)), + } + if self.peek() == Some(b'.') { + self.pos += 1; + if !matches!(self.peek(), Some(b'0'..=b'9')) { + return Err(format!("expected digit after '.' at {}", self.pos)); + } + while matches!(self.peek(), Some(b'0'..=b'9')) { + self.pos += 1; + } + } + if matches!(self.peek(), Some(b'e' | b'E')) { + self.pos += 1; + if matches!(self.peek(), Some(b'+' | b'-')) { + self.pos += 1; + } + if !matches!(self.peek(), Some(b'0'..=b'9')) { + return Err(format!("expected exponent digit at {}", self.pos)); + } + while matches!(self.peek(), Some(b'0'..=b'9')) { + self.pos += 1; + } + } + let slice = std::str::from_utf8(&self.bytes[start..self.pos]).unwrap(); + let num = slice + .parse::() + .map_err(|_| format!("invalid float {slice}"))?; + if !num.is_finite() { + return Err(format!("non-finite JSON number {slice}")); + } + Ok(JsonVal::Num(num)) + } +} + +fn parse_json_object(src: &str) -> Vec<(String, JsonVal)> { + let mut parser = JsonParser::new(src); + let val = parser + .parse_value() + .unwrap_or_else(|e| panic!("invalid JSON {src:?}: {e}")); + assert_eq!(parser.pos, src.len(), "trailing bytes in JSON: {src:?}"); + match val { + JsonVal::Obj(fields) => fields, + other => panic!("expected JSON object, got {other:?}"), + } +} + +fn assert_accounting_and_order(build: &EventsBuild) { + let s = &build.stats; + assert_eq!( + s.filings_in, + s.filings_out + + s.filings_skipped_malformed_timestamp + + s.filings_skipped_unknown_zone + + s.filings_skipped_invalid_date_time + + s.filings_duplicate_collapsed, + "filing conservation failed: {s:?}" + ); + assert_eq!( + s.earnings_in, + s.earnings_out + + s.earnings_skipped_out_of_range + + s.earnings_duplicate_collapsed + + s.earnings_duplicate_conflict_dropped, + "earnings conservation failed: {s:?}" + ); + assert_eq!( + s.earnings_out, + s.earnings_linked_to_filing + s.earnings_lagged_1605 + ); + assert_eq!(s.rows_out, s.filings_out + s.earnings_out); + assert_eq!(s.rows_out, build.rows.len()); + + let mut distinct_keys = 0usize; + let mut prev_key: Option<&K> = None; + for row in &build.rows { + assert_eq!(row.ts_micros, row.known_at_micros); + assert_eq!(row.partition_year(), partition_year_utc(row.ts_micros)); + let fields = parse_json_object(&row.payload_json); + let keys: Vec<&str> = fields.iter().map(|(k, _)| k.as_str()).collect(); + if row.kind == EVENT_KIND_FILING { + assert_eq!(keys, vec!["filing_id", "form_type", "is_amendment", "url"]); + assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + } else { + assert_eq!(row.kind, EVENT_KIND_EARNINGS); + assert_eq!( + keys, + vec![ + "actual_eps", + "announce_time", + "fiscal_period_end", + "linked_filing_id", + "report_date", + "revenue", + ] + ); + assert!(!keys.contains(&"consensusEps")); + assert!(!keys.contains(&"consensus_eps")); + } + if prev_key != Some(&row.key) { + distinct_keys += 1; + prev_key = Some(&row.key); + } + } + assert_eq!(s.keys_out, distinct_keys); + + for pair in build.rows.windows(2) { + let lhs = ( + &pair[0].key, + pair[0].ts_micros, + pair[0].kind, + &pair[0].subtype, + &pair[0].payload_json, + ); + let rhs = ( + &pair[1].key, + pair[1].ts_micros, + pair[1].kind, + &pair[1].subtype, + &pair[1].payload_json, + ); + assert!(lhs <= rhs, "rows must be sorted deterministically"); + } +} + +#[test] +fn public_constants_and_filing_timestamps_match_contract() { + assert_eq!(EVENT_KIND_FILING, "filing"); + assert_eq!(EVENT_KIND_EARNINGS, "earnings"); + assert_eq!(KNOWN_AT_SOURCE_FILING_TIMESTAMP, "filing_timestamp"); + assert_eq!(KNOWN_AT_SOURCE_STATUTORY_LAG, "statutory_lag_estimate"); + assert_eq!(EARNINGS_FALLBACK_HOUR_ET, 16); + assert_eq!(EARNINGS_FALLBACK_MINUTE_ET, 5); + + let est = parse_filing_timefiled("2025-01-31T06:01:27 EST").unwrap(); + assert_eq!(est.utc_micros, utc_micros(2025, 1, 31, 11, 1, 27)); + assert_eq!(est.et_date, day(2025, 1, 31)); + + let edt = parse_filing_timefiled("2025-07-04T09:15:00 EDT").unwrap(); + assert_eq!(edt.utc_micros, utc_micros(2025, 7, 4, 13, 15, 0)); + assert_eq!(edt.et_date, day(2025, 7, 4)); + + let pre2008 = parse_filing_timefiled("2003-07-15T14:30:00 EDT").unwrap(); + assert_eq!(pre2008.utc_micros, utc_micros(2003, 7, 15, 18, 30, 0)); + assert_eq!(pre2008.et_date, day(2003, 7, 15)); + + assert_eq!( + parse_filing_timefiled("bad"), + Err(FilingTimeError::MalformedFormat) + ); + assert_eq!( + parse_filing_timefiled("2025-01-31T06:01:27 PST"), + Err(FilingTimeError::UnknownZone) + ); + assert_eq!( + parse_filing_timefiled("2025-01-31T06:01:27"), + Err(FilingTimeError::UnknownZone) + ); + assert_eq!( + parse_filing_timefiled("2025-02-30T06:01:27 EST"), + Err(FilingTimeError::InvalidDate) + ); + assert_eq!( + parse_filing_timefiled("2025-01-31T25:00:00 EST"), + Err(FilingTimeError::InvalidTime) + ); + assert_eq!( + parse_filing_timefiled("2025-01-31T12:60:00 EST"), + Err(FilingTimeError::InvalidTime) + ); +} + +#[test] +fn form_groups_and_periodic_predicate_cover_all_contract_forms() { + let cases = [ + ("10-K", FilingFormGroup::Form10K, "10-k", false, true), + ("10-K/A", FilingFormGroup::Form10K, "10-k", true, true), + ("10-K (Amended)", FilingFormGroup::Form10K, "10-k", true, true), + ("10-Q", FilingFormGroup::Form10Q, "10-q", false, true), + ("10-Q/A", FilingFormGroup::Form10Q, "10-q", true, true), + ("10-Q - Amended", FilingFormGroup::Form10Q, "10-q", true, true), + ("8-K", FilingFormGroup::Form8K, "8-k", false, false), + ("8-K/A", FilingFormGroup::Form8K, "8-k", true, false), + ("8-K (Amended)", FilingFormGroup::Form8K, "8-k", true, false), + ("4", FilingFormGroup::Form4, "4", false, false), + ("144", FilingFormGroup::Form144, "144", false, false), + ("40-F", FilingFormGroup::Form40F, "40-f", false, true), + ("Amended 40-F", FilingFormGroup::Form40F, "40-f", true, true), + ( + "Interim financial statements/report", + FilingFormGroup::InterimFinancials, + "interim_financial_statements", + false, + true, + ), + ( + "Annual financial statements", + FilingFormGroup::AnnualFinancials, + "annual_financial_statements", + false, + true, + ), + ("MD&A", FilingFormGroup::Mda, "mda", false, false), + ("52-109", FilingFormGroup::Form52109, "52-109", false, false), + ( + "NI 43-101", + FilingFormGroup::Ni43101, + "ni_43_101", + false, + false, + ), + ( + "45-106F1", + FilingFormGroup::Form45106F1, + "45-106f1", + false, + false, + ), + ( + "News release", + FilingFormGroup::NewsRelease, + "news_release", + false, + false, + ), + ("424B5", FilingFormGroup::Other, "other", false, false), + ("S-3", FilingFormGroup::Other, "other", false, false), + ("DEF 14A", FilingFormGroup::Other, "other", false, false), + ]; + + for (raw, group, subtype, amend, periodic) in cases { + let (got_group, got_amend) = classify_form_type(raw); + assert_eq!(got_group, group, "raw={raw:?}"); + assert_eq!(got_group.as_str(), subtype, "raw={raw:?}"); + assert_eq!(got_amend, amend, "raw={raw:?}"); + assert_eq!(got_group.is_periodic_financial_report(), periodic); + assert_eq!(is_periodic_financial_report(raw), periodic); + } + + assert_eq!(normalize_announce_time("BTO"), "bto"); + assert_eq!(normalize_announce_time(" amc "), "amc"); + assert_eq!(normalize_announce_time("N/A"), "unknown"); + assert_eq!(normalize_announce_time(""), "unknown"); + + // Regression: `10-K (Amended)` retains subtype `"10-k"` while preserving the raw label in JSON. + let amended_build = build_events( + vec![QmFiling { + key: 7_i32, + timefiled: "2025-03-03T16:15:00 EST".to_string(), + form_type: "10-K (Amended)".to_string(), + filing_id: Some("f-10k-amended".to_string()), + url: None, + }], + Vec::>::new(), + ); + assert_accounting_and_order(&amended_build); + assert_eq!(amended_build.rows.len(), 1); + assert_eq!(amended_build.rows[0].subtype, "10-k"); + let fields = parse_json_object(&amended_build.rows[0].payload_json); + assert_eq!( + fields, + vec![ + ( + "filing_id".to_string(), + JsonVal::Str("f-10k-amended".to_string()) + ), + ( + "form_type".to_string(), + JsonVal::Str("10-K (Amended)".to_string()) + ), + ("is_amendment".to_string(), JsonVal::Bool(true)), + ("url".to_string(), JsonVal::Null), + ] + ); +} + +#[test] +fn earnings_linking_lagging_cross_midnight_and_out_of_range_rules() { + let d_est = day(2025, 1, 31); // EST + let d_edt = day(2025, 7, 15); // EDT + let d_other = day(2025, 2, 3); + let d_pre2008 = day(2003, 7, 15); + + let filings = vec![ + // (a) Same-day 8-K for key=1 + QmFiling { + key: 1, + timefiled: "2025-01-31T16:10:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("k1-8k".to_string()), + url: None, + }, + // (b) Multiple same-day 8-K + News release for key=2 -> earliest wins + QmFiling { + key: 2, + timefiled: "2025-01-31T17:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("k2-late".to_string()), + url: None, + }, + QmFiling { + key: 2, + timefiled: "2025-01-31T07:30:00 EST".to_string(), + form_type: "News release".to_string(), + filing_id: Some("k2-early".to_string()), + url: None, + }, + // (b2) Exact timestamp tie for key=20 -> deterministic smallest filing_id wins + QmFiling { + key: 20, + timefiled: "2025-01-31T08:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("b-id".to_string()), + url: None, + }, + QmFiling { + key: 20, + timefiled: "2025-01-31T08:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("a-id".to_string()), + url: None, + }, + // (c) Non-qualifying Form 4 on same day for key=3 + qualifying 8-K on different date + QmFiling { + key: 3, + timefiled: "2025-01-31T08:00:00 EST".to_string(), + form_type: "4".to_string(), + filing_id: Some("k3-form4".to_string()), + url: None, + }, + QmFiling { + key: 3, + timefiled: "2025-02-03T08:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("k3-other-day".to_string()), + url: None, + }, + // (f) Pre-2008 qualifying 8-K for key=6 -> allows pre-2008 earnings to link! + QmFiling { + key: 6, + timefiled: "2003-07-15T16:15:00 EDT".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("k6-2003".to_string()), + url: None, + }, + // (g) Late-evening ET filing crossing into next UTC calendar day (2025-02-01T02:30:00Z) + QmFiling { + key: 7, + timefiled: "2025-01-31T21:30:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("k7-late-et".to_string()), + url: None, + }, + ]; + + let earnings = vec![ + // (a) N/A linked to same-day 8-K + QmEarning { + key: 1, + report_date: d_est, + announce_time: "N/A".to_string(), + fiscal_period_end: Some(day(2024, 12, 31)), + actual_eps: Some(1.25), + revenue: Some(100_000.0), + }, + // (b) Linked to earliest (News release 07:30 EST) + QmEarning { + key: 2, + report_date: d_est, + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: Some(0.5), + revenue: None, + }, + // (b2) Tie-break picks "a-id" + QmEarning { + key: 20, + report_date: d_est, + announce_time: "BTO".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (c)+(d) Unlinked EST (Form 4 doesn't qualify; 8-K is different date) -> 21:05Z + QmEarning { + key: 3, + report_date: d_est, + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (d)+(e) Unlinked EDT + BTO -> 20:05Z (never earlier than 16:05 ET) + QmEarning { + key: 4, + report_date: d_edt, + announce_time: "BTO".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (e) Unlinked EST + AMC -> 21:05Z + QmEarning { + key: 5, + report_date: d_other, + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (f1) Pre-2008 WITH linked filing -> succeeds via filing_timestamp + QmEarning { + key: 6, + report_date: d_pre2008, + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (f2) Pre-2008 WITHOUT linked filing -> skipped (out of range) + QmEarning { + key: 60, + report_date: MIN_SUPPORTED_DATE - 1, + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (f3) Post-2030 WITHOUT linked filing -> skipped (out of range) + QmEarning { + key: 61, + report_date: MAX_SUPPORTED_DATE + 1, + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: None, + revenue: None, + }, + // (g) Late-evening ET filing links by ET calendar date (2025-01-31) + QmEarning { + key: 7, + report_date: d_est, + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: Some(2.0), + revenue: None, + }, + ]; + + let built = build_events(filings, earnings); + assert_accounting_and_order(&built); + assert_eq!(built.stats.earnings_in, 10); + assert_eq!(built.stats.earnings_out, 8); + assert_eq!(built.stats.earnings_linked_to_filing, 5); + assert_eq!(built.stats.earnings_lagged_1605, 3); + assert_eq!(built.stats.earnings_skipped_out_of_range, 2); + + let find_earning = |key: i32| -> &EventRow { + built + .rows + .iter() + .find(|r| r.key == key && r.kind == EVENT_KIND_EARNINGS) + .unwrap_or_else(|| panic!("missing earning for key {key}")) + }; + + let e1 = find_earning(1); + assert_eq!(e1.known_at_micros, utc_micros(2025, 1, 31, 21, 10, 0)); + assert_eq!(e1.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(e1.subtype, "unknown"); + + let e2 = find_earning(2); + assert_eq!(e2.known_at_micros, utc_micros(2025, 1, 31, 12, 30, 0)); + assert_eq!(e2.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(e2.payload_json.contains("\"linked_filing_id\":\"k2-early\"")); + + let e20 = find_earning(20); + assert!(e20.payload_json.contains("\"linked_filing_id\":\"a-id\"")); + + let e3 = find_earning(3); + assert_eq!(e3.known_at_micros, utc_micros(2025, 1, 31, 21, 5, 0)); + assert_eq!(e3.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert_eq!(e3.subtype, "unknown"); + + let e4 = find_earning(4); + assert_eq!(e4.known_at_micros, utc_micros(2025, 7, 15, 20, 5, 0)); + assert_eq!(e4.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert_eq!(e4.subtype, "bto"); + + let e5 = find_earning(5); + assert_eq!(e5.known_at_micros, utc_micros(2025, 2, 3, 21, 5, 0)); + assert_eq!(e5.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert_eq!(e5.subtype, "amc"); + + let e6 = find_earning(6); + assert_eq!(e6.known_at_micros, utc_micros(2003, 7, 15, 20, 15, 0)); + assert_eq!(e6.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + + let e7 = find_earning(7); + assert_eq!(e7.known_at_micros, utc_micros(2025, 2, 1, 2, 30, 0)); + assert_eq!(e7.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(e7 + .payload_json + .contains("\"linked_filing_id\":\"k7-late-et\"")); +} + +#[test] +fn payload_json_round_trips_escapes_unicode_and_non_finite_numbers() { + let tricky_id = "id-\"quote\"\\slash\x08\x0c\n\r\t\x00\x1f-日本語-café"; + let tricky_form = "10-K/A \"amended\""; + let tricky_url = "https://sec.gov/Archives/a\\b?q=\"1\"&x=αβγ"; + + let raw = encode_filing_payload_json(Some(tricky_id), tricky_form, true, Some(tricky_url)); + let parsed = parse_json_object(&raw); + assert_eq!( + parsed, + vec![ + ("filing_id".to_string(), JsonVal::Str(tricky_id.to_string())), + ( + "form_type".to_string(), + JsonVal::Str(tricky_form.to_string()) + ), + ("is_amendment".to_string(), JsonVal::Bool(true)), + ("url".to_string(), JsonVal::Str(tricky_url.to_string())), + ] + ); + + let e_raw = encode_earnings_payload_json( + Some(f64::NAN), + "bto", + Some(day(2024, 9, 30)), + Some("acc\"1"), + day(2024, 10, 31), + Some(f64::INFINITY), + ); + let e_parsed = parse_json_object(&e_raw); + assert_eq!( + e_parsed, + vec![ + ("actual_eps".to_string(), JsonVal::Null), + ("announce_time".to_string(), JsonVal::Str("bto".to_string())), + ( + "fiscal_period_end".to_string(), + JsonVal::Str("2024-09-30".to_string()) + ), + ( + "linked_filing_id".to_string(), + JsonVal::Str("acc\"1".to_string()) + ), + ( + "report_date".to_string(), + JsonVal::Str("2024-10-31".to_string()) + ), + ("revenue".to_string(), JsonVal::Null), + ] + ); +} + +#[test] +fn deduplication_conflicts_zero_nan_normalization_and_permutation_invariance() { + let d1 = day(2025, 1, 31); + let d2 = day(2025, 7, 15); + + let filings = vec![ + QmFiling { + key: 1, + timefiled: "2025-01-31T06:01:27 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("f1".to_string()), + url: None, + }, + // Exact duplicate filing -> collapsed + QmFiling { + key: 1, + timefiled: "2025-01-31T06:01:27 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("f1".to_string()), + url: None, + }, + // Bad filings -> skipped and counted + QmFiling { + key: 1, + timefiled: "not-a-date".to_string(), + form_type: "10-K".to_string(), + filing_id: None, + url: None, + }, + QmFiling { + key: 1, + timefiled: "2025-01-31T06:01:27 PST".to_string(), + form_type: "10-K".to_string(), + filing_id: None, + url: None, + }, + QmFiling { + key: 1, + timefiled: "2025-02-30T06:01:27 EST".to_string(), + form_type: "10-K".to_string(), + filing_id: None, + url: None, + }, + QmFiling { + key: 1, + timefiled: "2025-01-31T25:00:00 EST".to_string(), + form_type: "10-K".to_string(), + filing_id: None, + url: None, + }, + ]; + + let earnings = vec![ + // Identical after -0.0 and distinct NaN normalization -> collapsed (no conflict) + QmEarning { + key: 1, + report_date: d1, + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: Some(-0.0), + revenue: Some(f64::NAN), + }, + QmEarning { + key: 1, + report_date: d1, + announce_time: " ".to_string(), + fiscal_period_end: None, + actual_eps: Some(0.0), + revenue: Some(f64::from_bits(0x7ff8_0000_0000_0001)), + }, + // Conflicting duplicate group -> dropped entirely + QmEarning { + key: 2, + report_date: d2, + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: Some(1.0), + revenue: None, + }, + QmEarning { + key: 2, + report_date: d2, + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: Some(2.0), + revenue: None, + }, + ]; + + let baseline = build_events(filings.clone(), earnings.clone()); + assert_accounting_and_order(&baseline); + assert_eq!(baseline.stats.filings_in, 6); + assert_eq!(baseline.stats.filings_out, 1); + assert_eq!(baseline.stats.filings_duplicate_collapsed, 1); + assert_eq!(baseline.stats.filings_skipped_malformed_timestamp, 1); + assert_eq!(baseline.stats.filings_skipped_unknown_zone, 1); + assert_eq!(baseline.stats.filings_skipped_invalid_date_time, 2); + assert_eq!(baseline.stats.earnings_in, 4); + assert_eq!(baseline.stats.earnings_out, 1); + assert_eq!(baseline.stats.earnings_duplicate_collapsed, 1); + assert_eq!(baseline.stats.earnings_duplicate_conflict_dropped, 2); + + let mut rng = Rng(0x570C_4B07_E7E4_9999); + for _ in 0..16 { + let mut f_perm = filings.clone(); + let mut e_perm = earnings.clone(); + shuffle(&mut f_perm, &mut rng); + shuffle(&mut e_perm, &mut rng); + let trial = build_events(f_perm, e_perm); + assert_accounting_and_order(&trial); + assert_eq!(trial.rows, baseline.rows); + assert_eq!(trial.stats, baseline.stats); + } + + let empty = build_events::(Vec::new(), Vec::new()); + assert_eq!(empty.stats, EventsStats::default()); + assert_accounting_and_order(&empty); +} + +#[test] +fn run_events_benchmark_and_cli_binary_are_reproducible() { + let a = run_events_benchmark(5_000); + let b = run_events_benchmark(5_000); + assert_eq!(a.rows, 5_000); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.keys_out, b.keys_out); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + + let bin = env!("CARGO_BIN_EXE_curate-etl"); + let run1 = Command::new(bin) + .args(["bench-events", "5000"]) + .output() + .expect("run bench-events #1"); + let run2 = Command::new(bin) + .args(["bench-events", "5000"]) + .output() + .expect("run bench-events #2"); + + assert!(run1.status.success(), "bench-events #1 failed"); + assert!(run2.status.success(), "bench-events #2 failed"); + + let out1 = String::from_utf8_lossy(&run1.stdout); + let out2 = String::from_utf8_lossy(&run2.stdout); + assert!(out1.contains("curate-etl bench-events")); + assert!(out1.contains("rows/s")); + assert!(out1.contains("checksum=0x")); + + let extract_checksum = |s: &str| -> String { + s.split("checksum=") + .nth(1) + .and_then(|rest| rest.split_whitespace().next()) + .expect("checksum token present") + .to_string() + }; + assert_eq!(extract_checksum(&out1), extract_checksum(&out2)); + + for bad in [ + &["bench-events", "0"][..], + &["bench-events", "-5"][..], + &["bench-events", "abc"][..], + &["bench-events", "10", "20"][..], + ] { + let out = Command::new(bin) + .args(bad) + .output() + .expect("run invalid bench-events"); + assert!(!out.status.success(), "expected failure for {bad:?}"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("bench-events")); + } +} diff --git a/tools/curate-etl/tests/events_reference.rs b/tools/curate-etl/tests/events_reference.rs new file mode 100644 index 00000000..92e1e357 --- /dev/null +++ b/tools/curate-etl/tests/events_reference.rs @@ -0,0 +1,595 @@ +//! Independent reference / point-in-time QA tests for the `events` builder (T-77 / M1.2g). +//! +//! Verifies: +//! - Independent EST (+5h) / EDT (+4h) UTC math oracle across pre-2008, leap-day, and +//! year-end cross-midnight filings, +//! - Cross-midnight ET calendar-date linking (`2024-12-31T21:30:00 EST` links to `2024-12-31` +//! while partitioning into UTC `year=2025`), +//! - Future-date poison-row stability (appending filings and earnings on later dates never alters +//! emitted rows from earlier dates), plus an explicit fixture showing that a same-date evening +//! filing replaces the `16:05 ET` fallback (which is intended for T+1 open use, not same-day +//! intraday cutoffs). + +use curate_etl::bench::{run_events_benchmark, DEFAULT_EVENTS_BENCH_ROWS}; +use curate_etl::{ + build_events, parse_filing_timefiled, partition_year_utc, ymd_to_epoch_days, QmEarning, + QmFiling, EVENT_KIND_EARNINGS, KNOWN_AT_SOURCE_FILING_TIMESTAMP, KNOWN_AT_SOURCE_STATUTORY_LAG, +}; + +const MICROS_PER_SEC: i64 = 1_000_000; +const MICROS_PER_HOUR: i64 = 3_600 * MICROS_PER_SEC; +const MICROS_PER_DAY: i64 = 24 * MICROS_PER_HOUR; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn oracle_utc_micros( + year: i32, + month: u32, + dom: u32, + hour: u32, + minute: u32, + second: u32, + offset_hours: i64, +) -> i64 { + let d = i64::from(day(year, month, dom)); + d * MICROS_PER_DAY + + (i64::from(hour) + offset_hours) * MICROS_PER_HOUR + + i64::from(minute) * 60 * MICROS_PER_SEC + + i64::from(second) * MICROS_PER_SEC +} + +#[test] +fn est_and_edt_conversions_match_independent_oracle_across_decades() { + let cases = [ + (1999, 12, 31, 23, 59, 59, "EST", 5), + (2000, 2, 29, 16, 30, 0, "EST", 5), + (2003, 7, 15, 14, 30, 0, "EDT", 4), + (2007, 11, 4, 0, 15, 10, "EDT", 4), + (2024, 12, 31, 21, 30, 0, "EST", 5), + (2025, 1, 31, 6, 1, 27, "EST", 5), + (2026, 3, 6, 17, 0, 0, "EST", 5), + (2026, 3, 9, 17, 0, 0, "EDT", 4), + ]; + + for (y, m, d, hh, mm, ss, zone, offset) in cases { + let raw = format!("{y:04}-{m:02}-{d:02}T{hh:02}:{mm:02}:{ss:02} {zone}"); + let parsed = parse_filing_timefiled(&raw).expect("valid oracle fixture"); + assert_eq!(parsed.et_date, day(y, m, d), "et_date mismatch for {raw}"); + assert_eq!( + parsed.utc_micros, + oracle_utc_micros(y, m, d, hh, mm, ss, offset), + "utc_micros mismatch for {raw}" + ); + } +} + +#[test] +fn year_end_late_et_filing_links_by_et_date_and_partitions_by_utc_year() { + let dec31 = day(2024, 12, 31); + let built = build_events( + vec![QmFiling { + key: 42_i32, + timefiled: "2024-12-31T21:30:00 EST".to_string(), + form_type: "News release".to_string(), + filing_id: Some("nye-nr".to_string()), + url: None, + }], + vec![QmEarning { + key: 42_i32, + report_date: dec31, + announce_time: "N/A".to_string(), + fiscal_period_end: Some(day(2024, 10, 31)), + actual_eps: Some(0.42), + revenue: None, + }], + ); + + assert_eq!(built.rows.len(), 2); + let expected_utc = oracle_utc_micros(2025, 1, 1, 2, 30, 0, 0); + assert_eq!(partition_year_utc(expected_utc), 2025); + + for row in &built.rows { + assert_eq!(row.ts_micros, expected_utc); + assert_eq!(row.known_at_micros, expected_utc); + assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(row.partition_year(), 2025); + } + + let earning = built + .rows + .iter() + .find(|r| r.kind == EVENT_KIND_EARNINGS) + .expect("earnings row present"); + assert!(earning + .payload_json + .contains("\"linked_filing_id\":\"nye-nr\"")); +} + +#[test] +fn appending_future_date_poison_filings_and_earnings_never_alters_prior_dates() { + let cutoff_utc = oracle_utc_micros(2025, 3, 1, 0, 0, 0, 0); + + let base_filings = vec![ + QmFiling { + key: 1_i32, + timefiled: "2025-01-31T08:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("f-jan".to_string()), + url: None, + }, + QmFiling { + key: 2_i32, + timefiled: "2025-02-10T16:30:00 EST".to_string(), + form_type: "10-K".to_string(), + filing_id: Some("f-feb".to_string()), + url: None, + }, + ]; + let base_earnings = vec![ + QmEarning { + key: 1_i32, + report_date: day(2025, 1, 31), + announce_time: "BTO".to_string(), + fiscal_period_end: Some(day(2024, 12, 31)), + actual_eps: Some(1.1), + revenue: Some(50_000.0), + }, + QmEarning { + key: 2_i32, + report_date: day(2025, 2, 10), + announce_time: "AMC".to_string(), + fiscal_period_end: Some(day(2024, 12, 31)), + actual_eps: Some(2.2), + revenue: Some(80_000.0), + }, + ]; + + let before = build_events(base_filings.clone(), base_earnings.clone()); + + let mut poisoned_filings = base_filings; + poisoned_filings.push(QmFiling { + key: 1, + timefiled: "2025-05-01T07:00:00 EDT".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("f-may-poison".to_string()), + url: None, + }); + poisoned_filings.push(QmFiling { + key: 2, + timefiled: "2025-02-11T07:00:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("f-next-day".to_string()), + url: None, + }); + poisoned_filings.push(QmFiling { + key: 1, + timefiled: "malformed".to_string(), + form_type: "8-K".to_string(), + filing_id: None, + url: None, + }); + + let mut poisoned_earnings = base_earnings; + poisoned_earnings.push(QmEarning { + key: 1, + report_date: day(2025, 5, 1), + announce_time: "N/A".to_string(), + fiscal_period_end: None, + actual_eps: Some(999.0), + revenue: None, + }); + poisoned_earnings.push(QmEarning { + key: 2, + report_date: day(2025, 6, 1), + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: Some(1.0), + revenue: None, + }); + poisoned_earnings.push(QmEarning { + key: 2, + report_date: day(2025, 6, 1), + announce_time: "AMC".to_string(), + fiscal_period_end: None, + actual_eps: Some(2.0), + revenue: None, + }); + + let after = build_events(poisoned_filings, poisoned_earnings); + let earlier: Vec<_> = after + .rows + .iter() + .filter(|r| r.ts_micros < cutoff_utc && r.known_at_micros < cutoff_utc) + .filter(|r| !(r.key == 2 && r.payload_json.contains("f-next-day"))) + .cloned() + .collect(); + assert_eq!(earlier, before.rows); +} + +#[test] +fn same_date_late_filing_replaces_1605_fallback_across_intraday_cutoff() { + // The 16:05 ET fallback (`statutory_lag_estimate`) is intended for T+1 open use, not same-day + // intraday cutoffs: if a same-date qualifying filing arrives at 21:30 ET, link precedence + // moves the earnings timestamp from 16:05 ET (before a 17:00 ET intraday cutoff) to 21:30 ET + // (after that cutoff). + let report_date = day(2025, 2, 10); + let intraday_cutoff_utc = oracle_utc_micros(2025, 2, 10, 17, 0, 0, 5); // 17:00 EST = 22:00Z + let fallback_1605_utc = oracle_utc_micros(2025, 2, 10, 16, 5, 0, 5); // 16:05 EST = 21:05Z + let late_filing_utc = oracle_utc_micros(2025, 2, 10, 21, 30, 0, 5); // 21:30 EST = 02:30Z Feb 11 + + let earning = QmEarning { + key: 2_i32, + report_date, + announce_time: "AMC".to_string(), + fiscal_period_end: Some(day(2024, 12, 31)), + actual_eps: Some(2.2), + revenue: Some(80_000.0), + }; + + let without_filing = build_events(Vec::>::new(), vec![earning.clone()]); + assert_eq!(without_filing.rows.len(), 1); + let fallback_row = &without_filing.rows[0]; + assert_eq!(fallback_row.known_at_micros, fallback_1605_utc); + assert_eq!(fallback_row.known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + assert!(fallback_row.known_at_micros < intraday_cutoff_utc); + + let with_late_filing = build_events( + vec![QmFiling { + key: 2_i32, + timefiled: "2025-02-10T21:30:00 EST".to_string(), + form_type: "8-K".to_string(), + filing_id: Some("f-late-8k".to_string()), + url: None, + }], + vec![earning], + ); + let linked_row = with_late_filing + .rows + .iter() + .find(|r| r.kind == EVENT_KIND_EARNINGS) + .expect("earnings row present"); + assert_eq!(linked_row.known_at_micros, late_filing_utc); + assert_eq!(linked_row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert!(linked_row.known_at_micros > intraday_cutoff_utc); +} + +#[test] +fn default_bench_events_matches_readme_recorded_output() { + // README records rows_out=491190, filings_out=484531, earnings_out=6659, keys_out=20000, + // checksum 0xbf74cd745a2646c6 and the stats line below for + // `cargo run --release -p curate-etl --offline -- bench-events`. + let report = run_events_benchmark(DEFAULT_EVENTS_BENCH_ROWS); + assert_eq!(DEFAULT_EVENTS_BENCH_ROWS, 500_000); + assert_eq!(report.filings_in, 492_500); + assert_eq!(report.earnings_in, 7_500); + assert_eq!(report.rows_out, 491_190); + assert_eq!(report.stats.filings_out, 484_531); + assert_eq!(report.stats.earnings_out, 6_659); + assert_eq!(report.keys_out, 20_000); + assert_eq!(report.stats.filings_skipped_malformed_timestamp, 1_525); + assert_eq!(report.stats.filings_skipped_unknown_zone, 1_496); + assert_eq!(report.stats.filings_skipped_invalid_date_time, 2_476); + assert_eq!(report.stats.filings_duplicate_collapsed, 2_472); + assert_eq!(report.stats.earnings_linked_to_filing, 2_569); + assert_eq!(report.stats.earnings_lagged_1605, 4_090); + assert_eq!(report.stats.earnings_skipped_out_of_range, 37); + assert_eq!(report.stats.earnings_duplicate_collapsed, 98); + assert_eq!(report.stats.earnings_duplicate_conflict_dropped, 706); + assert_eq!(report.checksum, 0xbf74_cd74_5a26_46c6); +} + +// --------------------------------------------------------------------------------------------- +// QA additions (T-77): robustness, PIT truncation, link eligibility and boundary edge cases. +// --------------------------------------------------------------------------------------------- + +struct QaRng(u64); + +impl QaRng { + 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 filing(key: i32, timefiled: &str, form_type: &str, id: Option<&str>) -> QmFiling { + QmFiling { + key, + timefiled: timefiled.to_string(), + form_type: form_type.to_string(), + filing_id: id.map(str::to_string), + url: None, + } +} + +fn earning(key: i32, report_date: i32, announce_time: &str, eps: f64) -> QmEarning { + QmEarning { + key, + report_date, + announce_time: announce_time.to_string(), + fiscal_period_end: None, + actual_eps: Some(eps), + revenue: None, + } +} + +#[test] +fn qa_non_ascii_and_seeded_garbage_timefiled_never_panics_and_is_counted() { + // Multibyte characters at structural offsets must not cause byte-slice panics. + let fixed = [ + "2025-01-31T06:01:27 ÉST", + "2025-01-31T06:01:27 EST", + "2025é01-31T06:01:27 EST", + "2025-01-31T06:01:2é EST", + "2025-01-31T06:01:27\u{00a0}EST", + "2025-01-31T06:01:27.123 EST", + "+025-01-31T06:01:27 EST", + "2025-01-31T06:01:27 EST\0", + ]; + for raw in fixed { + assert!(parse_filing_timefiled(raw).is_err(), "must reject {raw:?}"); + } + + let alphabet: Vec = "0123456789-T: ESTDZé\u{00a0}2/".chars().collect(); + let template: Vec = "2025-01-31T06:01:27 EST".chars().collect(); + let mut rng = QaRng(0x0A11_7E57_0000_0077); + let mut inputs = Vec::new(); + for i in 0..5_000 { + let mut chars = template.clone(); + let mutations = 1 + (rng.next() % 3) as usize; + for _ in 0..mutations { + let pos = (rng.next() as usize) % chars.len(); + chars[pos] = alphabet[(rng.next() as usize) % alphabet.len()]; + } + if rng.next() % 5 == 0 { + let cut = (rng.next() as usize) % chars.len(); + chars.truncate(cut); + } + let raw: String = chars.into_iter().collect(); + let _ = parse_filing_timefiled(&raw); // must not panic + inputs.push(filing(i % 7, &raw, "8-K", Some(&format!("g{i}")))); + } + + let built = build_events(inputs, Vec::>::new()); + let s = built.stats; + assert_eq!(s.filings_in, 5_000); + assert_eq!( + s.filings_in, + s.filings_out + + s.filings_skipped_malformed_timestamp + + s.filings_skipped_unknown_zone + + s.filings_skipped_invalid_date_time + + s.filings_duplicate_collapsed + ); + assert_eq!(s.rows_out, built.rows.len()); + // Every emitted row came from a string that parses successfully on its own. + for row in &built.rows { + assert_eq!(row.known_at_source, KNOWN_AT_SOURCE_FILING_TIMESTAMP); + assert_eq!(row.ts_micros, row.known_at_micros); + } +} + +#[test] +fn qa_skipped_or_non_qualifying_same_day_filings_never_anchor_earnings() { + let report = day(2025, 1, 31); + let filings = vec![ + // Same key, same ET date, qualifying form, but each row is unparseable → must not link. + filing(1, "2025-01-31T07:00:00 PST", "8-K", Some("bad-zone")), + filing( + 1, + "2025-01-31T25:00:00 EST", + "News release", + Some("bad-time"), + ), + filing(1, "2025-01-31 07:00:00 EST", "8-K/A", Some("bad-format")), + // Valid but non-qualifying forms on the same day. + filing(1, "2025-01-31T06:00:00 EST", "10-Q", Some("q")), + filing(1, "2025-01-31T06:30:00 EST", "NT 10-K", Some("nt")), + filing(1, "2025-01-31T06:45:00 EST", "MD&A", Some("mda")), + ]; + let built = build_events(filings, vec![earning(1, report, "BTO", 1.0)]); + + let e: Vec<_> = built + .rows + .iter() + .filter(|r| r.kind == EVENT_KIND_EARNINGS) + .collect(); + assert_eq!(e.len(), 1); + assert_eq!(e[0].known_at_source, KNOWN_AT_SOURCE_STATUTORY_LAG); + // 2025-01-31 is EST → 16:05 ET == 21:05Z. + assert_eq!( + e[0].known_at_micros, + oracle_utc_micros(2025, 1, 31, 21, 5, 0, 0) + ); + assert!(e[0].payload_json.contains("\"linked_filing_id\":null")); + assert_eq!(built.stats.earnings_linked_to_filing, 0); + assert_eq!(built.stats.earnings_lagged_1605, 1); + assert_eq!(built.stats.filings_skipped_unknown_zone, 1); + assert_eq!(built.stats.filings_skipped_invalid_date_time, 1); + assert_eq!(built.stats.filings_skipped_malformed_timestamp, 1); +} + +#[test] +fn qa_nt_and_variant_edgar_forms_are_not_periodic_reports() { + use curate_etl::{classify_form_type, is_periodic_financial_report, FilingFormGroup}; + // A late-filing notice must never be treated as the periodic report itself (PIT join safety). + for raw in [ + "NT 10-K", "NT 10-Q", "10-K405", "10-KT", "10-QT", "8-K12B", "40-FR12B", + ] { + assert!( + !is_periodic_financial_report(raw), + "{raw:?} must not be periodic" + ); + assert_eq!(classify_form_type(raw).0, FilingFormGroup::Other, "{raw:?}"); + } + // `/A` with internal whitespace still keeps the base group. + assert_eq!( + classify_form_type("10-K /A"), + (FilingFormGroup::Form10K, true) + ); + assert_eq!(classify_form_type("8-k/a"), (FilingFormGroup::Form8K, true)); +} + +#[test] +fn qa_earnings_duplicates_normalize_announce_time_and_conflicting_times_drop_group() { + let d = day(2025, 7, 15); + let earnings = vec![ + // Same normalized announce time ("bto") → collapse. + earning(1, d, "BTO", 2.0), + earning(1, d, " bto ", 2.0), + // "N/A" vs "other code" both normalize to "unknown" → collapse. + earning(2, d, "N/A", 3.0), + earning(2, d, "TBD", 3.0), + // BTO vs AMC for the same (key, report_date) → conflict, whole group dropped. + earning(3, d, "BTO", 4.0), + earning(3, d, "AMC", 4.0), + earning(3, d, "AMC", 4.0), + ]; + let built = build_events(Vec::>::new(), earnings); + let s = built.stats; + assert_eq!(s.earnings_in, 7); + assert_eq!(s.earnings_out, 2); + assert_eq!(s.earnings_duplicate_collapsed, 2); + assert_eq!(s.earnings_duplicate_conflict_dropped, 3); + assert!(built.rows.iter().all(|r| r.key != 3)); + let subtypes: Vec<_> = built + .rows + .iter() + .map(|r| (r.key, r.subtype.as_str())) + .collect(); + assert_eq!(subtypes, vec![(1, "bto"), (2, "unknown")]); + // 2025-07-15 is EDT → 16:05 ET == 20:05Z. + for row in &built.rows { + assert_eq!( + row.known_at_micros, + oracle_utc_micros(2025, 7, 15, 20, 5, 0, 0) + ); + } +} + +#[test] +fn qa_supported_range_boundaries_are_inclusive_for_unlinked_earnings() { + use curate_etl::{MAX_SUPPORTED_DATE, MIN_SUPPORTED_DATE}; + let earnings = vec![ + earning(1, MIN_SUPPORTED_DATE, "AMC", 1.0), + earning(2, MAX_SUPPORTED_DATE, "AMC", 1.0), + earning(3, MIN_SUPPORTED_DATE - 1, "AMC", 1.0), + earning(4, MAX_SUPPORTED_DATE + 1, "AMC", 1.0), + earning(5, i32::MIN, "AMC", 1.0), + earning(6, i32::MAX, "AMC", 1.0), + ]; + let built = build_events(Vec::>::new(), earnings); + assert_eq!(built.stats.earnings_out, 2); + assert_eq!(built.stats.earnings_skipped_out_of_range, 4); + // 2008-01-01 (EST) → 21:05Z; 2030-12-31 (EST) → 21:05Z. + assert_eq!( + built.rows[0].known_at_micros, + oracle_utc_micros(2008, 1, 1, 21, 5, 0, 0) + ); + assert_eq!( + built.rows[1].known_at_micros, + oracle_utc_micros(2030, 12, 31, 21, 5, 0, 0) + ); +} + +/// Extracts the `"report_date":"YYYY-MM-DD"` field from an earnings payload. +fn payload_report_date(payload: &str) -> String { + let marker = "\"report_date\":\""; + let start = payload.find(marker).expect("report_date present") + marker.len(); + payload[start..start + 10].to_string() +} + +#[test] +fn qa_seeded_truncation_rebuild_matches_full_build_for_every_cutoff() { + // Lens truncation test: deleting everything dated at/after ET date D and rebuilding must + // reproduce exactly the full build's rows dated before D (no future-dependent output). + let mut rng = QaRng(0x7A0C_A710_0000_0077); + let forms = [ + "8-K", + "News release", + "4", + "10-Q", + "8-K/A", + "Annual financial statements", + ]; + let start = day(2024, 1, 1); + let span = 120u64; + + let mut filings = Vec::new(); + for i in 0..3_000 { + let key = (rng.next() % 40) as i32; + let d = start + (rng.next() % span) as i32; + let (y, m, dd) = epoch_ymd(d); + // Include late-evening ET times that cross into the next UTC day; EST only so the + // ET-date cutoff maps to a single UTC instant. + let hour = [6, 9, 12, 16, 17, 21, 23][(rng.next() % 7) as usize]; + let ts = format!( + "{y:04}-{m:02}-{dd:02}T{hour:02}:{:02}:{:02} EST", + rng.next() % 60, + rng.next() % 60 + ); + filings.push(( + d, + filing( + key, + &ts, + forms[(rng.next() % 6) as usize], + Some(&format!("t{i}")), + ), + )); + } + let mut earnings = Vec::new(); + for _ in 0..600 { + let key = (rng.next() % 40) as i32; + let d = start + (rng.next() % span) as i32; + let at = ["BTO", "AMC", "N/A"][(rng.next() % 3) as usize]; + earnings.push((d, earning(key, d, at, (rng.next() % 500) as f64 / 100.0))); + } + + let full = build_events( + filings.iter().map(|(_, f)| f.clone()), + earnings.iter().map(|(_, e)| e.clone()), + ); + + for offset in [1, 17, 45, 60, 89, 119] { + let cutoff = start + offset; + let (cy, cm, cd) = epoch_ymd(cutoff); + let cutoff_str = format!("{cy:04}-{cm:02}-{cd:02}"); + let cutoff_utc = i64::from(cutoff) * MICROS_PER_DAY + 5 * MICROS_PER_HOUR; + + let truncated = build_events( + filings + .iter() + .filter(|(d, _)| *d < cutoff) + .map(|(_, f)| f.clone()), + earnings + .iter() + .filter(|(d, _)| *d < cutoff) + .map(|(_, e)| e.clone()), + ); + let expected: Vec<_> = full + .rows + .iter() + .filter(|r| { + if r.kind == EVENT_KIND_EARNINGS { + payload_report_date(&r.payload_json) < cutoff_str + } else { + r.ts_micros < cutoff_utc + } + }) + .cloned() + .collect(); + assert_eq!( + truncated.rows, expected, + "truncation mismatch at cutoff {cutoff_str}" + ); + } +} + +fn epoch_ymd(epoch_day: i32) -> (i32, u32, u32) { + curate_etl::shorts::epoch_days_to_ymd(epoch_day) +} diff --git a/tools/curate-etl/tests/fx_contract.rs b/tools/curate-etl/tests/fx_contract.rs new file mode 100644 index 00000000..d56ecec1 --- /dev/null +++ b/tools/curate-etl/tests/fx_contract.rs @@ -0,0 +1,426 @@ +//! Contract tests for the public `curate_etl` `fx_1d` builder API (T-75 / M1.2e). +//! +//! Uses only the crate's public surface, guarding the USD/CAD merge precedence, bad-row +//! resilience, deduplication isolation, read-only 1% overlap audit, permutation invariance, +//! accounting invariants, and no-look-ahead carry-forward lookup semantics. + +use curate_etl::bench::{run_fx_benchmark, DEFAULT_FX_BENCH_LOOKUPS}; +use curate_etl::{ + build_fx_1d, fx_rate_on_or_before, ymd_to_epoch_days, Fx1dBuild, Fx1dRow, Fx1dStats, + FxDailyBar, FxSource, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD, +}; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn bar(session_date: i32, open: f64, high: f64, low: f64, close: f64) -> FxDailyBar { + FxDailyBar { + session_date, + open, + high, + low, + close, + } +} + +fn flat(session_date: i32, rate: f64) -> FxDailyBar { + bar(session_date, rate, rate, rate, rate) +} + +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 shuffle(items: &mut [T], rng: &mut Rng) { + for i in (1..items.len()).rev() { + let j = (rng.next() % (i as u64 + 1)) as usize; + items.swap(i, j); + } +} + +fn assert_accounting_and_order(build: &Fx1dBuild) { + let s = &build.stats; + assert_eq!( + s.eod.rows_in, + s.eod.rows_kept + + s.eod.dropped_invalid_ohlc + + s.eod.dropped_inconsistent_ohlc + + s.eod.duplicate_collapsed + + s.eod.duplicate_conflict_dropped, + "EOD accounting invariant failed: {s:?}" + ); + assert_eq!( + s.te.rows_in, + s.te.rows_kept + + s.te.dropped_invalid_ohlc + + s.te.dropped_inconsistent_ohlc + + s.te.duplicate_collapsed + + s.te.duplicate_conflict_dropped, + "TE accounting invariant failed: {s:?}" + ); + assert_eq!( + s.rows_out, + s.eod.rows_kept + s.te.rows_kept - s.te_superseded_by_eod, + "merge rows_out invariant failed: {s:?}" + ); + assert_eq!( + s.rows_out, + s.eod_rows_out + s.te_rows_out, + "eod_rows_out + te_rows_out != rows_out: {s:?}" + ); + assert_eq!(s.rows_out, build.rows.len()); + assert_eq!( + s.overlap_within_tolerance + s.overlap_mismatched, + s.overlap_checked, + "overlap within + mismatched != checked: {s:?}" + ); + assert_eq!( + s.overlap_checked, s.te_superseded_by_eod, + "overlap_checked != te_superseded_by_eod: {s:?}" + ); + + for pair in build.rows.windows(2) { + assert!( + pair[0].session_date < pair[1].session_date, + "rows must be strictly ascending and unique: {} >= {}", + pair[0].session_date, + pair[1].session_date + ); + } + for row in &build.rows { + assert_eq!(row.pair, FX_PAIR_USDCAD); + assert_eq!(row.pair, "USDCAD"); + } +} + +fn assert_rows_bit_eq(a: &[Fx1dRow], b: &[Fx1dRow]) { + assert_eq!(a.len(), b.len()); + for (x, y) in a.iter().zip(b) { + assert_eq!(x.pair, y.pair); + assert_eq!(x.session_date, y.session_date); + assert_eq!(x.open.to_bits(), y.open.to_bits()); + assert_eq!(x.high.to_bits(), y.high.to_bits()); + assert_eq!(x.low.to_bits(), y.low.to_bits()); + assert_eq!(x.close.to_bits(), y.close.to_bits()); + assert_eq!(x.source, y.source); + } +} + +fn assert_stats_bit_eq(a: &Fx1dStats, b: &Fx1dStats) { + assert_eq!(a.eod, b.eod); + assert_eq!(a.te, b.te); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.eod_rows_out, b.eod_rows_out); + assert_eq!(a.te_rows_out, b.te_rows_out); + assert_eq!(a.te_superseded_by_eod, b.te_superseded_by_eod); + assert_eq!(a.overlap_checked, b.overlap_checked); + assert_eq!(a.overlap_within_tolerance, b.overlap_within_tolerance); + assert_eq!(a.overlap_mismatched, b.overlap_mismatched); + assert_eq!(a.max_overlap_rel.to_bits(), b.max_overlap_rel.to_bits()); +} + +#[test] +fn eod_precedence_te_gap_and_tail_fill_and_provenance_strings() { + assert_eq!(FX_PAIR_USDCAD, "USDCAD"); + assert_eq!(FX_OVERLAP_REL_TOLERANCE, 0.01); + assert_eq!(FxSource::EodCadForex.as_str(), "eod_cad_forex"); + assert_eq!(FxSource::TeUsdCad.as_str(), "te_usdcad"); + + let d1971 = day(1971, 1, 4); + let d_gap = day(2024, 11, 12); + let d_overlap = day(2025, 12, 31); + let d_tail1 = day(2026, 1, 2); + let d_tail2 = day(2026, 1, 5); + + let eod = [ + bar(d_overlap, 1.435, 1.445, 1.430, 1.440), + bar(d1971, 1.010, 1.015, 1.005, 1.012), + ]; + let te = [ + bar(d_tail2, 1.382, 1.390, 1.378, 1.385), + bar(d_overlap, 1.436, 1.446, 1.431, 1.441), + bar(d_gap, 1.395, 1.402, 1.390, 1.398), + bar(d_tail1, 1.380, 1.388, 1.376, 1.384), + ]; + + let built = build_fx_1d(&eod, &te); + assert_accounting_and_order(&built); + assert_eq!(built.rows.len(), 5); + assert_eq!(built.stats.eod_rows_out, 2); + assert_eq!(built.stats.te_rows_out, 3); + assert_eq!(built.stats.te_superseded_by_eod, 1); + + let dates: Vec = built.rows.iter().map(|r| r.session_date).collect(); + assert_eq!(dates, vec![d1971, d_gap, d_overlap, d_tail1, d_tail2]); + + assert_eq!(built.rows[0].source.as_str(), "eod_cad_forex"); + assert_eq!(built.rows[1].source.as_str(), "te_usdcad"); + assert_eq!(built.rows[2].source.as_str(), "eod_cad_forex"); + // Overlap date preserves EOD OHLC bit-for-bit. + assert_eq!(built.rows[2].open.to_bits(), eod[0].open.to_bits()); + assert_eq!(built.rows[2].high.to_bits(), eod[0].high.to_bits()); + assert_eq!(built.rows[2].low.to_bits(), eod[0].low.to_bits()); + assert_eq!(built.rows[2].close.to_bits(), eod[0].close.to_bits()); + assert_eq!(built.rows[3].source.as_str(), "te_usdcad"); + assert_eq!(built.rows[4].source.as_str(), "te_usdcad"); +} + +#[test] +fn bad_row_priority_and_duplicate_conflict_isolation_across_sources() { + let base = day(2024, 1, 2); + let eod = [ + // Invalid beats inconsistent when both apply + bar(base, f64::NAN, 1.0, 2.0, 1.5), + bar(base + 1, 0.0, 1.0, 2.0, 1.5), + bar(base + 2, -1.0, 1.5, 1.0, 1.2), + bar(base + 3, 1.2, f64::INFINITY, 1.1, 1.15), + bar(base + 4, 1.2, 1.3, f64::NEG_INFINITY, 1.25), + // Inconsistent OHLC + bar(base + 5, 1.2, 1.1, 1.3, 1.2), + bar(base + 6, 1.0, 1.3, 1.1, 1.2), + bar(base + 7, 1.4, 1.3, 1.1, 1.2), + bar(base + 8, 1.2, 1.3, 1.1, 1.0), + bar(base + 9, 1.2, 1.3, 1.1, 1.4), + // Identical duplicate collapses + flat(base + 10, 1.35), + flat(base + 10, 1.35), + // Conflicting duplicate group drops entirely in EOD; TE fills base+11 + flat(base + 11, 1.36), + flat(base + 11, 1.37), + flat(base + 11, 1.36), + ]; + let te = [ + flat(base + 11, 1.365), + // Conflicting TE group on base+10 drops cleanly without affecting EOD row + flat(base + 10, 1.35), + flat(base + 10, 1.40), + // Invalid TE row on base+12 + valid TE row on base+12 -> valid survives + bar(base + 12, -0.0, 1.4, 1.3, 1.35), + flat(base + 12, 1.355), + ]; + + let built = build_fx_1d(&eod, &te); + assert_accounting_and_order(&built); + assert_eq!(built.stats.eod.dropped_invalid_ohlc, 5); + assert_eq!(built.stats.eod.dropped_inconsistent_ohlc, 5); + assert_eq!(built.stats.eod.duplicate_collapsed, 1); + assert_eq!(built.stats.eod.duplicate_conflict_dropped, 3); + assert_eq!(built.stats.eod.rows_kept, 1); + + assert_eq!(built.stats.te.dropped_invalid_ohlc, 1); + assert_eq!(built.stats.te.dropped_inconsistent_ohlc, 0); + assert_eq!(built.stats.te.duplicate_collapsed, 0); + assert_eq!(built.stats.te.duplicate_conflict_dropped, 2); + assert_eq!(built.stats.te.rows_kept, 2); + + assert_eq!(built.rows.len(), 3); + assert_eq!(built.rows[0].session_date, base + 10); + assert_eq!(built.rows[0].source, FxSource::EodCadForex); + assert_eq!(built.rows[1].session_date, base + 11); + assert_eq!(built.rows[1].source, FxSource::TeUsdCad); + assert_eq!(built.rows[2].session_date, base + 12); + assert_eq!(built.rows[2].source, FxSource::TeUsdCad); +} + +#[test] +fn overlap_one_percent_boundary_is_inclusive_and_strictly_read_only() { + let base = day(2025, 3, 1); + let eod = [ + bar(base, 99.5, 101.0, 99.0, 100.0), // te = 101.0 -> exact +1% (within) + bar(base + 1, 99.5, 101.0, 99.0, 100.0), // te = 99.0 -> exact -1% (within) + bar(base + 2, 99.5, 101.0, 99.0, 100.0), // te = 101.01 -> +1.01% (mismatch) + bar(base + 3, 99.5, 101.0, 99.0, 100.0), // te = 98.99 -> -1.01% (mismatch) + bar(base + 4, 99.5, 101.0, 99.0, 100.0), // te = 200.0 -> +100% (mismatch) + ]; + let te = [ + flat(base, 101.0), + flat(base + 1, 99.0), + flat(base + 2, 101.01), + flat(base + 3, 98.99), + flat(base + 4, 200.0), + ]; + + let built = build_fx_1d(&eod, &te); + assert_accounting_and_order(&built); + assert_eq!(built.stats.overlap_checked, 5); + assert_eq!(built.stats.overlap_within_tolerance, 2); + assert_eq!(built.stats.overlap_mismatched, 3); + assert_eq!(built.stats.max_overlap_rel, 1.0); + + // Output rows must be bit-identical to EOD inputs. + for (row, orig) in built.rows.iter().zip(&eod) { + assert_eq!(row.source, FxSource::EodCadForex); + assert_eq!(row.open.to_bits(), orig.open.to_bits()); + assert_eq!(row.high.to_bits(), orig.high.to_bits()); + assert_eq!(row.low.to_bits(), orig.low.to_bits()); + assert_eq!(row.close.to_bits(), orig.close.to_bits()); + } +} + +#[test] +fn overlap_decimal_usdcad_quotes_at_one_percent_boundary_avoid_f64_false_mismatches() { + let base = day(2025, 5, 1); + let eod = [ + flat(base, 1.4000), // te = 1.4140 -> exact +1% (within despite f64 rounding) + flat(base + 1, 1.4000), // te = 1.3860 -> exact -1% (within) + flat(base + 2, 1.4000), // te = 1.4141 -> just above +1% (mismatch) + flat(base + 3, 1.4000), // te = 1.3859 -> just below -1% (mismatch) + ]; + let te = [ + flat(base, 1.4140), + flat(base + 1, 1.3860), + flat(base + 2, 1.4141), + flat(base + 3, 1.3859), + ]; + + let built = build_fx_1d(&eod, &te); + assert_accounting_and_order(&built); + assert_eq!(built.stats.overlap_checked, 4); + assert_eq!(built.stats.overlap_within_tolerance, 2); + assert_eq!(built.stats.overlap_mismatched, 2); + assert_eq!( + built.stats.max_overlap_rel.to_bits(), + ((1.4000_f64 - 1.4141_f64).abs() / 1.4000_f64).to_bits() + ); +} + +#[test] +fn permutation_invariance_holds_across_multiple_fixed_seed_shuffles() { + let base = day(2020, 1, 2); + let mut eod = Vec::new(); + let mut te = Vec::new(); + + for i in 0..80_i32 { + let d = base + i; + let close = 1.30 + (i % 15) as f64 * 0.005; + let b = bar(d, close - 0.002, close + 0.004, close - 0.004, close); + if i % 7 != 0 { + eod.push(b); + if i % 11 == 0 { + eod.push(b); // identical dup + } + if i % 19 == 0 { + let mut c = b; + c.close += 0.001; + eod.push(c); // conflicting dup + } + } + if i >= 40 { + let factor = if i % 9 == 0 { 1.03 } else { 1.002 }; + let tb = bar( + d, + b.open * factor, + b.high * factor, + b.low * factor, + b.close * factor, + ); + te.push(tb); + if i % 13 == 0 { + te.push(tb); // identical dup + } + if i % 23 == 0 { + let mut c = tb; + c.close += 0.001; + te.push(c); // conflicting dup + } + } + } + // Inject invalid and inconsistent rows into both sources. + eod.push(bar(base + 200, f64::NAN, 1.3, 1.2, 1.25)); + eod.push(bar(base + 201, 1.25, 1.20, 1.30, 1.25)); + te.push(bar(base + 202, -1.0, 1.3, 1.2, 1.25)); + te.push(bar(base + 203, 1.50, 1.35, 1.25, 1.30)); + + let baseline = build_fx_1d(&eod, &te); + assert_accounting_and_order(&baseline); + assert!(baseline.stats.overlap_checked > 0); + assert!(baseline.stats.overlap_within_tolerance > 0); + assert!(baseline.stats.overlap_mismatched > 0); + + let mut rng = Rng(0x570C_4B07_F81D_9999); + for _ in 0..16 { + let mut eod_perm = eod.clone(); + let mut te_perm = te.clone(); + shuffle(&mut eod_perm, &mut rng); + shuffle(&mut te_perm, &mut rng); + + let trial = build_fx_1d(&eod_perm, &te_perm); + assert_accounting_and_order(&trial); + assert_rows_bit_eq(&baseline.rows, &trial.rows); + assert_stats_bit_eq(&baseline.stats, &trial.stats); + } +} + +#[test] +fn fx_rate_on_or_before_enforces_no_lookahead_and_staleness_bounds() { + let fri = day(2025, 2, 14); + let sat = day(2025, 2, 15); + let sun = day(2025, 2, 16); + let holiday_mon = day(2025, 2, 17); // Family Day / Presidents' Day + let tue = day(2025, 2, 18); + let later = day(2025, 3, 1); + + let built = build_fx_1d( + &[flat(fri, 1.420), flat(tue, 1.425)], + &[flat(later, 1.440)], + ); + let rows = &built.rows; + + // Empty slice always None + assert_eq!(fx_rate_on_or_before(&[], fri, 10), None); + // Date before first row always None (never looks ahead) + assert_eq!(fx_rate_on_or_before(rows, fri - 1, u32::MAX), None); + // Exact hits with max_stale_days == 0 + assert_eq!(fx_rate_on_or_before(rows, fri, 0).map(|r| r.close), Some(1.420)); + assert_eq!(fx_rate_on_or_before(rows, tue, 0).map(|r| r.close), Some(1.425)); + assert_eq!(fx_rate_on_or_before(rows, later, 0).map(|r| r.close), Some(1.440)); + + // Long weekend carry-forward (Fri -> Sat, Sun, Mon) + assert_eq!(fx_rate_on_or_before(rows, sat, 3).map(|r| r.session_date), Some(fri)); + assert_eq!(fx_rate_on_or_before(rows, sun, 3).map(|r| r.session_date), Some(fri)); + assert_eq!(fx_rate_on_or_before(rows, holiday_mon, 3).map(|r| r.session_date), Some(fri)); + // Staleness limit exceeded on holiday_mon (age = 3 > 2) -> None, never looks ahead to Tue + assert_eq!(fx_rate_on_or_before(rows, holiday_mon, 2), None); + + // Exhaustive no-look-ahead sweep across the full range + for q in (fri - 5)..=(later + 5) { + if let Some(found) = fx_rate_on_or_before(rows, q, 4) { + assert!(found.session_date <= q, "look-ahead violation: {} > {}", found.session_date, q); + assert!(i64::from(q) - i64::from(found.session_date) <= 4); + } + } + + // Extreme i32 dates do not overflow + let extreme = build_fx_1d(&[flat(i32::MIN, 1.0), flat(0, 1.1)], &[]); + assert_eq!( + fx_rate_on_or_before(&extreme.rows, i32::MIN, 0).map(|r| r.session_date), + Some(i32::MIN) + ); + assert_eq!(fx_rate_on_or_before(&extreme.rows, i32::MAX, 5), None); + assert_eq!( + fx_rate_on_or_before(&extreme.rows, i32::MAX, u32::MAX).map(|r| r.session_date), + Some(0) + ); +} + +#[test] +fn run_fx_benchmark_is_deterministic_across_runs() { + let a = run_fx_benchmark(1_000); + let b = run_fx_benchmark(1_000); + assert_eq!(a.rows, 1_000); + assert_eq!(a.lookups, DEFAULT_FX_BENCH_LOOKUPS); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.lookup_hits, b.lookup_hits); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); +} diff --git a/tools/curate-etl/tests/fx_reference.rs b/tools/curate-etl/tests/fx_reference.rs new file mode 100644 index 00000000..45fe646b --- /dev/null +++ b/tools/curate-etl/tests/fx_reference.rs @@ -0,0 +1,427 @@ +//! QA differential and point-in-time tests for `build_fx_1d` / `fx_rate_on_or_before` (T-75 / M1.2e). +//! +//! Compares the optimized builder (sort + in-place compaction + two-pointer merge) against a +//! deliberately naive reference written only from the documented rules (`BTreeMap` grouping per +//! source, then a per-date merge), and the binary-search lookup against a linear scan. Also runs +//! truncation and poison tests: rows/lookups dated before a cutoff must not depend on any input +//! dated at or after it. All comparisons on `f64` fields are bitwise. + +use std::collections::BTreeMap; + +use curate_etl::{ + build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource, + FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD, +}; + +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 bar(session_date: i32, open: f64, high: f64, low: f64, close: f64) -> FxDailyBar { + FxDailyBar { + session_date, + open, + high, + low, + close, + } +} + +fn flat(session_date: i32, rate: f64) -> FxDailyBar { + bar(session_date, rate, rate, rate, rate) +} + +fn bits(b: &FxDailyBar) -> [u64; 4] { + [ + b.open.to_bits(), + b.high.to_bits(), + b.low.to_bits(), + b.close.to_bits(), + ] +} + +/// Reference per-source cleaning straight from the task rules. +fn reference_clean(input: &[FxDailyBar]) -> (BTreeMap, FxSourceStats) { + let mut stats = FxSourceStats { + rows_in: input.len(), + ..FxSourceStats::default() + }; + let mut groups: BTreeMap> = BTreeMap::new(); + for b in input { + let fields = [b.open, b.high, b.low, b.close]; + if fields.iter().any(|v| !v.is_finite() || *v <= 0.0) { + stats.dropped_invalid_ohlc += 1; + continue; + } + let inside = |v: f64| v >= b.low && v <= b.high; + if b.high < b.low || !inside(b.open) || !inside(b.close) { + stats.dropped_inconsistent_ohlc += 1; + continue; + } + groups.entry(b.session_date).or_default().push(*b); + } + let mut kept = BTreeMap::new(); + for (date, group) in groups { + if group.iter().all(|g| bits(g) == bits(&group[0])) { + stats.duplicate_collapsed += group.len() - 1; + kept.insert(date, group[0]); + } else { + stats.duplicate_conflict_dropped += group.len(); + } + } + stats.rows_kept = kept.len(); + (kept, stats) +} + +fn row(b: &FxDailyBar, source: FxSource) -> Fx1dRow { + Fx1dRow { + pair: FX_PAIR_USDCAD, + session_date: b.session_date, + open: b.open, + high: b.high, + low: b.low, + close: b.close, + source, + } +} + +/// Reference merge. The 1% check mirrors the documented few-ulp rounding slack; the boundary +/// semantics themselves are pinned by the hand-picked cases in `fx_contract.rs`. +fn reference_build(eod: &[FxDailyBar], te: &[FxDailyBar]) -> Fx1dBuild { + let (eod_kept, eod_stats) = reference_clean(eod); + let (te_kept, te_stats) = reference_clean(te); + let mut stats = Fx1dStats { + eod: eod_stats, + te: te_stats, + ..Fx1dStats::default() + }; + let mut dates: Vec = eod_kept.keys().chain(te_kept.keys()).copied().collect(); + dates.sort_unstable(); + dates.dedup(); + let mut rows = Vec::new(); + for d in dates { + match (eod_kept.get(&d), te_kept.get(&d)) { + (Some(e), Some(t)) => { + rows.push(row(e, FxSource::EodCadForex)); + stats.eod_rows_out += 1; + stats.te_superseded_by_eod += 1; + stats.overlap_checked += 1; + let rel = (e.close - t.close).abs() / e.close; + stats.max_overlap_rel = stats.max_overlap_rel.max(rel); + if rel <= FX_OVERLAP_REL_TOLERANCE + 4.0 * f64::EPSILON { + stats.overlap_within_tolerance += 1; + } else { + stats.overlap_mismatched += 1; + } + } + (Some(e), None) => { + rows.push(row(e, FxSource::EodCadForex)); + stats.eod_rows_out += 1; + } + (None, Some(t)) => { + rows.push(row(t, FxSource::TeUsdCad)); + stats.te_rows_out += 1; + } + (None, None) => unreachable!(), + } + } + stats.rows_out = rows.len(); + Fx1dBuild { rows, stats } +} + +fn assert_rows_bit_eq(actual: &[Fx1dRow], expected: &[Fx1dRow], ctx: &str) { + assert_eq!(actual.len(), expected.len(), "{ctx}: row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.pair, e.pair, "{ctx}: row {i} pair"); + assert_eq!(a.session_date, e.session_date, "{ctx}: row {i} date"); + assert_eq!(a.source, e.source, "{ctx}: row {i} source"); + assert_eq!(a.open.to_bits(), e.open.to_bits(), "{ctx}: row {i} open"); + assert_eq!(a.high.to_bits(), e.high.to_bits(), "{ctx}: row {i} high"); + assert_eq!(a.low.to_bits(), e.low.to_bits(), "{ctx}: row {i} low"); + assert_eq!(a.close.to_bits(), e.close.to_bits(), "{ctx}: row {i} close"); + } +} + +fn assert_stats_bit_eq(a: &Fx1dStats, e: &Fx1dStats, ctx: &str) { + assert_eq!(a.eod, e.eod, "{ctx}: eod stats"); + assert_eq!(a.te, e.te, "{ctx}: te stats"); + assert_eq!(a.rows_out, e.rows_out, "{ctx}: rows_out"); + assert_eq!(a.eod_rows_out, e.eod_rows_out, "{ctx}: eod_rows_out"); + assert_eq!(a.te_rows_out, e.te_rows_out, "{ctx}: te_rows_out"); + assert_eq!( + a.te_superseded_by_eod, e.te_superseded_by_eod, + "{ctx}: superseded" + ); + assert_eq!(a.overlap_checked, e.overlap_checked, "{ctx}: checked"); + assert_eq!( + a.overlap_within_tolerance, e.overlap_within_tolerance, + "{ctx}: within" + ); + assert_eq!( + a.overlap_mismatched, e.overlap_mismatched, + "{ctx}: mismatched" + ); + assert_eq!( + a.max_overlap_rel.to_bits(), + e.max_overlap_rel.to_bits(), + "{ctx}: max_overlap_rel" + ); +} + +/// Random bar over a small date window so duplicates, overlaps and gaps are frequent. Rates are +/// drawn from a coarse grid so bitwise-identical duplicates occur naturally. +fn random_bar(rng: &mut Rng, date_lo: i32, date_span: u64) -> FxDailyBar { + let d = date_lo + rng.below(date_span) as i32; + let grid = |rng: &mut Rng| 1.30 + rng.below(8) as f64 * 0.005; + let mut low = grid(rng); + let mut high = grid(rng); + if low > high { + std::mem::swap(&mut low, &mut high); + } + let pick = |rng: &mut Rng| if rng.below(2) == 0 { low } else { high }; + let mut b = bar(d, pick(rng), high, low, pick(rng)); + match rng.below(20) { + 0 => b.open = f64::NAN, + 1 => b.high = f64::INFINITY, + 2 => b.low = -0.0, + 3 => b.close = -1.0, + 4 => std::mem::swap(&mut b.high, &mut b.low), // possibly high < low + 5 => b.open = high + 0.01, // open above range + 6 => b.close = low - 0.01, // close below range + 7 => b.close *= 1.02, // maybe outside; also creates overlap mismatches + _ => {} + } + b +} + +#[test] +fn builder_matches_naive_reference_on_random_seeded_inputs() { + let mut rng = Rng(0xF1D0_C0DE_75FA_0001); + let mut coverage = Fx1dStats::default(); + for trial in 0..300 { + let n_eod = rng.below(60) as usize; + let n_te = rng.below(60) as usize; + let eod: Vec<_> = (0..n_eod).map(|_| random_bar(&mut rng, -10, 40)).collect(); + let te: Vec<_> = (0..n_te).map(|_| random_bar(&mut rng, 5, 50)).collect(); + let actual = build_fx_1d(&eod, &te); + let expected = reference_build(&eod, &te); + let ctx = format!("trial {trial}"); + assert_rows_bit_eq(&actual.rows, &expected.rows, &ctx); + assert_stats_bit_eq(&actual.stats, &expected.stats, &ctx); + let s = actual.stats; + coverage.eod.dropped_invalid_ohlc += s.eod.dropped_invalid_ohlc; + coverage.te.dropped_inconsistent_ohlc += s.te.dropped_inconsistent_ohlc; + coverage.eod.duplicate_collapsed += s.eod.duplicate_collapsed; + coverage.te.duplicate_conflict_dropped += s.te.duplicate_conflict_dropped; + coverage.overlap_within_tolerance += s.overlap_within_tolerance; + coverage.overlap_mismatched += s.overlap_mismatched; + coverage.te_rows_out += s.te_rows_out; + } + // The generator must actually exercise every rule, or the comparison proves little. + assert!(coverage.eod.dropped_invalid_ohlc > 0, "{coverage:?}"); + assert!(coverage.te.dropped_inconsistent_ohlc > 0, "{coverage:?}"); + assert!(coverage.eod.duplicate_collapsed > 0, "{coverage:?}"); + assert!(coverage.te.duplicate_conflict_dropped > 0, "{coverage:?}"); + assert!(coverage.overlap_within_tolerance > 0, "{coverage:?}"); + assert!(coverage.overlap_mismatched > 0, "{coverage:?}"); + assert!(coverage.te_rows_out > 0, "{coverage:?}"); +} + +#[test] +fn every_invalid_value_on_every_ohlc_field_counts_as_invalid() { + let bad_values = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, -0.0, -1.35]; + let mut eod = Vec::new(); + let mut d = 0; + for &v in &bad_values { + for field in 0..4 { + let mut b = bar(d, 1.35, 1.36, 1.34, 1.35); + match field { + 0 => b.open = v, + 1 => b.high = v, + 2 => b.low = v, + _ => b.close = v, + } + eod.push(b); + d += 1; + } + } + let built = build_fx_1d(&eod, &eod); + assert!(built.rows.is_empty()); + for s in [built.stats.eod, built.stats.te] { + assert_eq!(s.rows_in, 24); + assert_eq!(s.dropped_invalid_ohlc, 24); + assert_eq!(s.dropped_inconsistent_ohlc, 0); + assert_eq!(s.rows_kept, 0); + } + assert_eq!(built.stats.rows_out, 0); + assert_eq!(built.stats.overlap_checked, 0); +} + +#[test] +fn ohlc_exactly_on_range_bounds_is_kept() { + // open == low and close == high (and a fully flat bar) are consistent, not dropped. + let built = build_fx_1d( + &[bar(1, 1.30, 1.40, 1.30, 1.40), flat(2, 1.35)], + &[bar(3, 1.40, 1.40, 1.30, 1.30)], + ); + assert_eq!(built.stats.eod.rows_kept, 2); + assert_eq!(built.stats.te.rows_kept, 1); + assert_eq!(built.stats.eod.dropped_inconsistent_ohlc, 0); + assert_eq!(built.stats.te.dropped_inconsistent_ohlc, 0); + assert_eq!(built.rows.len(), 3); +} + +#[test] +fn identical_te_duplicates_on_overlap_date_supersede_once() { + let built = build_fx_1d( + &[flat(10, 1.35)], + &[flat(10, 1.351), flat(10, 1.351), flat(10, 1.351)], + ); + assert_eq!(built.stats.te.duplicate_collapsed, 2); + assert_eq!(built.stats.te.rows_kept, 1); + assert_eq!(built.stats.te_superseded_by_eod, 1); + assert_eq!(built.stats.overlap_checked, 1); + assert_eq!(built.rows.len(), 1); + assert_eq!(built.rows[0].source, FxSource::EodCadForex); + assert_eq!(built.rows[0].close.to_bits(), 1.35_f64.to_bits()); +} + +#[test] +fn te_only_and_eod_only_inputs_pass_through_with_correct_source() { + let te_only = build_fx_1d(&[], &[flat(3, 1.31), flat(1, 1.30)]); + assert_eq!(te_only.rows.len(), 2); + assert!(te_only.rows.iter().all(|r| r.source == FxSource::TeUsdCad)); + assert_eq!(te_only.rows[0].session_date, 1); + assert_eq!(te_only.stats.te_rows_out, 2); + assert_eq!(te_only.stats.eod_rows_out, 0); + assert_eq!(te_only.stats.max_overlap_rel, 0.0); + + let eod_only = build_fx_1d(&[flat(3, 1.31), flat(1, 1.30)], &[]); + assert!(eod_only + .rows + .iter() + .all(|r| r.source == FxSource::EodCadForex)); + assert_eq!(eod_only.stats.eod_rows_out, 2); +} + +fn linear_lookup(rows: &[Fx1dRow], date: i32, max_stale: u32) -> Option<&Fx1dRow> { + rows.iter() + .rev() + .find(|r| r.session_date <= date) + .filter(|r| i64::from(date) - i64::from(r.session_date) <= i64::from(max_stale)) +} + +#[test] +fn lookup_matches_linear_scan_on_random_series() { + let mut rng = Rng(0xF1D0_C0DE_75FA_0002); + for _ in 0..200 { + let n = rng.below(40) as usize; + let mut d = -500 + rng.below(1000) as i32; + let mut eod = Vec::with_capacity(n); + for _ in 0..n { + d += 1 + rng.below(6) as i32; + eod.push(flat(d, 1.30 + rng.below(100) as f64 * 0.001)); + } + let built = build_fx_1d(&eod, &[]); + for _ in 0..200 { + let q = -520 + rng.below(1400) as i32; + let stale = rng.below(8) as u32; + let got = fx_rate_on_or_before(&built.rows, q, stale); + assert_eq!( + got, + linear_lookup(&built.rows, q, stale), + "q={q} stale={stale}" + ); + if let Some(r) = got { + assert!(r.session_date <= q, "look-ahead: {} > {q}", r.session_date); + } + } + } +} + +/// Builds an input mix spanning dates 0..200 in both sources, with bad rows and duplicates. +fn mixed_inputs(seed: u64) -> (Vec, Vec) { + let mut rng = Rng(seed); + let eod = (0..300).map(|_| random_bar(&mut rng, 0, 150)).collect(); + let te = (0..300).map(|_| random_bar(&mut rng, 50, 150)).collect(); + (eod, te) +} + +#[test] +fn truncation_test_rows_before_cutoff_do_not_depend_on_later_inputs() { + let (eod, te) = mixed_inputs(0xF1D0_C0DE_75FA_0003); + let full = build_fx_1d(&eod, &te); + for cutoff in [0, 1, 49, 50, 51, 100, 149, 150, 199, 200] { + let eod_t: Vec<_> = eod + .iter() + .copied() + .filter(|b| b.session_date < cutoff) + .collect(); + let te_t: Vec<_> = te + .iter() + .copied() + .filter(|b| b.session_date < cutoff) + .collect(); + let truncated = build_fx_1d(&eod_t, &te_t); + let full_prefix: Vec = full + .rows + .iter() + .copied() + .filter(|r| r.session_date < cutoff) + .collect(); + assert_rows_bit_eq(&truncated.rows, &full_prefix, &format!("cutoff {cutoff}")); + for q in -5..cutoff { + assert_eq!( + fx_rate_on_or_before(&truncated.rows, q, 4), + fx_rate_on_or_before(&full.rows, q, 4), + "cutoff {cutoff} q {q}" + ); + } + } +} + +#[test] +fn poison_test_absurd_future_rows_never_move_earlier_rows_or_lookups() { + let (eod, te) = mixed_inputs(0xF1D0_C0DE_75FA_0004); + let clean = build_fx_1d(&eod, &te); + let cutoff = 120; + + let mut eod_p = eod.clone(); + let mut te_p = te.clone(); + for d in cutoff..cutoff + 100 { + // Absurd future "restatements": conflicting duplicates of existing dates, huge rates, + // and dates both sources share, all at or after the cutoff. + eod_p.push(flat(d, 1.0e9)); + te_p.push(flat(d, 1.0e-9)); + te_p.push(flat(d, 7.0)); + } + let poisoned = build_fx_1d(&eod_p, &te_p); + + let before = |b: &Fx1dBuild| -> Vec { + b.rows + .iter() + .copied() + .filter(|r| r.session_date < cutoff) + .collect() + }; + assert_rows_bit_eq(&before(&poisoned), &before(&clean), "poison prefix"); + for q in -5..cutoff { + assert_eq!( + fx_rate_on_or_before(&poisoned.rows, q, 10), + fx_rate_on_or_before(&clean.rows, q, 10), + "poison q {q}" + ); + } +} diff --git a/tools/curate-etl/tests/parquet_bars_contract.rs b/tools/curate-etl/tests/parquet_bars_contract.rs new file mode 100644 index 00000000..81e79314 --- /dev/null +++ b/tools/curate-etl/tests/parquet_bars_contract.rs @@ -0,0 +1,533 @@ +//! QA contract tests for the public `bars_1d` Parquet writer API (T-90 / M1.2i). +//! +//! Uses only the crate's public surface (`write_bars_1d_dataset`, `bars_1d_parquet_schema`, the +//! `curate-etl` binary) plus an independent Parquet column reader, guarding the +//! `design/DATA-CONTRACTS.md` §3A `bars_1d/year=YYYY/part.parquet` layout, refresh semantics, +//! string-interning row-group boundaries, in-process writer serialization and the +//! `bench-parquet-bars` CLI contract. + +use std::borrow::Cow; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Barrier}; +use std::thread; + +use curate_etl::{ + bars_1d_parquet_schema, write_bars_1d_dataset, ymd_to_epoch_days, Bars1dParquetRow, + Bars1dWriteOptions, ParquetBarsError, +}; +use parquet::basic::Compression; +use parquet::column::reader::ColumnReader; +use parquet::file::reader::{FileReader, SerializedFileReader}; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +/// Unique, self-cleaning temp dir under `std::env::temp_dir()`. +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let seq = SEQ.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "curate-etl-pq-contract-{tag}-{}-{seq}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp dir"); + Self(path) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn row(listing_id: i32, session_date: i32, close: f64, currency: &str) -> Bars1dParquetRow { + let ts = i64::from(session_date) * 86_400_000_000 + 20 * 3_600_000_000; + Bars1dParquetRow { + listing_id, + ts_micros: ts, + session_date, + open: close - 0.25, + high: close + 1.0, + low: close - 1.0, + close, + volume: 1_000.0 + f64::from(listing_id), + vwap: if listing_id % 2 == 0 { + None + } else { + Some(close + 0.125) + }, + currency: Cow::Owned(currency.to_string()), + source: Cow::Borrowed("eod_unadj"), + known_at_micros: ts + 900_000_000, + } +} + +fn part_path(out: &Path, year: i32) -> PathBuf { + out.join(format!("bars_1d/year={year:04}/part.parquet")) +} + +fn read_rows(path: &Path) -> Vec { + let reader = SerializedFileReader::new(File::open(path).expect("open")).expect("reader"); + let meta = reader.metadata(); + let mut out = Vec::new(); + for rg in 0..meta.num_row_groups() { + let n = meta.row_group(rg).num_rows() as usize; + let g = reader.get_row_group(rg).expect("row group"); + let col = |i: usize| g.get_column_reader(i).expect("column reader"); + let i32s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::Int32ColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected INT32"), + } + v + }; + let i64s = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::Int64ColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected INT64"), + } + v + }; + let f64s = |c: ColumnReader| -> Vec> { + let mut v = Vec::new(); + let mut defs = Vec::new(); + match c { + ColumnReader::DoubleColumnReader(mut r) => { + assert_eq!( + r.read_records(n, Some(&mut defs), None, &mut v).unwrap().0, + n + ); + } + _ => panic!("expected DOUBLE"), + } + if defs.is_empty() { + return v.into_iter().map(Some).collect(); + } + let mut it = v.into_iter(); + defs.iter() + .map(|&d| if d == 1 { it.next() } else { None }) + .collect() + }; + let strs = |c: ColumnReader| -> Vec { + let mut v = Vec::new(); + match c { + ColumnReader::ByteArrayColumnReader(mut r) => { + assert_eq!(r.read_records(n, None, None, &mut v).unwrap().0, n); + } + _ => panic!("expected BYTE_ARRAY"), + } + v.iter() + .map(|b| std::str::from_utf8(b.data()).expect("utf8").to_string()) + .collect() + }; + let req = |v: Vec>| -> Vec { + v.into_iter().map(|x| x.expect("required double")).collect() + }; + let lid = i32s(col(0)); + let ts = i64s(col(1)); + let sd = i32s(col(2)); + let open = req(f64s(col(3))); + let high = req(f64s(col(4))); + let low = req(f64s(col(5))); + let close = req(f64s(col(6))); + let volume = req(f64s(col(7))); + let vwap = f64s(col(8)); + let cur = strs(col(9)); + let src = strs(col(10)); + let ka = i64s(col(11)); + for i in 0..n { + out.push(Bars1dParquetRow { + listing_id: lid[i], + ts_micros: ts[i], + session_date: sd[i], + open: open[i], + high: high[i], + low: low[i], + close: close[i], + volume: volume[i], + vwap: vwap[i], + currency: Cow::Owned(cur[i].clone()), + source: Cow::Owned(src[i].clone()), + known_at_micros: ka[i], + }); + } + } + out +} + +fn assert_rows_bitwise(actual: &[Bars1dParquetRow], expected: &[Bars1dParquetRow]) { + assert_eq!(actual.len(), expected.len(), "row count"); + for (i, (a, e)) in actual.iter().zip(expected).enumerate() { + assert_eq!(a.listing_id, e.listing_id, "row {i} listing_id"); + assert_eq!(a.ts_micros, e.ts_micros, "row {i} ts"); + assert_eq!(a.session_date, e.session_date, "row {i} session_date"); + for (name, x, y) in [ + ("open", a.open, e.open), + ("high", a.high, e.high), + ("low", a.low, e.low), + ("close", a.close, e.close), + ("volume", a.volume, e.volume), + ] { + assert_eq!(x.to_bits(), y.to_bits(), "row {i} {name}"); + } + assert_eq!( + a.vwap.map(f64::to_bits), + e.vwap.map(f64::to_bits), + "row {i} vwap" + ); + assert_eq!(a.currency, e.currency, "row {i} currency"); + assert_eq!(a.source, e.source, "row {i} source"); + assert_eq!(a.known_at_micros, e.known_at_micros, "row {i} known_at"); + } +} + +/// Lists every file under `dir` (recursively), relative to `dir`, sorted. +fn list_files(dir: &Path) -> Vec { + fn walk(root: &Path, dir: &Path, out: &mut Vec) { + let Ok(entries) = fs::read_dir(dir) else { + return; + }; + for entry in entries { + let path = entry.expect("dir entry").path(); + if path.is_dir() { + walk(root, &path, out); + } else { + out.push(path.strip_prefix(root).unwrap().display().to_string()); + } + } + } + let mut out = Vec::new(); + walk(dir, dir, &mut out); + out.sort(); + out +} + +#[test] +fn file_schema_equals_public_schema_and_contract_column_order() { + let tmp = TempDir::new("schema"); + let rows = vec![row(1, day(2024, 3, 1), 10.0, "USD")]; + write_bars_1d_dataset(&tmp.0, &rows, Bars1dWriteOptions::default()).unwrap(); + + let reader = SerializedFileReader::new(File::open(part_path(&tmp.0, 2024)).unwrap()).unwrap(); + let meta = reader.metadata(); + let file_schema = meta.file_metadata().schema(); + let public_schema = bars_1d_parquet_schema().unwrap(); + assert_eq!( + file_schema, + public_schema.as_ref(), + "on-disk schema == public schema" + ); + + let names: Vec<&str> = file_schema.get_fields().iter().map(|f| f.name()).collect(); + assert_eq!( + names, + [ + "listing_id", + "ts", + "session_date", + "open", + "high", + "low", + "close", + "volume", + "vwap", + "currency", + "source", + "known_at" + ] + ); + for rg in meta.row_groups() { + for c in rg.columns() { + assert!( + matches!(c.compression(), Compression::ZSTD(_)), + "{} not ZSTD", + c.column_path() + ); + } + } +} + +#[test] +fn multi_year_refresh_publishes_new_values_bitwise_not_stale_rows() { + // Reviewer gap: old and new partitions have equal row counts, so only a value check proves + // the refresh actually replaced the stale bar. + let tmp = TempDir::new("refresh"); + let old = vec![ + row(1, day(2023, 6, 1), 10.0, "USD"), + row(1, day(2024, 6, 3), 20.0, "USD"), + row(2, day(2022, 6, 1), 30.0, "CAD"), + ]; + write_bars_1d_dataset(&tmp.0, &old, Bars1dWriteOptions::default()).unwrap(); + let untouched_2022 = fs::read(part_path(&tmp.0, 2022)).unwrap(); + + let new = vec![ + row(1, day(2023, 6, 1), 11.5, "USD"), + row(1, day(2024, 6, 3), 21.5, "CAD"), + row(1, day(2025, 1, 2), 31.5, "USD"), + ]; + let stats = write_bars_1d_dataset(&tmp.0, &new, Bars1dWriteOptions::default()).unwrap(); + assert_eq!(stats.rows_written, 3); + assert_eq!(stats.files_written, 3); + + assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2023)), &new[0..1]); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2024)), &new[1..2]); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2025)), &new[2..3]); + assert_eq!(fs::read(part_path(&tmp.0, 2022)).unwrap(), untouched_2022); + assert_eq!( + list_files(&tmp.0.join("bars_1d")), + [ + "year=2022/part.parquet", + "year=2023/part.parquet", + "year=2024/part.parquet", + "year=2025/part.parquet" + ] + ); +} + +#[test] +fn rows_interleaved_across_years_keep_listing_then_date_order_per_file() { + let tmp = TempDir::new("order"); + let rows = vec![ + row(1, day(2023, 12, 29), 1.0, "USD"), + row(1, day(2024, 1, 2), 2.0, "USD"), + row(1, day(2024, 2, 29), 3.0, "USD"), + row(7, day(2023, 12, 31), 4.0, "CAD"), + row(7, day(2024, 1, 1), 5.0, "CAD"), + row(9, day(2024, 12, 31), 6.0, "USD"), + ]; + let stats = write_bars_1d_dataset(&tmp.0, &rows, Bars1dWriteOptions::default()).unwrap(); + + assert_eq!(stats.rows_by_year.get(&2023), Some(&2)); + assert_eq!(stats.rows_by_year.get(&2024), Some(&4)); + let y23: Vec<_> = vec![rows[0].clone(), rows[3].clone()]; + let y24: Vec<_> = vec![ + rows[1].clone(), + rows[2].clone(), + rows[4].clone(), + rows[5].clone(), + ]; + assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2023)), &y23); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2024)), &y24); +} + +#[test] +fn session_date_days_since_epoch_round_trip_including_pre_epoch_and_leap_day() { + let tmp = TempDir::new("dates"); + let rows = vec![ + row(1, day(1969, 12, 31), 1.0, "USD"), + row(1, day(1970, 1, 1), 2.0, "USD"), + row(1, day(2000, 2, 29), 3.0, "USD"), + ]; + assert_eq!(rows[0].session_date, -1); + assert_eq!(rows[1].session_date, 0); + let stats = write_bars_1d_dataset(&tmp.0, &rows, Bars1dWriteOptions::default()).unwrap(); + assert_eq!( + stats.rows_by_year.keys().copied().collect::>(), + [1969, 1970, 2000] + ); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 1969)), &rows[0..1]); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 1970)), &rows[1..2]); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2000)), &rows[2..3]); +} + +#[test] +fn string_interner_crossing_linear_limit_and_row_group_resets_round_trip() { + // 12 distinct currencies (crosses the writer's small linear-intern threshold mid-group), + // revisiting earlier values after the threshold, across 3 row groups so per-group + // interner resets are exercised. + let tmp = TempDir::new("intern"); + let currencies: Vec = (0..12).map(|i| format!("C{i:02}")).collect(); + let mut rows = Vec::new(); + let base = day(2021, 1, 4); + for i in 0..30i32 { + let idx = ((i * 7) % 12) as usize; + let mut r = row(1, base + i, 100.0 + f64::from(i), ¤cies[idx]); + r.source = Cow::Owned(format!("src{}", (i * 5) % 11)); + rows.push(r); + } + let opts = Bars1dWriteOptions { + row_group_rows: 11, + ..Bars1dWriteOptions::default() + }; + let stats = write_bars_1d_dataset(&tmp.0, &rows, opts).unwrap(); + assert_eq!(stats.row_groups_written, 3); + assert_rows_bitwise(&read_rows(&part_path(&tmp.0, 2021)), &rows); +} + +#[test] +fn concurrent_in_process_writers_publish_one_complete_generation_and_no_transients() { + let tmp = TempDir::new("concurrent"); + let out = Arc::new(tmp.0.clone()); + let make = |close_base: f64, cur: &'static str| -> Vec { + (0..2_000) + .map(|i| { + row( + 1 + i / 400, + day(2020, 1, 1) + (i % 400), + close_base + f64::from(i), + cur, + ) + }) + .collect() + }; + let gens = Arc::new([make(1_000.0, "USD"), make(5_000.0, "CAD")]); + let barrier = Arc::new(Barrier::new(2)); + let handles: Vec<_> = (0..2) + .map(|g| { + let (out, gens, barrier) = (out.clone(), gens.clone(), barrier.clone()); + thread::spawn(move || { + barrier.wait(); + let opts = Bars1dWriteOptions { + row_group_rows: 97, + ..Bars1dWriteOptions::default() + }; + write_bars_1d_dataset(out.as_path(), &gens[g], opts) + }) + }) + .collect(); + for h in handles { + let stats = h.join().expect("writer thread").expect("writer result"); + assert_eq!(stats.rows_written, 2_000); + } + + // Every year file must come entirely from one generation (no mixed / truncated output). + for year in [2020, 2021] { + let got = read_rows(&part_path(&tmp.0, year)); + let from = |g: usize| -> Vec { + let (lo, hi) = (day(year, 1, 1), day(year + 1, 1, 1)); + gens[g] + .iter() + .filter(|r| r.session_date >= lo && r.session_date < hi) + .cloned() + .collect() + }; + let g = if got.first().map(|r| r.currency.as_ref()) == Some("USD") { + 0 + } else { + 1 + }; + assert_rows_bitwise(&got, &from(g)); + } + assert_eq!( + list_files(&tmp.0.join("bars_1d")), + ["year=2020/part.parquet", "year=2021/part.parquet"] + ); +} + +#[test] +fn unsorted_row_after_several_years_opened_keeps_existing_partitions_and_leaves_no_files() { + let tmp = TempDir::new("midfail"); + let seed = vec![ + row(1, day(2019, 5, 1), 9.0, "USD"), + row(1, day(2020, 5, 1), 9.5, "USD"), + ]; + write_bars_1d_dataset(&tmp.0, &seed, Bars1dWriteOptions::default()).unwrap(); + let before_2019 = fs::read(part_path(&tmp.0, 2019)).unwrap(); + let before_2020 = fs::read(part_path(&tmp.0, 2020)).unwrap(); + + let bad = vec![ + row(1, day(2019, 5, 1), 1.0, "USD"), + row(1, day(2020, 5, 1), 2.0, "USD"), + row(1, day(2021, 5, 3), 3.0, "USD"), + row(1, day(2021, 5, 2), 4.0, "USD"), // goes backwards + row(2, day(2022, 5, 2), 5.0, "USD"), + ]; + let err = write_bars_1d_dataset(&tmp.0, &bad, Bars1dWriteOptions::default()).unwrap_err(); + match &err { + ParquetBarsError::UnsortedInput { + prev_listing_id, + prev_session_date, + listing_id, + session_date, + } => { + assert_eq!((*prev_listing_id, *prev_session_date), (1, day(2021, 5, 3))); + assert_eq!((*listing_id, *session_date), (1, day(2021, 5, 2))); + } + other => panic!("expected UnsortedInput, got {other:?}"), + } + let msg = err.to_string(); + assert!( + msg.contains(&day(2021, 5, 3).to_string()) && msg.contains(&day(2021, 5, 2).to_string()) + ); + + assert_eq!(fs::read(part_path(&tmp.0, 2019)).unwrap(), before_2019); + assert_eq!(fs::read(part_path(&tmp.0, 2020)).unwrap(), before_2020); + assert_eq!( + list_files(&tmp.0.join("bars_1d")), + ["year=2019/part.parquet", "year=2020/part.parquet"], + "no staging, backup, lock or new partition files may remain" + ); +} + +#[test] +fn io_error_exposes_source_chain_and_path() { + let tmp = TempDir::new("ioerr"); + let file_as_out = tmp.0.join("not-a-dir"); + fs::write(&file_as_out, b"x").unwrap(); + let err = write_bars_1d_dataset( + &file_as_out, + &[row(1, day(2024, 1, 2), 1.0, "USD")], + Bars1dWriteOptions::default(), + ) + .unwrap_err(); + assert!(matches!(err, ParquetBarsError::Io { .. }), "got {err:?}"); + assert!(std::error::Error::source(&err).is_some()); + assert!(err.to_string().contains("not-a-dir")); + assert_eq!(fs::read(&file_as_out).unwrap(), b"x"); +} + +#[test] +fn bench_parquet_bars_cli_prints_metrics_and_removes_its_temp_dir() { + let tmp = TempDir::new("cli"); + let out = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(["bench-parquet-bars", "20000"]) + .env("TMPDIR", &tmp.0) + .output() + .expect("spawn curate-etl"); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + out.status.success(), + "stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + for needle in [ + "curate-etl bench-parquet-bars", + "rows=20000", + "read_back_rows=20000", + "rows/s", + "MB/s", + "bytes/row", + "compression=", + ] { + assert!(stdout.contains(needle), "missing '{needle}' in:\n{stdout}"); + } + let leftovers: Vec<_> = fs::read_dir(&tmp.0).unwrap().collect(); + assert!( + leftovers.is_empty(), + "benchmark left files in TMPDIR: {leftovers:?}" + ); + + let bad = Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(["bench-parquet-bars", "0"]) + .env("TMPDIR", &tmp.0) + .output() + .expect("spawn curate-etl"); + assert!(!bad.status.success()); + assert!(String::from_utf8_lossy(&bad.stderr).contains("bench-parquet-bars")); +} diff --git a/tools/curate-etl/tests/provider_mapping_contract.rs b/tools/curate-etl/tests/provider_mapping_contract.rs new file mode 100644 index 00000000..c4a7a125 --- /dev/null +++ b/tools/curate-etl/tests/provider_mapping_contract.rs @@ -0,0 +1,319 @@ +//! Public-API and CLI contract tests for `curate_etl::provider_mapping` (M1.2h). + +use std::process::{Command, Output}; + +use curate_etl::{ + ymd_to_epoch_days, MappingRange, ProviderMappingCursor, ProviderMappingError, + ProviderMappingRow, ProviderMappingTable, +}; + +fn 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 run_cli(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_curate-etl")) + .args(args) + .output() + .expect("spawn curate-etl binary") +} + +struct ContractRng(u64); + +impl ContractRng { + fn new(seed: u64) -> Self { + Self(seed) + } + + 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, items: &mut [T]) { + for i in (1..items.len()).rev() { + let j = (self.next_u64() % (i as u64 + 1)) as usize; + items.swap(i, j); + } + } +} + +/// Brute-force linear reference oracle over raw rows. +fn brute_force_resolve( + rows: &[ProviderMappingRow], + source: &str, + source_id: &str, + bar_date: i32, +) -> Option { + let mut found = None; + for r in rows { + if r.source == source + && r.source_id == source_id + && bar_date >= r.valid_from + && r.valid_to.is_none_or(|to| bar_date <= to) + { + assert!( + found.is_none(), + "test fixture must not contain overlapping ranges" + ); + found = Some(r.listing_id); + } + } + found +} + +#[test] +fn fb_us_ticker_reuse_contract_and_verbatim_whitespace_ids() { + let d_2012_05_17 = ymd_to_epoch_days(2012, 5, 17).unwrap(); + let d_2012_05_18 = ymd_to_epoch_days(2012, 5, 18).unwrap(); + let d_2022_06_08 = ymd_to_epoch_days(2022, 6, 8).unwrap(); + let d_2022_06_09 = ymd_to_epoch_days(2022, 6, 9).unwrap(); + let d_2023_06_01 = ymd_to_epoch_days(2023, 6, 1).unwrap(); + let d_2025_01_02 = ymd_to_epoch_days(2025, 1, 2).unwrap(); + let d_2026_05_01 = ymd_to_epoch_days(2026, 5, 1).unwrap(); + + let table = ProviderMappingTable::from_rows([ + row("eod", "FB.US", d_2012_05_18, Some(d_2022_06_08), 1), + row("eod", "FB.US", d_2025_01_02, None, 2), + row("eod", " FB.US ", d_2012_05_18, None, 99), + row("qm", "FB.US", d_2012_05_18, None, 77), + ]) + .unwrap(); + + assert_eq!(table.len(), 3); + assert_eq!(table.range_count(), 4); + + assert_eq!(table.resolve("eod", "FB.US", d_2012_05_17), None); + assert_eq!(table.resolve("eod", "FB.US", d_2012_05_18), Some(1)); + assert_eq!(table.resolve("eod", "FB.US", d_2022_06_08), Some(1)); + assert_eq!(table.resolve("eod", "FB.US", d_2022_06_09), None); + assert_eq!(table.resolve("eod", "FB.US", d_2023_06_01), None); + assert_eq!(table.resolve("eod", "FB.US", d_2025_01_02), Some(2)); + assert_eq!(table.resolve("eod", "FB.US", d_2026_05_01), Some(2)); + + // Verbatim whitespace preservation and source isolation. + assert_eq!(table.resolve("eod", " FB.US ", d_2023_06_01), Some(99)); + assert_eq!(table.resolve("qm", "FB.US", d_2023_06_01), Some(77)); + assert_eq!(table.resolve("ib", "FB.US", d_2023_06_01), None); + assert_eq!(table.resolve("eod", "FB.US ", d_2023_06_01), None); +} + +#[test] +fn typed_error_variants_and_adjacent_range_acceptance() { + let d1 = ymd_to_epoch_days(2020, 1, 1).unwrap(); + let d2 = ymd_to_epoch_days(2021, 1, 1).unwrap(); + + assert_eq!( + ProviderMappingTable::from_rows([row(" ", "A", d1, None, 1)]).unwrap_err(), + ProviderMappingError::EmptySource + ); + assert_eq!( + ProviderMappingTable::from_rows([row("eod", "\t", d1, None, 1)]).unwrap_err(), + ProviderMappingError::EmptySourceId { + source: "eod".to_string() + } + ); + assert_eq!( + ProviderMappingTable::from_rows([row("eod", "A", d1, None, 0)]).unwrap_err(), + ProviderMappingError::InvalidListingId { + source: "eod".to_string(), + source_id: "A".to_string(), + listing_id: 0, + } + ); + assert_eq!( + ProviderMappingTable::from_rows([row("eod", "A", d2, Some(d1), 1)]).unwrap_err(), + ProviderMappingError::InvalidRange { + source: "eod".to_string(), + source_id: "A".to_string(), + valid_from: d2, + valid_to: d1, + } + ); + assert_eq!( + ProviderMappingTable::from_rows([ + row("eod", "A", d1, Some(d2), 1), + row("eod", "A", d1, Some(d2), 1), + ]) + .unwrap_err(), + ProviderMappingError::DuplicateValidFrom { + source: "eod".to_string(), + source_id: "A".to_string(), + valid_from: d1, + } + ); + assert_eq!( + ProviderMappingTable::from_rows([ + row("eod", "A", d1, None, 1), + row("eod", "A", d2, None, 2), + ]) + .unwrap_err(), + ProviderMappingError::OverlappingRanges { + source: "eod".to_string(), + source_id: "A".to_string(), + first_valid_from: d1, + first_valid_to: None, + second_valid_from: d2, + second_valid_to: None, + } + ); + + // Adjacent ranges (valid_to = d1, next valid_from = d1 + 1) succeed. + let adjacent = ProviderMappingTable::from_rows([ + row("eod", "A", d1 - 10, Some(d1), 1), + row("eod", "A", d1 + 1, Some(d2), 2), + ]) + .unwrap(); + assert_eq!( + adjacent.ranges_for("eod", "A"), + &[ + MappingRange { + valid_from: d1 - 10, + valid_to: Some(d1), + listing_id: 1, + }, + MappingRange { + valid_from: d1 + 1, + valid_to: Some(d2), + listing_id: 2, + }, + ] + ); + + // Reversing a mixed-invalid batch must return the exact same typed error. + let mixed = vec![ + row("eod", " ", d1, None, 1), + row("qm", "B", d2, Some(d1), 2), + ]; + let mut mixed_rev = mixed.clone(); + mixed_rev.reverse(); + let err_fwd = ProviderMappingTable::from_rows(mixed).unwrap_err(); + let err_rev = ProviderMappingTable::from_rows(mixed_rev).unwrap_err(); + assert_eq!( + err_fwd, + ProviderMappingError::EmptySourceId { + source: "eod".to_string() + } + ); + assert_eq!(err_fwd, err_rev); +} + +#[test] +fn brute_force_oracle_cursor_equivalence_and_permutation_invariance() { + let mut rng = ContractRng::new(0x1234_5678_9ABC_DEF0); + let sources = ["eod", "qm", "ib", "ceo"]; + let mut rows = Vec::new(); + let mut keys = Vec::new(); + let mut listing_id = 100i32; + + for k in 0..40usize { + let src = sources[k % sources.len()]; + let id = format!("T{k:03}"); + keys.push((src, id.clone())); + + let n_ranges = 1 + (k % 3); + let mut start = 15_000 + (rng.next_u64() % 100) as i32; + for r in 0..n_ranges { + let is_last = r + 1 == n_ranges; + let len = (rng.next_u64() % 40) as i32; + let valid_to = if is_last && (k % 2 == 0) { + None + } else { + Some(start + len) + }; + rows.push(row(src, &id, start, valid_to, listing_id)); + listing_id += 1; + let gap = 1 + (rng.next_u64() % 20) as i32; + start = start + len + gap; + } + } + + let mut permuted = rows.clone(); + rng.shuffle(&mut permuted); + + let table_a = ProviderMappingTable::from_rows(rows.clone()).unwrap(); + let table_b = ProviderMappingTable::from_rows(permuted).unwrap(); + assert_eq!(table_a.len(), table_b.len()); + assert_eq!(table_a.range_count(), table_b.range_count()); + + for (src, id) in &keys { + assert_eq!(table_a.ranges_for(src, id), table_b.ranges_for(src, id)); + let mut cursor = ProviderMappingCursor::new(table_a.ranges_for(src, id)); + for d in 14_990..=15_350 { + let expected = brute_force_resolve(&rows, src, id, d); + assert_eq!(table_a.resolve(src, id, d), expected); + assert_eq!(table_b.resolve(src, id, d), expected); + assert_eq!(cursor.resolve(d), expected); + } + } +} + +#[test] +fn cli_bench_provider_mapping_is_deterministic_and_rejects_invalid_args() { + let a = run_cli(&["bench-provider-mapping", "50000"]); + let b = run_cli(&["bench-provider-mapping", "50000"]); + assert!(a.status.success(), "{}", String::from_utf8_lossy(&a.stderr)); + assert!(b.status.success(), "{}", String::from_utf8_lossy(&b.stderr)); + assert!(a.stderr.is_empty()); + assert!(b.stderr.is_empty()); + + let out_a = String::from_utf8_lossy(&a.stdout); + let out_b = String::from_utf8_lossy(&b.stdout); + assert!(out_a.contains("curate-etl bench-provider-mapping"), "{out_a}"); + assert!(out_a.contains("keys=60000 "), "{out_a}"); + assert!(out_a.contains("rows/s"), "{out_a}"); + assert!(out_a.contains("lookups=50000 "), "{out_a}"); + assert!(out_a.contains("hits="), "{out_a}"); + assert!(out_a.contains("misses="), "{out_a}"); + assert!(out_a.contains("lookups/s"), "{out_a}"); + assert!(out_a.contains("ns/lookup"), "{out_a}"); + assert!(out_a.contains("checksum=0x"), "{out_a}"); + + let field = |s: &str, prefix: &str| { + s.split_whitespace() + .find(|t| t.starts_with(prefix)) + .map(str::to_owned) + }; + let checksum_a = field(&out_a, "checksum="); + let checksum_b = field(&out_b, "checksum="); + assert!(checksum_a.is_some(), "{out_a}"); + assert_eq!(checksum_a, checksum_b); + assert_eq!(field(&out_a, "hits="), field(&out_b, "hits=")); + assert_eq!(field(&out_a, "misses="), field(&out_b, "misses=")); + + // Help mentions bench-provider-mapping. + let help = run_cli(&["--help"]); + assert!(help.status.success()); + assert!(String::from_utf8_lossy(&help.stdout).contains("bench-provider-mapping")); + + // Invalid invocations exit 1 with stderr usage mentioning bench-provider-mapping. + for bad in [ + &["bench-provider-mapping", "0"][..], + &["bench-provider-mapping", "-5"][..], + &["bench-provider-mapping", "abc"][..], + &["bench-provider-mapping", "10", "20"][..], + ] { + let out = run_cli(bad); + assert!(!out.status.success(), "{bad:?} should fail"); + assert_eq!(out.status.code(), Some(1), "{bad:?}"); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("error:"), "{bad:?}: {err}"); + assert!(err.contains("bench-provider-mapping"), "{bad:?}: {err}"); + assert!(out.stdout.is_empty(), "{bad:?} wrote to stdout"); + } +} diff --git a/tools/curate-etl/tests/provider_mapping_reference.rs b/tools/curate-etl/tests/provider_mapping_reference.rs new file mode 100644 index 00000000..ef7d42d9 --- /dev/null +++ b/tools/curate-etl/tests/provider_mapping_reference.rs @@ -0,0 +1,442 @@ +//! QA differential and validation-oracle tests for `ProviderMappingTable` / +//! `ProviderMappingCursor` (T-81 / M1.2h). +//! +//! Compares the optimized table (source-partitioned `HashMap` index + contiguous range arena + +//! binary search) against a naive linear scan over the raw rows, and `from_rows` validation +//! against a brute-force validator written only from the documented rules. Every generator is +//! seeded, so failures reproduce from the printed seed. + +use std::collections::BTreeMap; + +use curate_etl::bench::{run_provider_mapping_benchmark, PROVIDER_MAPPING_BENCH_KEY_COUNT}; +use curate_etl::{ + MappingRange, ProviderMappingCursor, ProviderMappingError, ProviderMappingRow, + ProviderMappingTable, +}; + +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, items: &mut [T]) { + for i in (1..items.len()).rev() { + let j = self.below(i as u64 + 1) as usize; + items.swap(i, j); + } + } +} + +fn 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, + } +} + +/// Linear-scan oracle over raw (already valid, non-overlapping) rows. +fn naive_resolve( + rows: &[ProviderMappingRow], + source: &str, + source_id: &str, + d: i32, +) -> Option { + rows.iter() + .find(|r| { + r.source == source + && r.source_id == source_id + && d >= r.valid_from + && r.valid_to.is_none_or(|to| d <= to) + }) + .map(|r| r.listing_id) +} + +/// Variant-only classification of a validation outcome. +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +enum Outcome { + Ok, + EmptySource, + EmptySourceId, + InvalidListingId, + InvalidRange, + DuplicateValidFrom, + OverlappingRanges, +} + +fn classify(result: &Result) -> Outcome { + match result { + Ok(_) => Outcome::Ok, + Err(ProviderMappingError::EmptySource) => Outcome::EmptySource, + Err(ProviderMappingError::EmptySourceId { .. }) => Outcome::EmptySourceId, + Err(ProviderMappingError::InvalidListingId { .. }) => Outcome::InvalidListingId, + Err(ProviderMappingError::InvalidRange { .. }) => Outcome::InvalidRange, + Err(ProviderMappingError::DuplicateValidFrom { .. }) => Outcome::DuplicateValidFrom, + Err(ProviderMappingError::OverlappingRanges { .. }) => Outcome::OverlappingRanges, + } +} + +/// Brute-force validator from the documented rules: row-level errors take precedence (ranked +/// EmptySource < EmptySourceId < InvalidListingId < InvalidRange); otherwise the first key in +/// `(source, source_id)` order with a same-`valid_from` pair reports a duplicate, or with any +/// pairwise-intersecting inclusive ranges reports an overlap. +fn oracle_validate(rows: &[ProviderMappingRow]) -> Outcome { + let mut best: Option = None; + let rank = |o: Outcome| o as u8; + for r in rows { + let o = if r.source.trim().is_empty() { + Outcome::EmptySource + } else if r.source_id.trim().is_empty() { + Outcome::EmptySourceId + } else if r.listing_id <= 0 { + Outcome::InvalidListingId + } else if r.valid_to.is_some_and(|to| to < r.valid_from) { + Outcome::InvalidRange + } else { + continue; + }; + if best.is_none_or(|b| rank(o) < rank(b)) { + best = Some(o); + } + } + if let Some(b) = best { + return b; + } + + let mut by_key: BTreeMap<(&str, &str), Vec<&ProviderMappingRow>> = BTreeMap::new(); + for r in rows { + by_key + .entry((r.source.as_str(), r.source_id.as_str())) + .or_default() + .push(r); + } + for key_rows in by_key.values() { + let mut dup = false; + let mut overlap = false; + for (i, a) in key_rows.iter().enumerate() { + for b in &key_rows[i + 1..] { + if a.valid_from == b.valid_from { + dup = true; + } + let a_to = a.valid_to.map_or(i64::MAX, i64::from); + let b_to = b.valid_to.map_or(i64::MAX, i64::from); + let lo = i64::from(a.valid_from.max(b.valid_from)); + if lo <= a_to.min(b_to) { + overlap = true; + } + } + } + // Same valid_from always overlaps too; the first sorted violating pair decides which + // error is reported, so only assert that one of them is. + if dup || overlap { + return if dup && !overlap_without_dup(key_rows) { + Outcome::DuplicateValidFrom + } else { + Outcome::OverlappingRanges + }; + } + } + Outcome::Ok +} + +/// For a key with duplicates, decides which error the documented sorted-adjacent scan reports +/// first: walk rows sorted by `(valid_from, valid_to)` and return `true` if an overlap between +/// distinct `valid_from`s is met before any same-`valid_from` pair. +fn overlap_without_dup(key_rows: &[&ProviderMappingRow]) -> bool { + let mut sorted: Vec<&ProviderMappingRow> = key_rows.to_vec(); + sorted.sort_by_key(|r| { + ( + r.valid_from, + r.valid_to.map_or(i64::MAX, i64::from), + r.listing_id, + ) + }); + for pair in sorted.windows(2) { + if pair[0].valid_from == pair[1].valid_from { + return false; + } + let overlaps = pair[0].valid_to.is_none_or(|to| to >= pair[1].valid_from); + if overlaps { + return true; + } + } + false +} + +/// Generates a valid table: `n_sources` sources, single-day / adjacent / gapped / open-ended +/// ranges. Returns rows plus every `(source, source_id)` key (and a few absent probes). +fn gen_valid(rng: &mut Rng, n_sources: usize) -> (Vec, Vec<(String, String)>) { + let mut rows = Vec::new(); + let mut keys = Vec::new(); + let mut listing = 1i32; + for s in 0..n_sources { + let source = format!("src{s:02}"); + let n_keys = 1 + rng.below(6) as usize; + for k in 0..n_keys { + let id = format!("ID{k}"); + keys.push((source.clone(), id.clone())); + let n_ranges = 1 + rng.below(4) as usize; + let mut start = 1_000 + rng.below(50) as i32; + for r in 0..n_ranges { + let is_last = r + 1 == n_ranges; + let len = match rng.below(3) { + 0 => 0, // single-day range + _ => rng.below(30) as i32, + }; + let valid_to = if is_last && rng.below(2) == 0 { + None + } else { + Some(start + len) + }; + rows.push(row(&source, &id, start, valid_to, listing)); + listing += 1; + let gap = if rng.below(2) == 0 { + 1 + } else { + 2 + rng.below(15) as i32 + }; + start += len + gap; + } + } + } + keys.push(("src00".to_string(), "MISSING".to_string())); + keys.push(("nosrc".to_string(), "ID0".to_string())); + (rows, keys) +} + +#[test] +fn resolve_and_cursor_match_linear_scan_oracle_across_seeds_and_source_counts() { + for seed in 0..60u64 { + let mut rng = Rng(0x0A11_CE00_0000_0000 ^ seed); + // Alternate between the linear source scan (<= 8) and binary search (> 8) paths. + let n_sources = if seed % 2 == 0 { + 1 + rng.below(8) as usize + } else { + 9 + rng.below(6) as usize + }; + let (mut rows, keys) = gen_valid(&mut rng, n_sources); + let oracle_rows = rows.clone(); + rng.shuffle(&mut rows); + let table = + ProviderMappingTable::from_rows(rows).unwrap_or_else(|e| panic!("seed {seed}: {e}")); + + assert_eq!(table.range_count(), oracle_rows.len(), "seed {seed}"); + assert_eq!(table.len(), keys.len() - 2, "seed {seed}"); + + for (src, id) in &keys { + let mut ascending = ProviderMappingCursor::new(table.ranges_for(src, id)); + for d in 990..=1_300 { + let expected = naive_resolve(&oracle_rows, src, id, d); + assert_eq!( + table.resolve(src, id, d), + expected, + "seed {seed} ({src},{id},{d})" + ); + assert_eq!( + ascending.resolve(d), + expected, + "seed {seed} cursor ({src},{id},{d})" + ); + } + for d in [i32::MIN, i32::MIN + 1, -1, 0, i32::MAX - 1, i32::MAX] { + let expected = naive_resolve(&oracle_rows, src, id, d); + assert_eq!( + table.resolve(src, id, d), + expected, + "seed {seed} extreme {d}" + ); + } + + // Random-order probes through one cursor must still equal resolve. + let mut random = table.cursor_for(src, id); + for _ in 0..200 { + let d = 990 + rng.below(320) as i32; + assert_eq!( + random.resolve(d), + table.resolve(src, id, d), + "seed {seed} random ({src},{id},{d})" + ); + } + } + } +} + +#[test] +fn from_rows_accepts_exactly_what_brute_force_validator_accepts_and_is_permutation_invariant() { + let sources = ["eod", "qm", " ", "ib"]; + let ids = ["A", "B", "", " A", "\t"]; + let mut seen: Vec = Vec::new(); + for seed in 0..400u64 { + let mut rng = Rng(0xBADD_A7A0_0000_0000 ^ seed); + let n = 1 + rng.below(7) as usize; + let mut rows = Vec::with_capacity(n); + for _ in 0..n { + // Mostly well-formed rows so key-level errors and Ok outcomes are common. + let source = if rng.below(12) == 0 { + sources[2] + } else { + sources[[0, 1, 3][rng.below(3) as usize]] + }; + let source_id = if rng.below(10) == 0 { + ids[[2, 4][rng.below(2) as usize]] + } else { + ids[[0, 1, 3][rng.below(3) as usize]] + }; + let from = rng.below(20) as i32; + let to = match rng.below(4) { + 0 => None, + 1 if rng.below(5) == 0 => Some(from - 1 - rng.below(3) as i32), + _ => Some(from + rng.below(6) as i32), + }; + let listing_id = if rng.below(15) == 0 { + -(rng.below(2) as i32) + } else { + 1 + rng.below(50) as i32 + }; + rows.push(row(source, source_id, from, to, listing_id)); + } + + let baseline = ProviderMappingTable::from_rows(rows.clone()); + assert_eq!( + classify(&baseline), + oracle_validate(&rows), + "seed {seed}: {rows:?}" + ); + if !seen.contains(&classify(&baseline)) { + seen.push(classify(&baseline)); + } + + for _ in 0..4 { + let mut shuffled = rows.clone(); + rng.shuffle(&mut shuffled); + let candidate = ProviderMappingTable::from_rows(shuffled); + match (&baseline, &candidate) { + (Err(a), Err(b)) => { + assert_eq!(a, b, "seed {seed}: error changed under permutation") + } + (Ok(a), Ok(b)) => { + assert_eq!(a.len(), b.len()); + assert_eq!(a.range_count(), b.range_count()); + for r in &rows { + assert_eq!( + a.ranges_for(&r.source, &r.source_id), + b.ranges_for(&r.source, &r.source_id) + ); + for d in -5..30 { + assert_eq!( + a.resolve(&r.source, &r.source_id, d), + b.resolve(&r.source, &r.source_id, d) + ); + } + } + } + _ => panic!("seed {seed}: Ok/Err outcome changed under permutation"), + } + } + } + // Guard against a generator that never exercises some outcome. + assert_eq!(seen.len(), 7, "outcomes exercised: {seen:?}"); +} + +#[test] +fn matching_is_case_sensitive_and_unicode_whitespace_only_ids_are_rejected() { + let table = ProviderMappingTable::from_rows([ + row("eod", "FB.US", 100, None, 1), + row("eod", "\u{00A0}FB.US", 100, None, 2), + ]) + .unwrap(); + assert_eq!(table.resolve("eod", "FB.US", 100), Some(1)); + assert_eq!(table.resolve("eod", "\u{00A0}FB.US", 100), Some(2)); + assert_eq!(table.resolve("eod", "fb.us", 100), None); + assert_eq!(table.resolve("EOD", "FB.US", 100), None); + assert_eq!(table.resolve("eod", "", 100), None); + assert_eq!(table.resolve("", "FB.US", 100), None); + + for blank in ["\u{3000}", "\u{00A0}\u{2003}", "\u{2028}"] { + assert_eq!( + ProviderMappingTable::from_rows([row("eod", blank, 100, None, 1)]).unwrap_err(), + ProviderMappingError::EmptySourceId { + source: "eod".to_string() + }, + "{blank:?}" + ); + assert_eq!( + ProviderMappingTable::from_rows([row(blank, "FB.US", 100, None, 1)]).unwrap_err(), + ProviderMappingError::EmptySource, + "{blank:?}" + ); + } +} + +#[test] +fn ranges_for_returns_sorted_canonical_slice_and_cursor_reset_restarts() { + let table = ProviderMappingTable::from_rows([ + row("ib", "107113386", 50, None, 3), + row("ib", "107113386", 10, Some(19), 1), + row("ib", "107113386", 20, Some(30), 2), + ]) + .unwrap(); + let expected = [ + MappingRange { + valid_from: 10, + valid_to: Some(19), + listing_id: 1, + }, + MappingRange { + valid_from: 20, + valid_to: Some(30), + listing_id: 2, + }, + MappingRange { + valid_from: 50, + valid_to: None, + listing_id: 3, + }, + ]; + assert_eq!(table.ranges_for("ib", "107113386"), &expected); + assert!(expected[0].contains(10) && expected[0].contains(19) && !expected[0].contains(20)); + assert!(expected[2].contains(i32::MAX) && !expected[2].contains(49)); + + let mut cursor = table.cursor_for("ib", "107113386"); + assert_eq!(cursor.resolve(i32::MIN), None); + assert_eq!(cursor.resolve(i32::MAX), Some(3)); + cursor.reset(); + assert_eq!(cursor.resolve(15), Some(1)); + assert_eq!(cursor.resolve(31), None); + assert_eq!(cursor.resolve(20), Some(2)); // backwards probe after a gap miss +} + +#[test] +fn benchmark_workload_matches_spec_shape_and_miss_rate() { + let report = run_provider_mapping_benchmark(200_000).unwrap(); + assert_eq!(report.key_count, PROVIDER_MAPPING_BENCH_KEY_COUNT); + assert_eq!(report.key_count, 60_000); + assert_eq!(report.range_count, 68_000); + assert_eq!(report.multi_range_keys, 6_000); + assert_eq!(report.hits + report.misses, 200_000); + let miss_rate = report.misses as f64 / report.lookups as f64; + // ~5% designed misses plus any random probes that land in interior gaps. + assert!((0.04..0.07).contains(&miss_rate), "miss rate {miss_rate}"); + + let again = run_provider_mapping_benchmark(200_000).unwrap(); + assert_eq!(report.checksum, again.checksum); + assert_eq!(report.hits, again.hits); +} diff --git a/tools/curate-etl/tests/shorts_contract.rs b/tools/curate-etl/tests/shorts_contract.rs new file mode 100644 index 00000000..3840d32b --- /dev/null +++ b/tools/curate-etl/tests/shorts_contract.rs @@ -0,0 +1,497 @@ +//! Contract tests for the public `curate_etl` `shorts` builder API and CLI binary (T-76 / M1.2f). +//! +//! Uses only the crate's public surface and compiled binary (`CARGO_BIN_EXE_curate-etl`), guarding: +//! - Canadian TSX holiday calendar & weekend observance rules (2008–2030), +//! - `+4` Canadian business-day lag calculation & out-of-range error handling, +//! - `America/Toronto` ET→UTC DST conversion (including spring-gap and fall-overlap rejections), +//! - `build_shorts` bad-row resilience, optional-field sanitization, `-0.0` normalization, +//! deduplication, accounting invariants, no-look-ahead, and permutation invariance, +//! - `bench-shorts` reproducibility and CLI argument validation. + +use std::process::Command; + +use curate_etl::bench::run_shorts_benchmark; +use curate_etl::{ + add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, + is_canadian_business_day, ymd_to_epoch_days, CeoShortReport, ShortRow, ShortsBuild, + ShortsError, ShortsStats, MAX_SUPPORTED_DATE, MAX_SUPPORTED_YEAR, MIN_SUPPORTED_DATE, + MIN_SUPPORTED_YEAR, SHORTS_DISSEMINATION_HOUR_ET, SHORTS_DISSEMINATION_MINUTE_ET, + SHORTS_LAG_BUSINESS_DAYS, SHORTS_SOURCE_CEO, +}; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture 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 +} + +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 shuffle(items: &mut [T], rng: &mut Rng) { + for i in (1..items.len()).rev() { + let j = (rng.next() % (i as u64 + 1)) as usize; + items.swap(i, j); + } +} + +fn assert_accounting_and_order(build: &ShortsBuild) { + let s = &build.stats; + assert_eq!( + s.rows_in, + s.rows_out + + s.dropped_invalid_shares_short + + s.duplicate_collapsed + + s.duplicate_conflict_dropped, + "accounting invariant failed: {s:?}" + ); + assert_eq!(s.rows_out, build.rows.len()); + + let mut distinct_keys = 0usize; + let mut prev_key: Option<&K> = None; + for row in &build.rows { + assert!( + row.known_at_date > row.report_date, + "look-ahead violation: known_at_date {} <= report_date {}", + row.known_at_date, + row.report_date + ); + assert_eq!(row.source, SHORTS_SOURCE_CEO); + assert_eq!(row.source, "ceo_shorts"); + if prev_key != Some(&row.key) { + distinct_keys += 1; + prev_key = Some(&row.key); + } + } + assert_eq!(s.keys_out, distinct_keys); + + for pair in build.rows.windows(2) { + assert!( + (&pair[0].key, pair[0].report_date) < (&pair[1].key, pair[1].report_date), + "rows must be strictly sorted by (key, report_date)" + ); + } +} + +fn assert_rows_bit_eq(a: &[ShortRow], b: &[ShortRow]) { + assert_eq!(a.len(), b.len()); + for (x, y) in a.iter().zip(b) { + assert_eq!(x.key, y.key); + assert_eq!(x.report_date, y.report_date); + assert_eq!(x.known_at_date, y.known_at_date); + assert_eq!(x.known_at_utc_micros, y.known_at_utc_micros); + assert_eq!(x.shares_short.to_bits(), y.shares_short.to_bits()); + assert_eq!( + x.net_change.map(f64::to_bits), + y.net_change.map(f64::to_bits) + ); + assert_eq!( + x.pct_float.map(f64::to_bits), + y.pct_float.map(f64::to_bits) + ); + assert_eq!(x.source, y.source); + } +} + +#[test] +fn public_constants_and_calendar_holidays_match_contract() { + assert_eq!(SHORTS_SOURCE_CEO, "ceo_shorts"); + assert_eq!(SHORTS_LAG_BUSINESS_DAYS, 4); + assert_eq!(SHORTS_DISSEMINATION_HOUR_ET, 17); + assert_eq!(SHORTS_DISSEMINATION_MINUTE_ET, 0); + assert_eq!(MIN_SUPPORTED_YEAR, 2008); + assert_eq!(MAX_SUPPORTED_YEAR, 2030); + assert_eq!(epoch_days_to_ymd(MIN_SUPPORTED_DATE), (2008, 1, 1)); + assert_eq!(epoch_days_to_ymd(MAX_SUPPORTED_DATE), (2030, 12, 31)); + + // Pinned TSX holidays and weekend observances + let non_business = [ + (2024, 3, 29), // Good Friday + (2023, 7, 3), // Canada Day observed + (2022, 12, 26), // Christmas observed + (2022, 12, 27), // Boxing Day observed + (2021, 2, 15), // Family Day + (2024, 5, 20), // Victoria Day + (2024, 8, 5), // Civic Holiday + (2024, 10, 14), // Thanksgiving + (2022, 1, 3), // New Year's Day observed (Sat Jan 1 -> Mon Jan 3) + (2023, 1, 2), // New Year's Day observed (Sun Jan 1 -> Mon Jan 2) + (2020, 12, 28), // Boxing Day observed (Fri Dec 25 / Sat Dec 26 -> Mon Dec 28) + (2021, 12, 27), // Christmas observed (Sat Dec 25 -> Mon Dec 27) + (2021, 12, 28), // Boxing Day observed (Sun Dec 26 -> Tue Dec 28) + ]; + for (y, m, d) in non_business { + assert_eq!( + is_canadian_business_day(day(y, m, d)), + Ok(false), + "expected {y:04}-{m:02}-{d:02} to be a non-business day" + ); + } + + // Ordinary weekday + federal holidays where TSX trades normally + for (y, m, d) in [(2024, 6, 12), (2023, 10, 2), (2024, 11, 11)] { + assert_eq!( + is_canadian_business_day(day(y, m, d)), + Ok(true), + "expected {y:04}-{m:02}-{d:02} to be a business day" + ); + } +} + +#[test] +fn plus_four_business_days_and_out_of_range_errors() { + assert_eq!( + add_canadian_business_days(day(2024, 3, 15), 4), + Ok(day(2024, 3, 21)) + ); + assert_eq!( + add_canadian_business_days(day(2024, 3, 28), 4), + Ok(day(2024, 4, 4)) + ); + assert_eq!( + add_canadian_business_days(day(2023, 12, 29), 4), + Ok(day(2024, 1, 5)) + ); + assert_eq!( + add_canadian_business_days(day(2023, 9, 30), 4), + Ok(day(2023, 10, 5)) + ); + assert_eq!( + add_canadian_business_days(day(2024, 6, 12), 0), + Ok(day(2024, 6, 12)) + ); + + // Out-of-range dates return typed ShortsError::DateOutOfRange without panicking + for bad in [ + MIN_SUPPORTED_DATE - 1, + MAX_SUPPORTED_DATE + 1, + i32::MIN, + i32::MAX, + ] { + assert!(matches!( + is_canadian_business_day(bad), + Err(ShortsError::DateOutOfRange { .. }) + )); + assert!(matches!( + add_canadian_business_days(bad, 4), + Err(ShortsError::DateOutOfRange { .. }) + )); + assert!(matches!( + et_to_utc_micros(bad, 17, 0, 0), + Err(ShortsError::DateOutOfRange { .. }) + )); + } + assert!(matches!( + add_canadian_business_days(day(2030, 12, 30), 4), + Err(ShortsError::DateOutOfRange { .. }) + )); +} + +#[test] +fn et_to_utc_micros_dst_transitions_and_local_time_validation() { + // Summer EDT (21:00Z) vs Winter EST (22:00Z) + assert_eq!( + et_to_utc_micros(day(2024, 7, 15), 17, 0, 0), + Ok(utc_micros(2024, 7, 15, 21, 0, 0)) + ); + assert_eq!( + et_to_utc_micros(day(2024, 1, 15), 17, 0, 0), + Ok(utc_micros(2024, 1, 15, 22, 0, 0)) + ); + + // Both sides of March spring-forward (2024-03-10) + assert_eq!( + et_to_utc_micros(day(2024, 3, 9), 17, 0, 0), + Ok(utc_micros(2024, 3, 9, 22, 0, 0)) + ); + assert_eq!( + et_to_utc_micros(day(2024, 3, 10), 17, 0, 0), + Ok(utc_micros(2024, 3, 10, 21, 0, 0)) + ); + + // Both sides of November fall-back (2024-11-03) + assert_eq!( + et_to_utc_micros(day(2024, 11, 2), 17, 0, 0), + Ok(utc_micros(2024, 11, 2, 21, 0, 0)) + ); + assert_eq!( + et_to_utc_micros(day(2024, 11, 3), 17, 0, 0), + Ok(utc_micros(2024, 11, 3, 22, 0, 0)) + ); + + // Events 16:05 ET reuse + assert_eq!( + et_to_utc_micros(day(2026, 3, 6), 16, 5, 0), + Ok(utc_micros(2026, 3, 6, 21, 5, 0)) + ); + assert_eq!( + et_to_utc_micros(day(2026, 3, 9), 16, 5, 0), + Ok(utc_micros(2026, 3, 9, 20, 5, 0)) + ); + + // Nonexistent, ambiguous, and invalid clock times + assert!(matches!( + et_to_utc_micros(day(2026, 3, 8), 2, 30, 0), + Err(ShortsError::NonexistentLocalTime { .. }) + )); + assert!(matches!( + et_to_utc_micros(day(2026, 11, 1), 1, 30, 0), + Err(ShortsError::AmbiguousLocalTime { .. }) + )); + assert!(matches!( + et_to_utc_micros(day(2024, 6, 12), 25, 0, 0), + Err(ShortsError::InvalidLocalTime { .. }) + )); +} + +#[test] +fn build_shorts_happy_path_bad_rows_dedup_and_empty_input() { + let empty = build_shorts::(Vec::new()).unwrap(); + assert!(empty.rows.is_empty()); + assert_eq!(empty.stats, ShortsStats::default()); + assert_accounting_and_order(&empty); + + let d_winter = day(2023, 12, 29); // +4bd -> 2024-01-05 (EST -> 22:00Z) + let d_summer = day(2024, 6, 15); // Sat -> +4bd -> 2024-06-20 (EDT -> 21:00Z) + let d_easter = day(2024, 3, 28); // Thu before Good Friday -> +4bd -> 2024-04-04 (EDT -> 21:00Z) + + let rows = vec![ + CeoShortReport { + key: 20, + report_date: d_summer, + shares_short: 250_000.0, + net_change: Some(-12_500.0), + pct_float: Some(3.25), + }, + // Identical duplicate with -0.0 normalization + CeoShortReport { + key: 10, + report_date: d_winter, + shares_short: -0.0, + net_change: Some(-0.0), + pct_float: Some(-0.0), + }, + CeoShortReport { + key: 10, + report_date: d_winter, + shares_short: 0.0, + net_change: Some(0.0), + pct_float: Some(0.0), + }, + // Non-finite optional fields nulled and counted + CeoShortReport { + key: 10, + report_date: d_easter, + shares_short: 42_000.0, + net_change: Some(f64::NEG_INFINITY), + pct_float: Some(f64::NAN), + }, + // Invalid shares_short dropped without incrementing optional-field null counters + CeoShortReport { + key: 30, + report_date: d_winter, + shares_short: -1.0, + net_change: Some(f64::NAN), + pct_float: Some(f64::INFINITY), + }, + CeoShortReport { + key: 30, + report_date: d_summer, + shares_short: f64::NAN, + net_change: None, + pct_float: None, + }, + // Conflicting duplicate group dropped entirely + CeoShortReport { + key: 40, + report_date: d_summer, + shares_short: 10_000.0, + net_change: Some(500.0), + pct_float: None, + }, + CeoShortReport { + key: 40, + report_date: d_summer, + shares_short: 10_000.0, + net_change: Some(600.0), + pct_float: None, + }, + ]; + + let built = build_shorts(rows).unwrap(); + assert_accounting_and_order(&built); + assert_eq!(built.stats.rows_in, 8); + assert_eq!(built.stats.rows_out, 3); + assert_eq!(built.stats.keys_out, 2); + assert_eq!(built.stats.dropped_invalid_shares_short, 2); + assert_eq!(built.stats.nulled_invalid_net_change, 1); + assert_eq!(built.stats.nulled_invalid_pct_float, 1); + assert_eq!(built.stats.duplicate_collapsed, 1); + assert_eq!(built.stats.duplicate_conflict_dropped, 2); + + assert_eq!(built.rows[0].key, 10); + assert_eq!(built.rows[0].known_at_date, day(2024, 1, 5)); + assert_eq!( + built.rows[0].known_at_utc_micros, + utc_micros(2024, 1, 5, 22, 0, 0) + ); + assert_eq!(built.rows[0].shares_short.to_bits(), 0.0_f64.to_bits()); + + assert_eq!(built.rows[1].key, 10); + assert_eq!(built.rows[1].known_at_date, day(2024, 4, 4)); + assert_eq!( + built.rows[1].known_at_utc_micros, + utc_micros(2024, 4, 4, 21, 0, 0) + ); + assert_eq!(built.rows[1].net_change, None); + assert_eq!(built.rows[1].pct_float, None); + + assert_eq!(built.rows[2].key, 20); + assert_eq!(built.rows[2].known_at_date, day(2024, 6, 20)); + assert_eq!( + built.rows[2].known_at_utc_micros, + utc_micros(2024, 6, 20, 21, 0, 0) + ); +} + +#[test] +fn permutation_invariance_holds_across_fixed_seed_shuffles() { + let dates = [ + day(2017, 4, 15), + day(2020, 12, 31), + day(2022, 12, 15), + day(2023, 9, 30), + day(2024, 3, 15), + day(2024, 3, 28), + day(2025, 11, 15), + day(2026, 4, 30), + ]; + + let mut input = Vec::new(); + for key in 1..=25_i32 { + for (idx, &d) in dates.iter().enumerate() { + let base = CeoShortReport { + key, + report_date: d, + shares_short: ((key as usize * 1_000) + idx * 50) as f64, + net_change: if idx % 3 == 0 { + Some(f64::NAN) + } else { + Some((idx as f64 - 3.0) * 100.0) + }, + pct_float: if idx % 4 == 0 { + Some(f64::INFINITY) + } else { + Some(0.5 + idx as f64 * 0.25) + }, + }; + input.push(base.clone()); + if (key + idx as i32) % 7 == 0 { + input.push(base.clone()); // identical duplicate + } + if (key + idx as i32) % 11 == 0 { + let mut conflict = base; + conflict.shares_short += 1.0; + input.push(conflict); // conflicting duplicate + } + } + if key % 5 == 0 { + input.push(CeoShortReport { + key, + report_date: dates[0], + shares_short: -10.0, + net_change: Some(f64::NAN), + pct_float: None, + }); + } + } + + let baseline = build_shorts(input.clone()).unwrap(); + assert_accounting_and_order(&baseline); + assert!(baseline.stats.duplicate_collapsed > 0); + assert!(baseline.stats.duplicate_conflict_dropped > 0); + assert!(baseline.stats.dropped_invalid_shares_short > 0); + assert!(baseline.stats.nulled_invalid_net_change > 0); + assert!(baseline.stats.nulled_invalid_pct_float > 0); + + let mut rng = Rng(0x570C_4B07_5404_9999); + for _ in 0..16 { + let mut perm = input.clone(); + shuffle(&mut perm, &mut rng); + let trial = build_shorts(perm).unwrap(); + assert_accounting_and_order(&trial); + assert_rows_bit_eq(&baseline.rows, &trial.rows); + assert_eq!(baseline.stats, trial.stats); + } +} + +#[test] +fn run_shorts_benchmark_and_cli_binary_are_reproducible() { + let a = run_shorts_benchmark(2_000).unwrap(); + let b = run_shorts_benchmark(2_000).unwrap(); + assert_eq!(a.rows, 2_000); + assert_eq!(a.rows_out, b.rows_out); + assert_eq!(a.keys_out, b.keys_out); + assert_eq!(a.stats, b.stats); + assert_eq!(a.checksum, b.checksum); + assert_ne!(a.checksum, 0); + + let bin = env!("CARGO_BIN_EXE_curate-etl"); + let run1 = Command::new(bin) + .args(["bench-shorts", "5000"]) + .output() + .expect("run bench-shorts #1"); + let run2 = Command::new(bin) + .args(["bench-shorts", "5000"]) + .output() + .expect("run bench-shorts #2"); + + assert!(run1.status.success(), "bench-shorts #1 failed"); + assert!(run2.status.success(), "bench-shorts #2 failed"); + + let out1 = String::from_utf8_lossy(&run1.stdout); + let out2 = String::from_utf8_lossy(&run2.stdout); + assert!(out1.contains("curate-etl bench-shorts")); + assert!(out1.contains("rows/s")); + assert!(out1.contains("checksum=0x")); + + let extract_checksum = |s: &str| -> String { + s.split("checksum=") + .nth(1) + .and_then(|rest| rest.split_whitespace().next()) + .expect("checksum token present") + .to_string() + }; + assert_eq!(extract_checksum(&out1), extract_checksum(&out2)); + + // Invalid CLI args exit non-zero and mention bench-shorts in usage + for bad in [ + &["bench-shorts", "0"][..], + &["bench-shorts", "abc"][..], + &["bench-shorts", "10", "20"][..], + ] { + let out = Command::new(bin) + .args(bad) + .output() + .expect("run invalid bench-shorts"); + assert!(!out.status.success(), "expected failure for {bad:?}"); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("bench-shorts")); + } +} diff --git a/tools/curate-etl/tests/shorts_reference.rs b/tools/curate-etl/tests/shorts_reference.rs new file mode 100644 index 00000000..b50101ea --- /dev/null +++ b/tools/curate-etl/tests/shorts_reference.rs @@ -0,0 +1,463 @@ +//! Independent reference / point-in-time QA tests for the `shorts` builder (T-76 / M1.2f). +//! +//! Oracles here are written independently of `src/shorts.rs`: +//! - the full TSX market-holiday list for `2017..=2027` (the `ceoShorts` data window plus a year +//! of headroom), typed out by hand from the published TSX holiday schedules; +//! - `America/Toronto` DST switch dates for `2008..=2030`, extracted from the system IANA tzdata +//! (`zoneinfo.ZoneInfo("America/Toronto")` offset changes at 12:00 local). +//! +//! Point-in-time checks follow the leakage lens: `known_at` is strictly after the whole report +//! day in Toronto, adding later reports ("poison") never moves earlier rows, and an out-of-range +//! date fails the build wherever it appears in the input. + +use std::collections::BTreeSet; + +use curate_etl::bench::{run_shorts_benchmark, DEFAULT_SHORTS_BENCH_ROWS}; +use curate_etl::{ + add_canadian_business_days, build_shorts, epoch_days_to_ymd, et_to_utc_micros, + is_canadian_business_day, ymd_to_epoch_days, CeoShortReport, ShortsError, MAX_SUPPORTED_DATE, + MIN_SUPPORTED_DATE, SHORTS_LAG_BUSINESS_DAYS, +}; + +const MICROS_PER_HOUR: i64 = 3_600_000_000; +const MICROS_PER_DAY: i64 = 24 * MICROS_PER_HOUR; + +fn day(y: i32, m: u32, d: u32) -> i32 { + ymd_to_epoch_days(y, m, d).expect("valid fixture date") +} + +fn is_weekend(epoch_day: i32) -> bool { + // 1970-01-01 was a Thursday; 0 = Thursday, 2 = Saturday, 3 = Sunday. + matches!(epoch_day.rem_euclid(7), 2 | 3) +} + +#[rustfmt::skip] +/// Every TSX full-day market closure on a weekday, 2017..=2027. +const TSX_HOLIDAYS_2017_2027: &[(i32, u32, u32)] = &[ + // 2017 (Jan 1 Sun, Jul 1 Sat) + (2017, 1, 2), (2017, 2, 20), (2017, 4, 14), (2017, 5, 22), (2017, 7, 3), + (2017, 8, 7), (2017, 9, 4), (2017, 10, 9), (2017, 12, 25), (2017, 12, 26), + // 2018 (Jul 1 Sun) + (2018, 1, 1), (2018, 2, 19), (2018, 3, 30), (2018, 5, 21), (2018, 7, 2), + (2018, 8, 6), (2018, 9, 3), (2018, 10, 8), (2018, 12, 25), (2018, 12, 26), + // 2019 + (2019, 1, 1), (2019, 2, 18), (2019, 4, 19), (2019, 5, 20), (2019, 7, 1), + (2019, 8, 5), (2019, 9, 2), (2019, 10, 14), (2019, 12, 25), (2019, 12, 26), + // 2020 (Dec 25 Fri -> Boxing Day Mon Dec 28) + (2020, 1, 1), (2020, 2, 17), (2020, 4, 10), (2020, 5, 18), (2020, 7, 1), + (2020, 8, 3), (2020, 9, 7), (2020, 10, 12), (2020, 12, 25), (2020, 12, 28), + // 2021 (Dec 25 Sat -> Mon 27 / Tue 28; Victoria Day is May 24 itself) + (2021, 1, 1), (2021, 2, 15), (2021, 4, 2), (2021, 5, 24), (2021, 7, 1), + (2021, 8, 2), (2021, 9, 6), (2021, 10, 11), (2021, 12, 27), (2021, 12, 28), + // 2022 (Jan 1 Sat -> Mon Jan 3; Dec 25 Sun -> Mon 26 / Tue 27) + (2022, 1, 3), (2022, 2, 21), (2022, 4, 15), (2022, 5, 23), (2022, 7, 1), + (2022, 8, 1), (2022, 9, 5), (2022, 10, 10), (2022, 12, 26), (2022, 12, 27), + // 2023 (Jan 1 Sun, Jul 1 Sat) + (2023, 1, 2), (2023, 2, 20), (2023, 4, 7), (2023, 5, 22), (2023, 7, 3), + (2023, 8, 7), (2023, 9, 4), (2023, 10, 9), (2023, 12, 25), (2023, 12, 26), + // 2024 + (2024, 1, 1), (2024, 2, 19), (2024, 3, 29), (2024, 5, 20), (2024, 7, 1), + (2024, 8, 5), (2024, 9, 2), (2024, 10, 14), (2024, 12, 25), (2024, 12, 26), + // 2025 + (2025, 1, 1), (2025, 2, 17), (2025, 4, 18), (2025, 5, 19), (2025, 7, 1), + (2025, 8, 4), (2025, 9, 1), (2025, 10, 13), (2025, 12, 25), (2025, 12, 26), + // 2026 (Dec 25 Fri -> Boxing Day Mon Dec 28) + (2026, 1, 1), (2026, 2, 16), (2026, 4, 3), (2026, 5, 18), (2026, 7, 1), + (2026, 8, 3), (2026, 9, 7), (2026, 10, 12), (2026, 12, 25), (2026, 12, 28), + // 2027 (Easter Mar 28; Dec 25 Sat -> Mon 27 / Tue 28) + (2027, 1, 1), (2027, 2, 15), (2027, 3, 26), (2027, 5, 24), (2027, 7, 1), + (2027, 8, 2), (2027, 9, 6), (2027, 10, 11), (2027, 12, 27), (2027, 12, 28), +]; + +/// `(year, (month, day) of DST start Sunday, (month, day) of DST end Sunday)`. +type DstSwitches = (i32, (u32, u32), (u32, u32)); + +/// `America/Toronto` DST switch Sundays per year from IANA tzdata. +#[rustfmt::skip] +const TZDATA_DST_2008_2030: &[DstSwitches] = &[ + (2008, (3, 9), (11, 2)), (2009, (3, 8), (11, 1)), (2010, (3, 14), (11, 7)), + (2011, (3, 13), (11, 6)), (2012, (3, 11), (11, 4)), (2013, (3, 10), (11, 3)), + (2014, (3, 9), (11, 2)), (2015, (3, 8), (11, 1)), (2016, (3, 13), (11, 6)), + (2017, (3, 12), (11, 5)), (2018, (3, 11), (11, 4)), (2019, (3, 10), (11, 3)), + (2020, (3, 8), (11, 1)), (2021, (3, 14), (11, 7)), (2022, (3, 13), (11, 6)), + (2023, (3, 12), (11, 5)), (2024, (3, 10), (11, 3)), (2025, (3, 9), (11, 2)), + (2026, (3, 8), (11, 1)), (2027, (3, 14), (11, 7)), (2028, (3, 12), (11, 5)), + (2029, (3, 11), (11, 4)), (2030, (3, 10), (11, 3)), +]; + +fn tzdata_offset_hours_at_local(epoch_day: i32, hour: u8) -> i64 { + let (y, _, _) = epoch_days_to_ymd(epoch_day); + let &(_, (sm, sd), (em, ed)) = TZDATA_DST_2008_2030 + .iter() + .find(|(year, _, _)| *year == y) + .expect("year in tzdata table"); + let (start, end) = (day(y, sm, sd), day(y, em, ed)); + let edt = if epoch_day == start { + hour >= 3 + } else if epoch_day == end { + hour < 1 + } else { + epoch_day > start && epoch_day < end + }; + if edt { + 4 + } else { + 5 + } +} + +#[test] +fn calendar_matches_hand_typed_tsx_holiday_list_for_every_day_2017_to_2027() { + let holidays: BTreeSet = TSX_HOLIDAYS_2017_2027 + .iter() + .map(|&(y, m, d)| day(y, m, d)) + .collect(); + assert_eq!(holidays.len(), 110, "10 TSX weekday closures per year"); + assert!(holidays.iter().all(|&h| !is_weekend(h))); + + let mut mismatches = Vec::new(); + for d in day(2017, 1, 1)..=day(2027, 12, 31) { + let expected = !is_weekend(d) && !holidays.contains(&d); + let actual = is_canadian_business_day(d).expect("in supported range"); + if expected != actual { + mismatches.push((epoch_days_to_ymd(d), expected, actual)); + } + } + assert!(mismatches.is_empty(), "calendar mismatches: {mismatches:?}"); +} + +#[test] +fn every_supported_year_has_exactly_ten_weekday_closures_and_no_weekend_business_days() { + for year in 2008..=2030 { + let mut weekday_closures = 0; + for d in day(year, 1, 1)..=day(year, 12, 31) { + let business = is_canadian_business_day(d).unwrap(); + if is_weekend(d) { + assert!( + !business, + "weekend {:?} marked business", + epoch_days_to_ymd(d) + ); + } else if !business { + weekday_closures += 1; + } + } + // 9 holidays, Christmas/Boxing counted as two closures; observance never lands on a + // weekend and never collides with another holiday. + assert_eq!(weekday_closures, 10, "year {year}"); + } +} + +#[test] +fn et_to_utc_matches_tzdata_for_every_supported_day_at_17_00_and_16_05() { + for d in MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE { + for (hour, minute) in [(17_u8, 0_u8), (16, 5), (0, 0), (23, 59)] { + let offset = tzdata_offset_hours_at_local(d, hour); + let expected = i64::from(d) * MICROS_PER_DAY + + (i64::from(hour) + offset) * MICROS_PER_HOUR + + i64::from(minute) * 60_000_000; + assert_eq!( + et_to_utc_micros(d, hour, minute, 0), + Ok(expected), + "{:?} {hour:02}:{minute:02}", + epoch_days_to_ymd(d) + ); + } + } +} + +#[test] +fn dst_switch_instants_are_continuous_in_utc() { + for &(y, (sm, sd), (em, ed)) in TZDATA_DST_2008_2030 { + // Spring forward: 01:59:59 EST and 03:00:00 EDT are one second apart in UTC. + let start = day(y, sm, sd); + let before = et_to_utc_micros(start, 1, 59, 59).unwrap(); + let after = et_to_utc_micros(start, 3, 0, 0).unwrap(); + assert_eq!(after - before, 1_000_000, "spring {y}"); + assert!(matches!( + et_to_utc_micros(start, 2, 0, 0), + Err(ShortsError::NonexistentLocalTime { .. }) + )); + assert!(matches!( + et_to_utc_micros(start, 2, 59, 59), + Err(ShortsError::NonexistentLocalTime { .. }) + )); + + // Fall back: 00:59:59 EDT -> 02:00:00 EST spans 2h01s of real time. + let end = day(y, em, ed); + let before = et_to_utc_micros(end, 0, 59, 59).unwrap(); + let after = et_to_utc_micros(end, 2, 0, 0).unwrap(); + assert_eq!(after - before, 2 * MICROS_PER_HOUR + 1_000_000, "fall {y}"); + assert!(matches!( + et_to_utc_micros(end, 1, 0, 0), + Err(ShortsError::AmbiguousLocalTime { .. }) + )); + } +} + +#[test] +fn plus_four_business_days_is_exact_for_every_supported_start_date() { + let mut first_error_start = None; + for d in MIN_SUPPORTED_DATE..=MAX_SUPPORTED_DATE { + match add_canadian_business_days(d, SHORTS_LAG_BUSINESS_DAYS) { + Ok(r) => { + assert!(r > d); + assert!(is_canadian_business_day(r).unwrap()); + let counted = ((d + 1)..=r) + .filter(|&x| is_canadian_business_day(x).unwrap()) + .count(); + assert_eq!(counted, 4, "start {:?}", epoch_days_to_ymd(d)); + // Worst case is a Fri Christmas + Mon Boxing Day + Fri New Year's run + // (e.g. 2009-12-24 -> 2010-01-04 = 11 calendar days). + assert!(r - d <= 11, "start {:?}", epoch_days_to_ymd(d)); + assert!( + first_error_start.is_none(), + "error must only happen at the tail" + ); + } + Err(ShortsError::DateOutOfRange { epoch_day, .. }) => { + assert_eq!(epoch_day, MAX_SUPPORTED_DATE + 1); + first_error_start.get_or_insert(d); + } + Err(other) => panic!("unexpected error {other:?}"), + } + } + // 2030-12-24 (Tue) -> Fri 27, Mon 30, Tue 31, then out of range; 2030-12-23 -> 2030-12-31. + assert_eq!(first_error_start, Some(day(2030, 12, 24))); + assert_eq!( + add_canadian_business_days(day(2030, 12, 23), 4), + Ok(day(2030, 12, 31)) + ); + assert_eq!( + add_canadian_business_days(day(2009, 12, 24), 4), + Ok(day(2010, 1, 4)) + ); +} + +#[test] +fn every_semi_monthly_report_date_in_dataset_window_resolves() { + // ceoShorts report dates: the 15th and month-end, Apr 2017 .. Dec 2027. + for y in 2017..=2027 { + for m in 1..=12_u32 { + let next = if m == 12 { + day(y + 1, 1, 1) + } else { + day(y, m + 1, 1) + }; + for report_date in [day(y, m, 15), next - 1] { + let built = build_shorts(vec![CeoShortReport { + key: 1_i32, + report_date, + shares_short: 1.0, + net_change: None, + pct_float: None, + }]) + .expect("dataset window must be fully supported"); + assert_eq!(built.rows.len(), 1); + } + } + } +} + +#[test] +fn known_at_is_strictly_after_the_whole_toronto_report_day_and_on_known_at_date() { + let mut input = Vec::new(); + for (i, d) in (day(2017, 4, 1)..=day(2027, 12, 31)).step_by(3).enumerate() { + input.push(CeoShortReport { + key: (i % 7) as i32, + report_date: d, + shares_short: 100.0 + i as f64, + net_change: None, + pct_float: None, + }); + } + let built = build_shorts(input).unwrap(); + assert!(built.rows.len() > 1_000); + for row in &built.rows { + let end_of_report_day_utc = et_to_utc_micros(row.report_date, 23, 59, 59).unwrap(); + assert!(row.known_at_utc_micros > end_of_report_day_utc); + // 17:00 ET is 21:00/22:00 UTC, so the UTC calendar day equals known_at_date. + assert_eq!( + row.known_at_utc_micros.div_euclid(MICROS_PER_DAY), + i64::from(row.known_at_date) + ); + let hour_utc = row.known_at_utc_micros.rem_euclid(MICROS_PER_DAY) / MICROS_PER_HOUR; + let expected_hour = 17 + tzdata_offset_hours_at_local(row.known_at_date, 17); + assert_eq!(hour_utc, expected_hour); + assert_eq!( + row.known_at_date, + add_canadian_business_days(row.report_date, 4).unwrap() + ); + } +} + +#[test] +fn appending_future_reports_and_poison_rows_never_moves_earlier_rows() { + let base_dates = [day(2024, 1, 15), day(2024, 1, 31), day(2024, 2, 15)]; + let mut base = Vec::new(); + for key in 1..=3_i32 { + for (i, &d) in base_dates.iter().enumerate() { + base.push(CeoShortReport { + key, + report_date: d, + shares_short: f64::from(key * 1_000 + i as i32), + net_change: Some(10.0), + pct_float: Some(0.5), + }); + } + } + let before = build_shorts(base.clone()).unwrap(); + + let mut poisoned = base; + // Absurd later reports for the same keys, a conflicting pair and a bad row for a later date. + for key in 1..=3_i32 { + poisoned.push(CeoShortReport { + key, + report_date: day(2024, 2, 29), + shares_short: 1e15, + net_change: Some(-1e15), + pct_float: Some(9_999.0), + }); + } + poisoned.push(CeoShortReport { + key: 2, + report_date: day(2024, 3, 15), + shares_short: 1.0, + net_change: None, + pct_float: None, + }); + poisoned.push(CeoShortReport { + key: 2, + report_date: day(2024, 3, 15), + shares_short: 2.0, + net_change: None, + pct_float: None, + }); + poisoned.push(CeoShortReport { + key: 3, + report_date: day(2024, 3, 15), + shares_short: f64::NAN, + net_change: None, + pct_float: None, + }); + let after = build_shorts(poisoned).unwrap(); + + let earlier: Vec<_> = after + .rows + .iter() + .filter(|r| r.report_date <= day(2024, 2, 15)) + .cloned() + .collect(); + assert_eq!(earlier, before.rows); + assert_eq!(after.rows.len(), before.rows.len() + 3); + assert_eq!(after.stats.duplicate_conflict_dropped, 2); + assert_eq!(after.stats.dropped_invalid_shares_short, 1); +} + +#[test] +fn out_of_range_row_fails_build_regardless_of_position_and_other_rows() { + let good = |key: i32| CeoShortReport { + key, + report_date: day(2024, 6, 14), + shares_short: 5.0, + net_change: None, + pct_float: None, + }; + for bad_date in [day(2007, 12, 31), day(2030, 12, 28), i32::MIN, i32::MAX] { + for pos in 0..=3 { + let mut rows = vec![good(1), good(2), good(3)]; + rows.insert( + pos, + CeoShortReport { + key: 9, + report_date: bad_date, + shares_short: f64::NAN, + net_change: None, + pct_float: None, + }, + ); + assert!( + matches!(build_shorts(rows), Err(ShortsError::DateOutOfRange { .. })), + "bad date {bad_date} at position {pos}" + ); + } + } +} + +#[test] +fn signed_and_unsigned_zero_or_nan_payloads_do_not_create_false_conflicts() { + let d = day(2025, 5, 15); + let rows = vec![ + CeoShortReport { + key: "X", + report_date: d, + shares_short: 10.0, + net_change: Some(f64::NAN), + pct_float: Some(-0.0), + }, + CeoShortReport { + key: "X", + report_date: d, + // Different NaN payload / infinity must sanitise to the same `None`. + shares_short: 10.0, + net_change: Some(f64::from_bits(0x7ff8_0000_0000_0001)), + pct_float: Some(0.0), + }, + CeoShortReport { + key: "X", + report_date: d, + shares_short: 10.0, + net_change: Some(f64::INFINITY), + pct_float: Some(0.0), + }, + ]; + let built = build_shorts(rows).unwrap(); + assert_eq!(built.rows.len(), 1); + assert_eq!(built.stats.duplicate_collapsed, 2); + assert_eq!(built.stats.duplicate_conflict_dropped, 0); + assert_eq!(built.stats.nulled_invalid_net_change, 3); + assert_eq!(built.rows[0].net_change, None); + assert_eq!( + built.rows[0].pct_float.map(f64::to_bits), + Some(0.0_f64.to_bits()) + ); + + // A valid row sharing a (key, date) with an invalid-shares row is not treated as a conflict. + let built = build_shorts(vec![ + CeoShortReport { + key: "Y", + report_date: d, + shares_short: -1.0, + net_change: None, + pct_float: None, + }, + CeoShortReport { + key: "Y", + report_date: d, + shares_short: 7.0, + net_change: None, + pct_float: None, + }, + ]) + .unwrap(); + assert_eq!(built.rows.len(), 1); + assert_eq!(built.rows[0].shares_short, 7.0); + assert_eq!(built.stats.dropped_invalid_shares_short, 1); + assert_eq!(built.stats.duplicate_conflict_dropped, 0); +} + +#[test] +fn default_bench_shorts_matches_readme_recorded_output() { + // README records rows_out=528426, keys_out=12500, checksum 0x1a99126eaa1a519b and the stats + // line below for `cargo run --release -p curate-etl --offline -- bench-shorts`. + let report = run_shorts_benchmark(DEFAULT_SHORTS_BENCH_ROWS).expect("bench builds"); + assert_eq!(DEFAULT_SHORTS_BENCH_ROWS, 700_000); + assert_eq!(report.rows_out, 528_426); + assert_eq!(report.keys_out, 12_500); + assert_eq!(report.stats.dropped_invalid_shares_short, 6_915); + assert_eq!(report.stats.nulled_invalid_net_change, 3_673); + assert_eq!(report.stats.nulled_invalid_pct_float, 3_500); + assert_eq!(report.stats.duplicate_collapsed, 5_352); + assert_eq!(report.stats.duplicate_conflict_dropped, 159_307); + assert_eq!(report.checksum, 0x1a99_126e_aa1a_519b); +} diff --git a/tsconfig.contracts.json b/tsconfig.contracts.json index 4e26c81c..716a4f58 100644 --- a/tsconfig.contracts.json +++ b/tsconfig.contracts.json @@ -3,6 +3,7 @@ "include": [ "libs/core/services/test/contracts.type-test.ts", "test/contracts/strategy-runtime.type-test.ts", - "test/contracts/canonical-runner.type-test.ts" + "test/contracts/canonical-runner.type-test.ts", + "test/contracts/market-data-store.type-test.ts" ] }