Compare commits

..

69 commits

Author SHA1 Message Date
Studio
fe9ec15199 T-90: M1.2i — tools/curate-etl: Zstd Parquet writer for bars_1d (year=YYYY/part.parquet, contract schema) with round-trip tests and local benchmark (adds the parquet crate) 2026-11-28 12:06:03 -05:00
Studio
b907659da2 T-90: tests 2026-11-28 12:02:49 -05:00
Studio
441a98cd05 T-90: M1.2i — tools/curate-etl: Zstd Parquet writer for bars_1d (year=YYYY/part.parquet, contract schema) with round-trip tests and local benchmark (adds the parquet crate) 2026-11-28 11:56:40 -05:00
Studio
64cb0cb725 T-90: M1.2i — tools/curate-etl: Zstd Parquet writer for bars_1d (year=YYYY/part.parquet, contract schema) with round-trip tests and local benchmark (adds the parquet crate) 2026-11-28 11:49:39 -05:00
Studio
fd943851b4 T-90: M1.2i — tools/curate-etl: Zstd Parquet writer for bars_1d (year=YYYY/part.parquet, contract schema) with round-trip tests and local benchmark (adds the parquet crate) 2026-11-28 11:32:43 -05:00
Studio
62f47cf3e8 T-90: M1.2i — tools/curate-etl: Zstd Parquet writer for bars_1d (year=YYYY/part.parquet, contract schema) with round-trip tests and local benchmark (adds the parquet crate) 2026-11-28 11:24:10 -05:00
Studio
ae007b8f0e T-90: M1.2i — tools/curate-etl: Zstd Parquet writer for bars_1d (year=YYYY/part.parquet, contract schema) with round-trip tests and local benchmark (adds the parquet crate) 2026-11-28 11:12:41 -05:00
Studio
94791648c6 Sync master into dev 2026-11-28 11:01:16 -05:00
ee635ae5b7 Allow crates.io download hosts in studio.config.json 2026-11-28 10:59:06 -05:00
Studio
4b51bea15a T-91: tests 2026-11-28 06:54:56 -05:00
Studio
50e6da57f0 T-91: M1.1o — Security-master persist: remove the stale 1900-01-01 fallback provider_mapping row when a rerun supplies a real start date 2026-11-28 06:49:18 -05:00
Studio
297a7615bb T-89: tests 2026-11-28 06:33:12 -05:00
Studio
d1057c41f3 T-89: M1.1n — Security-master run CLI: read-only Mongo sources + bar spans → composeSecurityMasterRun → match report files, with opt-in persist to dev PostgreSQL (no new dependencies) 2026-11-28 06:27:26 -05:00
Studio
d691d64260 T-89: M1.1n — Security-master run CLI: read-only Mongo sources + bar spans → composeSecurityMasterRun → match report files, with opt-in persist to dev PostgreSQL (no new dependencies) 2026-11-28 06:20:47 -05:00
Studio
d539d32b09 T-88: tests 2026-11-28 06:06:59 -05:00
Studio
0b3a111cb6 T-88: M1.1m — Security-master run composer: readers output + bar spans → Stage A → Stage B → Pass 6 → Pass 4 → match report + persist input (pure, in-memory, no new dependencies) 2026-11-28 06:00:23 -05:00
Studio
bd8ddab1a2 T-88: M1.1m — Security-master run composer: readers output + bar spans → Stage A → Stage B → Pass 6 → Pass 4 → match report + persist input (pure, in-memory, no new dependencies) 2026-11-28 05:54:45 -05:00
Studio
8ccca45174 T-88: M1.1m — Security-master run composer: readers output + bar spans → Stage A → Stage B → Pass 6 → Pass 4 → match report + persist input (pure, in-memory, no new dependencies) 2026-11-28 05:43:45 -05:00
Studio
3bdf7a8da6 T-88: M1.1m — Security-master run composer: readers output + bar spans → Stage A → Stage B → Pass 6 → Pass 4 → match report + persist input (pure, in-memory, no new dependencies) 2026-11-28 05:38:20 -05:00
Studio
33b1d23f84 T-87: tests 2026-11-28 05:15:43 -05:00
Studio
b2a1f5ce80 T-87: M1.1l — Security-type classifier: eodSymbols.Type → securityTypeByIsin for the security-master loader (no new dependencies) 2026-11-28 05:10:22 -05:00
Studio
a368e8a47a T-87: M1.1l — Security-type classifier: eodSymbols.Type → securityTypeByIsin for the security-master loader (no new dependencies) 2026-11-28 05:03:34 -05:00
Studio
2f5ac2e7e7 T-87: M1.1l — Security-type classifier: eodSymbols.Type → securityTypeByIsin for the security-master loader (no new dependencies) 2026-11-28 04:55:34 -05:00
Studio
c9a4adabad T-86: tests 2026-11-28 04:42:46 -05:00
Studio
2888dfb136 T-86: M1.1k — Read-only Mongo source-symbol readers: eodSymbols / ibSymbols / qmSymbols / ceoSymbols / eodSymbolChange → Stage A + Stage B input records (no new dependencies) 2026-11-28 04:36:37 -05:00
Studio
cadc3d1b6d T-86: M1.1k — Read-only Mongo source-symbol readers: eodSymbols / ibSymbols / qmSymbols / ceoSymbols / eodSymbolChange → Stage A + Stage B input records (no new dependencies) 2026-11-28 04:27:43 -05:00
Studio
32677c50da T-86: M1.1k — Read-only Mongo source-symbol readers: eodSymbols / ibSymbols / qmSymbols / ceoSymbols / eodSymbolChange → Stage A + Stage B input records (no new dependencies) 2026-11-28 04:13:30 -05:00
Studio
fa55ff16fa T-85: tests 2026-11-28 03:49:08 -05:00
Studio
f130b239fe T-85: M1.4c — analyzeSignal / runEventStudy study runners in @stock-bot/research: analyzer math + automatic trial_ledger write + cluster N̂-deflated Sharpe (no new dependencies) 2026-11-28 03:43:13 -05:00
Studio
9d8dfc9bc8 T-85: M1.4c — analyzeSignal / runEventStudy study runners in @stock-bot/research: analyzer math + automatic trial_ledger write + cluster N̂-deflated Sharpe (no new dependencies) 2026-11-28 03:36:04 -05:00
Studio
45a98d309e T-85: M1.4c — analyzeSignal / runEventStudy study runners in @stock-bot/research: analyzer math + automatic trial_ledger write + cluster N̂-deflated Sharpe (no new dependencies) 2026-11-28 03:27:47 -05:00
Studio
17808bbda4 T-84: tests 2026-11-28 03:15:20 -05:00
Studio
744255c096 T-84: M1.3d — trial_ledger writer + cluster N̂-deflated Sharpe reader in @stock-bot/research (append one row per horizon, vault-fenced sample_end, PostgreSQL integration test + local benchmark) 2026-11-28 03:09:41 -05:00
Studio
dd05e20325 T-84: M1.3d — trial_ledger writer + cluster N̂-deflated Sharpe reader in @stock-bot/research (append one row per horizon, vault-fenced sample_end, PostgreSQL integration test + local benchmark) 2026-11-28 03:03:17 -05:00
Studio
9b57ea9677 T-84: M1.3d — trial_ledger writer + cluster N̂-deflated Sharpe reader in @stock-bot/research (append one row per horizon, vault-fenced sample_end, PostgreSQL integration test + local benchmark) 2026-11-28 02:49:52 -05:00
Studio
bbc31b9cd7 T-84: M1.3d — trial_ledger writer + cluster N̂-deflated Sharpe reader in @stock-bot/research (append one row per horizon, vault-fenced sample_end, PostgreSQL integration test + local benchmark) 2026-11-28 02:43:59 -05:00
Studio
6bbdb4049e T-83: tests 2026-11-28 02:28:42 -05:00
Studio
c4c99d6e8c T-83: M1.4b — Pure event-study math in @stock-bot/calculations: abnormal-return fan (AAR/CAAR) around events, date-clustered Newey-West t-stat and pre/post-2023 split (no I/O) 2026-11-28 02:23:06 -05:00
Studio
1a2396916e T-83: M1.4b — Pure event-study math in @stock-bot/calculations: abnormal-return fan (AAR/CAAR) around events, date-clustered Newey-West t-stat and pre/post-2023 split (no I/O) 2026-11-28 02:16:23 -05:00
Studio
ff0c5574a4 T-82: tests 2026-11-28 01:59:50 -05:00
Studio
c439138623 T-82: M1.4a — Pure signal analyzer math in @stock-bot/calculations: per-date IC / rank-IC, Newey-West t-stat, quantile spreads, turnover and pre/post-2023 recency gate (no I/O) 2026-11-28 01:53:32 -05:00
Studio
d9f0b45251 T-82: M1.4a — Pure signal analyzer math in @stock-bot/calculations: per-date IC / rank-IC, Newey-West t-stat, quantile spreads, turnover and pre/post-2023 recency gate (no I/O) 2026-11-28 01:47:48 -05:00
Studio
659cd042f6 T-82: M1.4a — Pure signal analyzer math in @stock-bot/calculations: per-date IC / rank-IC, Newey-West t-stat, quantile spreads, turnover and pre/post-2023 recency gate (no I/O) 2026-11-28 01:39:16 -05:00
Studio
306d324b8d T-78: M1.1j — Persist Pass 3/5/6 results into the security master: idempotent PostgreSQL loader with permanent listing_ids and override precedence 2026-11-28 01:36:19 -05:00
Studio
aeaff69527 T-78: tests 2026-11-28 01:33:09 -05:00
Studio
be5ebcbcfe T-78: M1.1j — Persist Pass 3/5/6 results into the security master: idempotent PostgreSQL loader with permanent listing_ids and override precedence 2026-11-28 01:26:51 -05:00
Studio
3ca206150e T-78: M1.1j — Persist Pass 3/5/6 results into the security master: idempotent PostgreSQL loader with permanent listing_ids and override precedence 2026-11-28 01:26:51 -05:00
Studio
d68577843e T-78: M1.1j — Persist Pass 3/5/6 results into the security master: idempotent PostgreSQL loader with permanent listing_ids and override precedence 2026-11-28 01:26:51 -05:00
Studio
d65d3f00d5 T-78: M1.1j — Persist Pass 3/5/6 results into the security master: idempotent PostgreSQL loader with permanent listing_ids and override precedence 2026-11-28 01:26:51 -05:00
Studio
7a8e83d22c T-81: tests 2026-11-28 01:20:52 -05:00
Studio
f1625cd73d T-81: M1.2h — tools/curate-etl: pure in-RAM provider_mapping table ((source, source_id, bar_date) → listing_id, date-ranged) with local benchmark (no new crates) 2026-11-28 01:08:14 -05:00
Studio
47dbb30493 T-81: M1.2h — tools/curate-etl: pure in-RAM provider_mapping table ((source, source_id, bar_date) → listing_id, date-ranged) with local benchmark (no new crates) 2026-11-28 01:02:32 -05:00
Studio
91c8d34cdc T-80: tests 2026-11-28 00:50:20 -05:00
Studio
70a371f3b0 T-80: M1.3a (re-land) — Canonical Deflated Sharpe Ratio + effective-trials (N̂) math in @stock-bot/calculations (missing from dev) 2026-11-28 00:44:29 -05:00
Studio
63b4c420c3 T-79: tests 2026-11-28 00:27:01 -05:00
Studio
be06a00ffe T-79: M1.3c — MarketDataStore contract types + pure 6-month Vault fence and DuckDB connection budget (no DuckDB dependency, no I/O) 2026-11-28 00:20:37 -05:00
Studio
cfcc856817 T-77: tests 2026-11-27 22:51:48 -05:00
Studio
88a7e32db7 T-77: M1.2g — tools/curate-etl: pure events builder (qmFilings timefiled → UTC + form groups; qmEarnings linked to same-day filing or lagged to 16:05 ET) with local benchmark (no new crates) 2026-11-27 22:45:41 -05:00
Studio
3100ec65b1 T-77: M1.2g — tools/curate-etl: pure events builder (qmFilings timefiled → UTC + form groups; qmEarnings linked to same-day filing or lagged to 16:05 ET) with local benchmark (no new crates) 2026-11-27 22:38:50 -05:00
Studio
9bd77a6869 T-76: tests 2026-11-27 22:24:06 -05:00
Studio
9e8cc1d3c7 T-76: M1.2f — tools/curate-etl: pure shorts builder (ceoShorts → +4 Canadian business-day 17:00 ET known_at) with local benchmark (no new crates) 2026-11-27 22:17:55 -05:00
Studio
a3cc5fd007 T-75: tests 2026-11-27 22:05:22 -05:00
Studio
65aed1c2b5 T-75: M1.2e — tools/curate-etl: pure fx_1d builder (merge CAD.FOREX daily + teMarketData.USDCAD into one USD/CAD series) with local benchmark (no new crates) 2026-11-27 21:59:58 -05:00
Studio
a494defef5 T-75: M1.2e — tools/curate-etl: pure fx_1d builder (merge CAD.FOREX daily + teMarketData.USDCAD into one USD/CAD series) with local benchmark (no new crates) 2026-11-27 21:52:48 -05:00
Studio
acbcb0ab7a T-74: tests 2026-11-27 21:41:41 -05:00
Studio
06f14c8730 T-74: M1.1i — Pass 3/4/6 match & conflict report: pure in-memory Markdown + CSV generator and override seed-SQL template (no DB I/O) 2026-11-27 21:34:43 -05:00
Studio
86bf0a68b2 T-74: M1.1i — Pass 3/4/6 match & conflict report: pure in-memory Markdown + CSV generator and override seed-SQL template (no DB I/O) 2026-11-27 21:23:56 -05:00
Studio
83ec301220 T-74: M1.1i — Pass 3/4/6 match & conflict report: pure in-memory Markdown + CSV generator and override seed-SQL template (no DB I/O) 2026-11-27 21:18:56 -05:00
Studio
cbabb17094 T-74: M1.1i — Pass 3/4/6 match & conflict report: pure in-memory Markdown + CSV generator and override seed-SQL template (no DB I/O) 2026-11-27 21:10:09 -05:00
78 changed files with 50723 additions and 20 deletions

190
Cargo.lock generated
View file

@ -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",
]

View file

@ -63,3 +63,131 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@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:<password>@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 <YYYY-MM-DD>`:** `--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:<password>@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`).

View file

@ -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}`;
}

View file

@ -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';

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -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 <YYYY-MM-DD> --out-dir <dir> [--persist] [--help]',
'',
'Options:',
' --as-of <YYYY-MM-DD> Required. Calendar reference date for Pass 6 delisting classification.',
' --out-dir <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> | void;
}
export interface RunSecurityMasterDeps {
readonly mongoCollectionClient: ReadOnlyMongoCollectionClient;
readonly barSpanReader: BarSpanAggregateReader;
readonly closeMongo?: () => Promise<void> | void;
readonly exchangeClassification?: ExchangeClassificationResult;
readonly exchangeLookup?: ExchangeSourceLookup;
readonly assertSafety?: () => void;
readonly createPostgresClient?: () =>
| Promise<SecurityMasterPostgresHandle>
| SecurityMasterPostgresHandle;
readonly persistFn?: typeof persistSecurityMaster;
readonly writeFile?: (filePath: string, content: string) => Promise<void> | 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<ComputeBarSpansOptions, 'sourceIdsBySource'>;
}
export interface RunSecurityMasterOutput {
readonly asOfDate: string;
readonly outDir: string;
readonly persist: boolean;
readonly filesWritten: readonly string[];
readonly exchanges: ExchangeClassificationResult;
readonly exchangeCountsByCollection: Readonly<Record<ExchangeSource, number>>;
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<string>();
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<void> {
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 <YYYY-MM-DD>');
}
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 <dir>');
}
return {
help: false,
asOfDate,
outDir,
persist,
};
}
export function assertSecurityMasterPersistSafety(
config: StockAppConfig,
env: Record<string, string | undefined> = 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<RunSecurityMasterOutput> {
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<typeof createReadOnlyMongoSourceSymbolReader>;
let exchanges: ExchangeClassificationResult;
let exchangeLookup: ExchangeSourceLookup;
const exchangeCountsByCollection: Record<ExchangeSource, number> = {
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<Record<string, unknown>>(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<readonly [string, string]> = [
[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<void> {
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<SecurityMasterPostgresHandle> => {
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<Row = Record<string, unknown>>(
text: string,
values?: readonly unknown[]
): Promise<SecurityMasterQueryResult<Row>> {
return poolClient.query(
text,
values === undefined ? undefined : [...values]
) as unknown as Promise<SecurityMasterQueryResult<Row>>;
},
release: () => {
poolClient.release();
},
};
let closed = false;
return {
queryable,
async close(): Promise<void> {
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);
});
}

File diff suppressed because it is too large Load diff

View file

@ -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<Record<string, SecurityType>> = 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<string, SecurityType> = new Map<string, SecurityType>(
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<string, SecurityType>;
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<SecurityType>;
readonly sourceIds: Set<string>;
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<string, SecurityType>();
const conflictingIsins = new Set<string>();
const unknownCounts = new Map<string, number>();
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<string, ConflictAccumulator>();
for (let i = 0; i < sampleLimit; i++) {
const isin = sortedConflictingIsins[i];
if (isin !== undefined) {
accumulators.set(isin, {
types: new Set<SecurityType>(),
sourceIds: new Set<string>(),
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<string, SecurityType>();
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<string, string>();
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);
}

File diff suppressed because it is too large Load diff

View file

@ -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

View file

@ -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
)
);

View file

@ -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
)
);

View file

@ -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;
}

File diff suppressed because it is too large Load diff

View file

@ -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';

File diff suppressed because it is too large Load diff

View file

@ -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';

View file

@ -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<typeof base>) =>
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);
});
});

View file

@ -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<number>(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<number>(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<number>(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);
});
});

View file

@ -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<EventStudyResult, { status: 'ok' }> {
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<EntityId, Float64Array>();
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<number>(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<EntityId, Float64Array>([['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<EntityId, Float64Array>([
['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<EntityId, Float64Array>();
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<EntityId, Float64Array>();
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<EntityId, Float64Array>();
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<EntityId, number[]>();
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<EntityId, Float64Array>([[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);
});
});

File diff suppressed because it is too large Load diff

View file

@ -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<number>(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<EntityId> | null;
readonly bottom: Set<EntityId> | 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<EntityId> | null = null;
let bottom: Set<EntityId> | 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<EntityId>, prev: Set<EntityId>): 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<EntityId>, prev.top as Set<EntityId>);
const bottom = turnoverOf(curr.bottom as Set<EntityId>, prev.bottom as Set<EntityId>);
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);
});
});

View file

@ -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');
});
});

76
libs/research/README.md Normal file
View file

@ -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:<uuid>`), 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`)

View file

@ -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:*",

View file

@ -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<Row = Record<string, unknown>>(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
)
);

View file

@ -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';

View file

@ -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<Record<string, TableCell>>;
/** 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<BarBatch>;
crossSection(q: {
features: string[];
date: string;
universe: UniverseRef;
asOf?: string;
}): Promise<Table>;
fundamentalsAsOf(q: {
listingIds: number[];
fields: string[];
asOf: string;
allowEstimatedLag?: boolean;
}): Promise<Table>;
events(q: {
kinds: EventKind[];
listingIds?: number[];
from: string;
to: string;
asOf?: string;
}): Promise<Table>;
shortsAsOf(q: { listingIds: number[]; from: string; to: string; asOf?: string }): Promise<Table>;
macroAsOf(q: {
countries: string[];
indicators: string[];
from: string;
to: string;
asOf?: string;
}): Promise<Table>;
fx(q: { pair: 'USD.CAD'; timeframe: '1m' | '1d'; from: string; to: string }): Promise<Table>;
universe(q: { ref: UniverseRef; date: string }): Promise<number[]>;
}
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<Record<string, string | undefined>> {
const globalRecord = globalThis as {
process?: { env?: Readonly<Record<string, string | undefined>> };
};
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<Record<string, string | undefined>>
): 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}';`,
],
};
}

View file

@ -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<CanonicalExpressionInput, 'sampleStart' | 'sampleEnd'>;
export type AnalyzeSignalOptions = Omit<SignalAnalysisOptions, 'vaultCutoffDate'>;
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<EventStudyResult, { readonly status: 'ok' }>;
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<string>([
'[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<unknown, unknown> {
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<BaseStudyRequest>;
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<AnalyzeSignalResult> {
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<SignalCrossSection>;
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<RunEventStudyResult> {
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<EntityId, NumericSeries>() : 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<EventStudyEvent>;
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,
};
}

File diff suppressed because it is too large Load diff

View file

@ -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);
});
});

View file

@ -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 | string | Date> = [
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);
}
});
});

View file

@ -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<Row = Record<string, unknown>>(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> = {}): 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<number, Float64Array>();
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> = {}): 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<unknown>, 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<number, Float64Array>();
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);
});
});

File diff suppressed because it is too large Load diff

View file

@ -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<number>(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>): 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<string, unknown> {
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<string, unknown>[]): {
executor: TrialLedgerExecutor;
calls: { text: string; params: readonly unknown[] | undefined }[];
} {
const calls: { text: string; params: readonly unknown[] | undefined }[] = [];
const executor: TrialLedgerExecutor = {
async query<Row = Record<string, unknown>>(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> | 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<number>(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<number, readonly string[]>([
[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<number | string, readonly string[]>([
[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<Row = Record<string, unknown>>(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<Row = Record<string, unknown>>() {
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'
);
});
});

File diff suppressed because it is too large Load diff

View file

@ -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);

View file

@ -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": {

View file

@ -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<A, B> =
(<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
const _sameStore: AssertEqual<MarketDataStore, SubpathMarketDataStore> = true;
const _sameScope: AssertEqual<DataScope, SubpathDataScope> = 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<BarBatch> {
return {
async *[Symbol.asyncIterator]() {
yield emptyBatch;
},
};
},
async crossSection(_q: {
features: string[];
date: string;
universe: UniverseRef;
asOf?: string;
}): Promise<Table> {
return emptyTable;
},
async fundamentalsAsOf(_q: {
listingIds: number[];
fields: string[];
asOf: string;
allowEstimatedLag?: boolean;
}): Promise<Table> {
return emptyTable;
},
async events(_q: {
kinds: EventKind[];
listingIds?: number[];
from: string;
to: string;
asOf?: string;
}): Promise<Table> {
return emptyTable;
},
async shortsAsOf(_q: {
listingIds: number[];
from: string;
to: string;
asOf?: string;
}): Promise<Table> {
return emptyTable;
},
async macroAsOf(_q: {
countries: string[];
indicators: string[];
from: string;
to: string;
asOf?: string;
}): Promise<Table> {
return emptyTable;
},
async fx(_q: {
pair: 'USD.CAD';
timeframe: '1m' | '1d';
from: string;
to: string;
}): Promise<Table> {
return emptyTable;
},
async universe(_q: { ref: UniverseRef; date: string }): Promise<number[]> {
return [101, 202];
},
};
function verifyAllMethods(store: MarketDataStore): void {
const _bars: AsyncIterable<BarBatch> = store.bars({
listingIds: [1, 2],
timeframe: '1d',
from: '2024-01-01',
to: '2025-12-31',
adjustment: 'raw',
});
const _barsWithOpts: AsyncIterable<BarBatch> = 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<Table> = store.crossSection({
features: ['rsi_14@v1'],
date: '2025-05-01',
universe: 'us_liquid_top3000',
asOf: '2025-05-01',
});
const _fundamentals: Promise<Table> = store.fundamentalsAsOf({
listingIds: [1],
fields: ['revenue_ttm'],
asOf: '2025-05-01',
allowEstimatedLag: false,
});
const _events: Promise<Table> = store.events({
kinds: ['filing', 'earnings', 'ceo_post', 'corporate_action'],
from: '2025-01-01',
to: '2025-05-01',
});
const _shorts: Promise<Table> = store.shortsAsOf({
listingIds: [1],
from: '2025-01-01',
to: '2025-05-01',
});
const _macro: Promise<Table> = store.macroAsOf({
countries: ['US', 'CA'],
indicators: ['CPI'],
from: '2025-01-01',
to: '2025-05-01',
});
const _fx: Promise<Table> = store.fx({
pair: 'USD.CAD',
timeframe: '1d',
from: '2025-01-01',
to: '2025-05-01',
});
const _universe: Promise<number[]> = 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<K extends keyof MarketDataStore> = Parameters<MarketDataStore[K]>[0];
type ReturnOf<K extends keyof MarketDataStore> = ReturnType<MarketDataStore[K]>;
const _exactMethodKeys: AssertEqual<
keyof MarketDataStore,
| 'bars'
| 'crossSection'
| 'fundamentalsAsOf'
| 'events'
| 'shortsAsOf'
| 'macroAsOf'
| 'fx'
| 'universe'
> = true;
const _exactScope: AssertEqual<DataScope, 'vault_fenced' | 'vault_evaluation_only'> = 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<ReturnOf<'bars'>, AsyncIterable<BarBatch>> = true;
const _exactCrossParam: AssertEqual<
ParamOf<'crossSection'>,
{ features: string[]; date: string; universe: UniverseRef; asOf?: string }
> = true;
const _exactCrossReturn: AssertEqual<ReturnOf<'crossSection'>, Promise<Table>> = true;
const _exactFundParam: AssertEqual<
ParamOf<'fundamentalsAsOf'>,
{ listingIds: number[]; fields: string[]; asOf: string; allowEstimatedLag?: boolean }
> = true;
const _exactFundReturn: AssertEqual<ReturnOf<'fundamentalsAsOf'>, Promise<Table>> = true;
const _exactEventsParam: AssertEqual<
ParamOf<'events'>,
{ kinds: EventKind[]; listingIds?: number[]; from: string; to: string; asOf?: string }
> = true;
const _exactEventsReturn: AssertEqual<ReturnOf<'events'>, Promise<Table>> = true;
const _exactShortsParam: AssertEqual<
ParamOf<'shortsAsOf'>,
{ listingIds: number[]; from: string; to: string; asOf?: string }
> = true;
const _exactShortsReturn: AssertEqual<ReturnOf<'shortsAsOf'>, Promise<Table>> = true;
const _exactMacroParam: AssertEqual<
ParamOf<'macroAsOf'>,
{ countries: string[]; indicators: string[]; from: string; to: string; asOf?: string }
> = true;
const _exactMacroReturn: AssertEqual<ReturnOf<'macroAsOf'>, Promise<Table>> = true;
const _exactFxParam: AssertEqual<
ParamOf<'fx'>,
{ pair: 'USD.CAD'; timeframe: '1m' | '1d'; from: string; to: string }
> = true;
const _exactFxReturn: AssertEqual<ReturnOf<'fx'>, Promise<Table>> = true;
const _exactUniverseParam: AssertEqual<
ParamOf<'universe'>,
{ ref: UniverseRef; date: string }
> = true;
const _exactUniverseReturn: AssertEqual<ReturnOf<'universe'>, Promise<number[]>> = 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,
];

View file

@ -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> | 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<number> {
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' }]);
});
});

View file

@ -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> | 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<T>(pool: Pool, fn: (client: PoolClient) => Promise<T>): Promise<T> {
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<string, SecurityType>([
['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<string, unknown[]> = {};
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<string, SecurityType>([['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);
});
});

File diff suppressed because it is too large Load diff

View file

@ -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> | 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<T>(pool: Pool, fn: (client: PoolClient) => Promise<T>): Promise<T> {
const client = await pool.connect();
try {
return await fn(client);
} finally {
client.release();
}
}
async function getSevenTableCounts(pool: Pool): Promise<Record<string, number>> {
const tables = [
'instrument',
'instrument_identifier_history',
'listing',
'listing_symbol_history',
'provider_mapping',
'resolution_conflict',
'corporate_action_continuity',
] as const;
const counts: Record<string, number> = {};
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<string, SecurityType>([
['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);
});
});

View file

@ -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> | 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<string>(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<number, Float64Array>();
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);
}
});
});

View file

@ -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> | 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<unknown>,
expectedCode: string,
messagePattern?: RegExp
): Promise<void> {
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<string>(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<number>(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<number>(nObs);
for (let t = 0; t < nObs; t += 1) {
baseFactor[t] = 0.0008 + 0.01 * factorGauss();
}
const noiseGauss = createGaussianSampler(9002);
const nearDupRows = new Array<TrialRowInput>(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<number>(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<TrialRowInput>(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);
});
});

View file

@ -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);
});
});

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -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<T>(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<string, SecurityType>;
}): 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<string, SecurityType>;
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<string, SecurityType>([
['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<T>(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<string, unknown>)) {
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);
});
});

File diff suppressed because it is too large Load diff

View file

@ -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<T>(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<string>(SECURITY_TYPES);
const observedOutputs = new Set<SecurityType>();
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<typeof buildSecurityTypeByIsin>) =>
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);
});
});

View file

@ -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<string> = 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<Record<string, readonly Record<string, unknown>[]>>
): ReadOnlySourceSymbolReader & { calls: string[] } {
const calls: string[] = [];
return {
calls,
isReadOnly: () => true,
find<T extends Record<string, unknown>>(name: string): AsyncIterable<T> {
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<string, unknown>,
['x'] as unknown as Record<string, unknown>,
{ 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');
});
});

File diff suppressed because it is too large Load diff

View file

@ -6,3 +6,5 @@ authors.workspace = true
license.workspace = true
[dependencies]
parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] }

View file

@ -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<K>`) into sorted, unique per-`(key, report_date)` point-in-time `ShortRow<K>` 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<K>`) and `qmEarnings` (`QmEarning<K>`) streams into deterministically sorted point-in-time `EventRow<K>` 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<MappingRange>` arena indexed by a sorted per-source `HashMap<String, (usize, usize)>` (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 `<out_dir>/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 `<out_dir>/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.<run>.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<K>`)
- 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

File diff suppressed because it is too large Load diff

View file

@ -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<CliAction, String> {
)),
},
["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::<usize>() {
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::<usize>() {
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::<usize>() {
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::<usize>() {
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::<usize>() {
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"));
}
}

File diff suppressed because it is too large Load diff

658
tools/curate-etl/src/fx.rs Normal file
View file

@ -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<Fx1dRow>,
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<FxDailyBar>, 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);
}
}

View file

@ -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,

View file

@ -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));

File diff suppressed because it is too large Load diff

View file

@ -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<Bars1dParquetRow> = (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<i64> = (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<i64> = (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<i64> = (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<i32> = 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<Bars1dParquetRow> = (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<Bars1dParquetRow> 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<Bars1dParquetRow> = (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::<Vec<_>>()
);
}
}
#[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::<usize>(),
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<Bars1dParquetRow> = (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);
}

File diff suppressed because it is too large Load diff

View file

@ -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<bool>,
/// 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<CalendarTable> = 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<bool, ShortsError> {
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<i32, ShortsError> {
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<i64, ShortsError> {
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<K = String> {
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<f64>,
/// Optional percent of float short passed through from caller (non-finite → `None`).
pub pct_float: Option<f64>,
}
/// A single curated `shorts` row, sorted and unique by `(key, report_date)`.
#[derive(Debug, Clone, PartialEq)]
pub struct ShortRow<K = String> {
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<f64>,
pub pct_float: Option<f64>,
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<K = String> {
pub rows: Vec<ShortRow<K>>,
pub stats: ShortsStats,
}
#[inline]
fn normalize_zero(v: f64) -> f64 {
if v == 0.0 {
0.0
} else {
v
}
}
struct NormalizedShort<K> {
key: K,
report_date: i32,
known_at_date: i32,
shares_short: f64,
net_change: Option<f64>,
pct_float: Option<f64>,
}
impl<K> NormalizedShort<K> {
#[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<K, I>(rows: I) -> Result<ShortsBuild<K>, ShortsError>
where
K: Ord + Clone,
I: IntoIterator<Item = CeoShortReport<K>>,
{
let iter = rows.into_iter();
let (lower, _) = iter.size_hint();
let mut stats = ShortsStats::default();
let mut valid: Vec<NormalizedShort<K>> = 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<ShortRow<K>> = 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<f64>,
pct_float: Option<f64>,
) -> CeoShortReport<String> {
CeoShortReport {
key: key.to_string(),
report_date,
shares_short,
net_change,
pct_float,
}
}
fn assert_invariants<K: Ord>(build: &ShortsBuild<K>) {
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::<String, _>(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 { .. }));
}
}

View file

@ -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="));
}

View file

@ -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<T>(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<u8> {
self.bytes.get(self.pos).copied()
}
fn parse_value(&mut self) -> Result<JsonVal, String> {
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<JsonVal, String> {
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<JsonVal, String> {
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<String, String> {
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<JsonVal, String> {
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::<f64>()
.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<K: Ord>(build: &EventsBuild<K>) {
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::<QmEarning<i32>>::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<i32> {
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::<i32, _, _>(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"));
}
}

View file

@ -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::<QmFiling<i32>>::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<i32> {
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<i32> {
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<char> = "0123456789-T: ESTDZé\u{00a0}2/".chars().collect();
let template: Vec<char> = "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::<QmEarning<i32>>::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::<QmFiling<i32>>::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::<QmFiling<i32>>::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)
}

View file

@ -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<T>(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<i32> = 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);
}

View file

@ -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<i32, FxDailyBar>, FxSourceStats) {
let mut stats = FxSourceStats {
rows_in: input.len(),
..FxSourceStats::default()
};
let mut groups: BTreeMap<i32, Vec<FxDailyBar>> = 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<i32> = 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<FxDailyBar>, Vec<FxDailyBar>) {
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<Fx1dRow> = 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<Fx1dRow> {
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}"
);
}
}

View file

@ -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<Bars1dParquetRow> {
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<i32> {
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<i64> {
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<Option<f64>> {
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<String> {
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<Option<f64>>| -> Vec<f64> {
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<String> {
fn walk(root: &Path, dir: &Path, out: &mut Vec<String>) {
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::<Vec<_>>(),
[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<String> = (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), &currencies[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<Bars1dParquetRow> {
(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<Bars1dParquetRow> {
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"));
}

View file

@ -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<i32>,
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<T>(&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<i32> {
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");
}
}

View file

@ -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<T>(&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<i32>,
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<i32> {
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<ProviderMappingTable, ProviderMappingError>) -> 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<Outcome> = 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<ProviderMappingRow>, 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<Outcome> = 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);
}

View file

@ -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<T>(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<K: Ord>(build: &ShortsBuild<K>) {
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<K: PartialEq + std::fmt::Debug>(a: &[ShortRow<K>], b: &[ShortRow<K>]) {
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::<i32, _>(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"));
}
}

View file

@ -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<i32> = 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);
}

View file

@ -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"
]
}